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
|
package db
import (
migrate "github.com/go-pg/migrations"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"github.com/go-redis/redis"
"github.com/jloup/utils"
)
var log = utils.StandardL().WithField("module", "db")
var (
DB *pg.DB
Redis *redis.Client
)
type DBConfig struct {
Type string // tcp or unix
Address string
Database string
User string
Password string
}
type RedisConfig struct {
Type string // tcp or unix
Address string
Password string
Database int
}
func Init(config DBConfig, redisConfig RedisConfig) {
var err error
DB = connect(config)
err = migratedb()
if err != nil {
log.Fatalf("cannot migratedb '%v'\n", err)
}
Redis = redis.NewClient(&redis.Options{
Network: redisConfig.Type,
Addr: redisConfig.Address,
Password: redisConfig.Password,
DB: redisConfig.Database,
})
_, err = Redis.Ping().Result()
if err != nil {
log.Fatalf("redis init error %s", err)
}
}
func migratedb() error {
mig := make([]migrate.Migration, 0)
for i := range migrations {
index := i
mig = append(mig, migrate.Migration{
Version: migrations[index].Version,
Up: func(db orm.DB) error {
for _, query := range migrations[index].Up {
_, err := db.Exec(query)
if err != nil {
return err
}
}
return nil
},
Down: func(db orm.DB) error {
for _, query := range migrations[index].Down {
_, err := db.Exec(query)
if err != nil {
return err
}
}
return nil
},
})
}
oldVersion, newVersion, err := migrate.RunMigrations(DB, mig, "up")
if oldVersion != newVersion {
log.Infof("Migrate DB: %v -> %v", oldVersion, newVersion)
} else {
log.Infof("DB up-to-date: version '%v'", newVersion)
}
return err
}
func connect(config DBConfig) *pg.DB {
return pg.Connect(&pg.Options{
User: config.User,
Password: config.Password,
Database: config.Database,
Network: config.Type,
Addr: config.Address,
})
}
|