-
Notifications
You must be signed in to change notification settings - Fork 13
/
store_postgres.go
100 lines (77 loc) · 2.01 KB
/
store_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package store
import (
"database/sql"
"strconv"
)
type postgresStore struct {
dbProvider DbProvider
}
func NewPostgresStore(dbProvider DbProvider) Store {
return postgresStore{dbProvider}
}
func (ps postgresStore) Put(name string, value string, checksum string) (string, error) {
db, err := ps.dbProvider.Db()
if err != nil {
return "", err
}
var id int
err = db.QueryRow("INSERT INTO configurations (name, value, checksum) VALUES($1, $2, $3) RETURNING id", name, value, checksum).Scan(&id)
if err != nil {
return "", err
}
return strconv.Itoa(int(id)), err
}
func (ps postgresStore) GetByName(name string) (Configurations, error) {
var results Configurations
db, err := ps.dbProvider.Db()
if err != nil {
return results, err
}
rows, err := db.Query("SELECT id, name, value, checksum FROM configurations WHERE name = $1 ORDER BY id DESC", name)
if err != nil {
if err == sql.ErrNoRows {
return results, nil
}
return results, err
}
defer rows.Close()
for rows.Next() {
var config Configuration
if err := rows.Scan(&config.ID, &config.Name, &config.Value, &config.ParameterChecksum); err != nil {
return results, err
}
results = append(results, config)
}
return results, err
}
func (ps postgresStore) GetByID(id string) (Configuration, error) {
result := Configuration{}
_, err := strconv.Atoi(id)
if err != nil {
return result, nil
}
db, err := ps.dbProvider.Db()
if err != nil {
return result, err
}
err = db.QueryRow("SELECT id, name, value, checksum FROM configurations WHERE id = $1", id).Scan(&result.ID, &result.Name, &result.Value, &result.ParameterChecksum)
if err == sql.ErrNoRows {
return result, nil
}
return result, err
}
func (ps postgresStore) Delete(name string) (int, error) {
db, err := ps.dbProvider.Db()
if err != nil {
return 0, err
}
result, err := db.Exec("DELETE FROM configurations WHERE name = $1", name)
if err != nil {
return 0, err
}
if result != nil {
rows, err := result.RowsAffected()
return int(rows), err
}
return 0, err
}