-
Notifications
You must be signed in to change notification settings - Fork 111
/
db.go
145 lines (122 loc) · 3.19 KB
/
db.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package pgdb
import (
"sort"
"time"
"github.com/go-gorp/gorp"
"github.com/gofrs/uuid"
_ "github.com/lib/pq"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/chef/automate/components/nodemanager-service/config"
"github.com/chef/automate/lib/db"
"github.com/chef/automate/lib/db/migrator"
"github.com/chef/automate/lib/logger"
)
type DB struct {
*gorp.DbMap
}
type DBTrans struct {
*gorp.Transaction
}
var validOrderFields = []string{"asc", "desc"}
func New(conf *config.Postgres) (*DB, error) {
connectionString := conf.ConnectionString
migrationsPath := conf.MigrationsPath
db, err := InitDB(connectionString)
if err != nil {
return nil, err
}
err = runMigrations(connectionString, migrationsPath)
if err != nil {
return nil, err
}
return db, nil
}
// Transact wraps your calls in a transaction. If the call should fail with an error it will
// perform a rollback. Otherwise the transaction will be committed.
func Transact(db *DB, txFunc func(*DBTrans) error) error {
trans, err := db.Begin()
if err != nil {
return errors.Wrap(err, "Unable to start transaction.")
}
tx := DBTrans{
Transaction: trans,
}
defer func() {
if err != nil {
tx.Rollback() // nolint: errcheck
} else {
err = tx.Commit()
if err != nil {
tx.Rollback() // nolint: errcheck
err = errors.Wrap(err, "Transaction failed and will be rolled back.")
}
}
}()
err = txFunc(&tx)
return err
}
func InitDB(connectionString string) (*DB, error) {
logrus.Debugf("Use PostgreSQL backend %s", connectionString)
sql, err := db.PGOpen(connectionString)
if err != nil {
return nil, errors.Wrapf(err, "Failed to open database with uri: %s", connectionString)
}
sql.SetMaxIdleConns(5)
// Check if the database exists
err = sql.Ping()
if err != nil {
return nil, errors.Wrapf(err, "Failed to ping database with uri: %s", connectionString)
}
db := &DB{
DbMap: &gorp.DbMap{
Db: sql,
Dialect: gorp.PostgresDialect{},
},
}
initTables(db.DbMap)
return db, nil
}
func runMigrations(connectionString string, migrationsPath string) error {
if err := migrator.Migrate(connectionString, migrationsPath,
logger.NewLogrusStandardLogger(), false,
); err != nil {
return errors.Wrapf(err, "Unable to complete database migrations")
}
return nil
}
func initTables(db *gorp.DbMap) {
// tell gorp about the tables.
// set auto-increment to false and tell it about our pk.
db.AddTableWithName(tag{}, "tags").SetKeys(false, "id")
db.AddTableWithName(node{}, "nodes").SetKeys(false, "id")
db.AddTableWithName(NodeTag{}, "nodes_tags")
db.AddTableWithName(NodeSecret{}, "nodes_secrets")
db.AddTableWithName(nodeManager{}, "node_managers").SetKeys(false, "id")
}
func createUUID() string {
return uuid.Must(uuid.NewV4()).String()
}
func valueOrDefaultStr(val string, def string) string {
if val == "" {
return def
}
return val
}
func valueOrDefaultInt(val int32, def int32) int32 {
if val == 0 {
return def
}
return val
}
func timeNowRef() time.Time {
return time.Now().UTC().Round(time.Second)
}
func getMapKeys(mapy map[string]string) []string {
keys := make([]string, 0, len(mapy))
for k := range mapy {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}