-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpostgres.go
67 lines (54 loc) · 1.81 KB
/
postgres.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package postgres
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"atomys.codes/webhooked/internal/valuable"
)
// storage is the struct contains client and config
// Run is made from external caller at begins programs
type storage struct {
client *sql.DB
config *config
}
// config is the struct contains config for connect client
// Run is made from internal caller
type config struct {
DatabaseURL valuable.Valuable `json:"databaseUrl"`
TableName string `json:"tableName"`
DataField string `json:"dataField"`
}
// NewStorage is the function for create new Postgres client storage
// Run is made from external caller at begins programs
// @param config contains config define in the webhooks yaml file
// @return PostgresStorage the struct contains client connected and config
// @return an error if the the client is not initialized successfully
func NewStorage(configRaw map[string]interface{}) (*storage, error) {
var err error
newClient := storage{
config: &config{},
}
if err := valuable.Decode(configRaw, &newClient.config); err != nil {
return nil, err
}
if newClient.client, err = sql.Open("postgres", newClient.config.DatabaseURL.First()); err != nil {
return nil, err
}
return &newClient, nil
}
// Name is the function for identified if the storage config is define in the webhooks
// Run is made from external caller
func (c storage) Name() string {
return "postgres"
}
// Push is the function for push data in the storage
// A run is made from external caller
// @param value that will be pushed
// @return an error if the push failed
func (c storage) Push(value interface{}) error {
request := fmt.Sprintf("INSERT INTO %s(%s) VALUES ($1)", c.config.TableName, c.config.DataField)
if _, err := c.client.Query(request, value); err != nil {
return err
}
return nil
}