]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blob - db/db.go
63de87cee27d049e420b95733156c48b94dcf12f
[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
60 mig := make([]migrate.Migration, 0)
61
62 for _, migration := range migrations {
63 mig = append(mig, migrate.Migration{
64 Version: migration.Version,
65 Up: func(db orm.DB) error {
66 for _, query := range migration.Up {
67 _, err := db.Exec(query)
68 if err != nil {
69 return err
70 }
71 }
72
73 return nil
74 },
75 Down: func(db orm.DB) error {
76 for _, query := range migration.Down {
77 _, err := db.Exec(query)
78 if err != nil {
79 return err
80 }
81 }
82
83 return nil
84 },
85 })
86 }
87
88 oldVersion, newVersion, err := migrate.RunMigrations(DB, mig, "up")
89
90 if oldVersion != newVersion {
91 log.Infof("Migrate DB: %v -> %v", oldVersion, newVersion)
92 } else {
93 log.Infof("DB up-to-date: version '%v'", newVersion)
94 }
95 return err
96 }
97
98 func connect(config DBConfig) *pg.DB {
99 return pg.Connect(&pg.Options{
100 User: config.User,
101 Password: config.Password,
102 Database: config.Database,
103 Network: config.Type,
104 Addr: config.Address,
105 })
106 }