]>
Commit | Line | Data |
---|---|---|
1 | package db | |
2 | ||
3 | import ( | |
4 | migrate "github.com/go-pg/migrations" | |
5 | "github.com/go-pg/pg" | |
6 | "github.com/go-pg/pg/orm" | |
7 | "github.com/go-redis/redis" | |
8 | "github.com/jloup/utils" | |
9 | ) | |
10 | ||
11 | var log = utils.StandardL().WithField("module", "db") | |
12 | ||
13 | var ( | |
14 | DB *pg.DB | |
15 | Redis *redis.Client | |
16 | ) | |
17 | ||
18 | type DBConfig struct { | |
19 | Address string | |
20 | Database string | |
21 | User string | |
22 | Password string | |
23 | } | |
24 | ||
25 | type RedisConfig struct { | |
26 | Type string // tcp or unix | |
27 | Address string | |
28 | Password string | |
29 | } | |
30 | ||
31 | func Init(config DBConfig, redisConfig RedisConfig) { | |
32 | var err error | |
33 | ||
34 | DB = connect(config) | |
35 | ||
36 | err = migratedb() | |
37 | if err != nil { | |
38 | log.Fatalf("cannot migratedb '%v'\n", err) | |
39 | } | |
40 | ||
41 | Redis = redis.NewClient(&redis.Options{ | |
42 | Network: redisConfig.Type, | |
43 | Addr: redisConfig.Address, | |
44 | Password: redisConfig.Password, | |
45 | DB: 0, | |
46 | }) | |
47 | ||
48 | _, err = Redis.Ping().Result() | |
49 | ||
50 | if err != nil { | |
51 | log.Fatalf("redis init error %s", err) | |
52 | } | |
53 | ||
54 | } | |
55 | ||
56 | func migratedb() error { | |
57 | /* Remove after first MEP */ | |
58 | version, err := migrate.Version(DB) | |
59 | if err != nil { | |
60 | return err | |
61 | } | |
62 | ||
63 | if version == 0 { | |
64 | return migrate.SetVersion(DB, 1) | |
65 | } | |
66 | /***/ | |
67 | ||
68 | mig := make([]migrate.Migration, 0) | |
69 | ||
70 | for _, migration := range migrations { | |
71 | mig = append(mig, migrate.Migration{ | |
72 | Version: migration.Version, | |
73 | Up: func(db orm.DB) error { | |
74 | for _, query := range migration.Up { | |
75 | _, err := db.Exec(query) | |
76 | if err != nil { | |
77 | return err | |
78 | } | |
79 | } | |
80 | ||
81 | return nil | |
82 | }, | |
83 | Down: func(db orm.DB) error { | |
84 | for _, query := range migration.Down { | |
85 | _, err := db.Exec(query) | |
86 | if err != nil { | |
87 | return err | |
88 | } | |
89 | } | |
90 | ||
91 | return nil | |
92 | }, | |
93 | }) | |
94 | } | |
95 | ||
96 | oldVersion, newVersion, err := migrate.RunMigrations(DB, mig, "up") | |
97 | ||
98 | if oldVersion != newVersion { | |
99 | log.Infof("Migrate DB: %v -> %v", oldVersion, newVersion) | |
100 | } else { | |
101 | log.Infof("DB up-to-date: version '%v'", newVersion) | |
102 | } | |
103 | return err | |
104 | } | |
105 | ||
106 | func connect(config DBConfig) *pg.DB { | |
107 | return pg.Connect(&pg.Options{ | |
108 | User: config.User, | |
109 | Password: config.Password, | |
110 | Database: config.Database, | |
111 | Addr: config.Address, | |
112 | }) | |
113 | } |