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, }) }