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 { /* Remove after first MEP */ version, err := migrate.Version(DB) if err != nil { return err } if version == 0 { return migrate.SetVersion(DB, 1) } /***/ mig := make([]migrate.Migration, 0) for _, migration := range migrations { mig = append(mig, migrate.Migration{ Version: migration.Version, Up: func(db orm.DB) error { for _, query := range migration.Up { _, err := db.Exec(query) if err != nil { return err } } return nil }, Down: func(db orm.DB) error { for _, query := range migration.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, }) }