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
|
package db
import (
"fmt"
"strings"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"github.com/jloup/utils"
)
var DB *pg.DB
var log = utils.StandardL().WithField("module", "db")
type DBConfig struct {
Address string
Database string
User string
Password string
}
func Init(config DBConfig) {
var err error
DB = connect(config)
err = createSchema(DB)
if err != nil {
log.Errorf("cannot create schemas %v\n", err)
}
err = createIndexes(DB)
if err != nil {
log.Errorf("cannot create indexes %v\n", err)
}
}
func connect(config DBConfig) *pg.DB {
return pg.Connect(&pg.Options{
User: config.User,
Password: config.Password,
Database: config.Database,
Addr: config.Address,
})
}
func createSchema(db *pg.DB) error {
for _, model := range []interface{}{&User{}, &MarketConfig{}} {
err := db.CreateTable(model, &orm.CreateTableOptions{IfNotExists: true})
if err != nil {
return err
}
}
return nil
}
func createIndexes(db *pg.DB) error {
indexes := []struct {
TableName string
Name string
Columns []string
}{
{"market_configs", "market_name_user_id_idx", []string{"user_id", "market_name"}},
}
for _, index := range indexes {
_, err := db.Exec(fmt.Sprintf("CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s (%s)", index.Name, index.TableName, strings.Join(index.Columns, ",")))
if err != nil {
return err
}
}
return nil
}
|