4 migrate "github.com/go-pg/migrations"
6 "github.com/go-pg/pg/orm"
7 "github.com/go-redis/redis"
8 "github.com/jloup/utils"
11 var log = utils.StandardL().WithField("module", "db")
18 type DBConfig struct {
19 Type string // tcp or unix
26 type RedisConfig struct {
27 Type string // tcp or unix
33 func Init(config DBConfig, redisConfig RedisConfig) {
40 log.Fatalf("cannot migratedb '%v'\n", err)
43 Redis = redis.NewClient(&redis.Options{
44 Network: redisConfig.Type,
45 Addr: redisConfig.Address,
46 Password: redisConfig.Password,
47 DB: redisConfig.Database,
50 _, err = Redis.Ping().Result()
53 log.Fatalf("redis init error %s", err)
58 func migratedb() error {
60 mig := make([]migrate.Migration, 0)
62 for i := range migrations {
64 mig = append(mig, migrate.Migration{
65 Version: migrations[index].Version,
66 Up: func(db orm.DB) error {
67 for _, query := range migrations[index].Up {
68 _, err := db.Exec(query)
76 Down: func(db orm.DB) error {
77 for _, query := range migrations[index].Down {
78 _, err := db.Exec(query)
89 oldVersion, newVersion, err := migrate.RunMigrations(DB, mig, "up")
91 if oldVersion != newVersion {
92 log.Infof("Migrate DB: %v -> %v", oldVersion, newVersion)
94 log.Infof("DB up-to-date: version '%v'", newVersion)
99 func connect(config DBConfig) *pg.DB {
100 return pg.Connect(&pg.Options{
102 Password: config.Password,
103 Database: config.Database,
104 Network: config.Type,
105 Addr: config.Address,