]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blob - db/db.go
Allow to configure the type of Postgres connection (tcp or unix).
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / db / db.go
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 Type string // tcp or unix
20 Address string
21 Database string
22 User string
23 Password string
24 }
25
26 type RedisConfig struct {
27 Type string // tcp or unix
28 Address string
29 Password string
30 Database int
31 }
32
33 func Init(config DBConfig, redisConfig RedisConfig) {
34 var err error
35
36 DB = connect(config)
37
38 err = migratedb()
39 if err != nil {
40 log.Fatalf("cannot migratedb '%v'\n", err)
41 }
42
43 Redis = redis.NewClient(&redis.Options{
44 Network: redisConfig.Type,
45 Addr: redisConfig.Address,
46 Password: redisConfig.Password,
47 DB: redisConfig.Database,
48 })
49
50 _, err = Redis.Ping().Result()
51
52 if err != nil {
53 log.Fatalf("redis init error %s", err)
54 }
55
56 }
57
58 func migratedb() error {
59 /* Remove after first MEP */
60 version, err := migrate.Version(DB)
61 if err != nil {
62 return err
63 }
64
65 if version == 0 {
66 return migrate.SetVersion(DB, 1)
67 }
68 /***/
69
70 mig := make([]migrate.Migration, 0)
71
72 for _, migration := range migrations {
73 mig = append(mig, migrate.Migration{
74 Version: migration.Version,
75 Up: func(db orm.DB) error {
76 for _, query := range migration.Up {
77 _, err := db.Exec(query)
78 if err != nil {
79 return err
80 }
81 }
82
83 return nil
84 },
85 Down: func(db orm.DB) error {
86 for _, query := range migration.Down {
87 _, err := db.Exec(query)
88 if err != nil {
89 return err
90 }
91 }
92
93 return nil
94 },
95 })
96 }
97
98 oldVersion, newVersion, err := migrate.RunMigrations(DB, mig, "up")
99
100 if oldVersion != newVersion {
101 log.Infof("Migrate DB: %v -> %v", oldVersion, newVersion)
102 } else {
103 log.Infof("DB up-to-date: version '%v'", newVersion)
104 }
105 return err
106 }
107
108 func connect(config DBConfig) *pg.DB {
109 return pg.Connect(&pg.Options{
110 User: config.User,
111 Password: config.Password,
112 Database: config.Database,
113 Network: config.Type,
114 Addr: config.Address,
115 })
116 }