-
Notifications
You must be signed in to change notification settings - Fork 45
/
db.go
79 lines (67 loc) · 1.74 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package models
import (
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type DBManager interface {
GetDB(dbType string) *gorm.DB
GetDefaultDB() *gorm.DB
SetDB(dbType string, db *gorm.DB)
RemoveDB(dbType string)
Init()
}
type dbManagerImpl struct {
DBs map[string]*gorm.DB // key: db type
defaultDBType string
}
func (dbm *dbManagerImpl) Init() {
for _, db := range dbm.DBs {
if err := db.AutoMigrate(&Client{}); err != nil {
logrus.WithError(err).Fatalf("cannot init db table [%s]", (&Client{}).TableName())
}
if err := db.AutoMigrate(&User{}); err != nil {
logrus.WithError(err).Fatalf("cannot init db table [%s]", (&User{}).TableName())
}
if err := db.AutoMigrate(&Server{}); err != nil {
logrus.WithError(err).Fatalf("cannot init db table [%s]", (&Server{}).TableName())
}
if err := db.AutoMigrate(&Cert{}); err != nil {
logrus.WithError(err).Fatalf("cannot init db table [%s]", (&Cert{}).TableName())
}
}
}
var (
dbm *dbManagerImpl
)
func MustInitDBManager(dbs map[string]*gorm.DB, defaultDBType string) {
if dbm == nil {
dbm = NewDBManager(dbs, defaultDBType)
}
}
func NewDBManager(dbs map[string]*gorm.DB, defaultDBType string) *dbManagerImpl {
if dbs == nil {
dbs = make(map[string]*gorm.DB)
}
return &dbManagerImpl{
DBs: dbs,
defaultDBType: defaultDBType,
}
}
func GetDBManager() DBManager {
if dbm == nil {
dbm = NewDBManager(nil, "")
}
return dbm
}
func (dbm *dbManagerImpl) GetDB(dbType string) *gorm.DB {
return dbm.DBs[dbType]
}
func (dbm *dbManagerImpl) SetDB(dbType string, db *gorm.DB) {
dbm.DBs[dbType] = db
}
func (dbm *dbManagerImpl) RemoveDB(dbType string) {
delete(dbm.DBs, dbType)
}
func (dbm *dbManagerImpl) GetDefaultDB() *gorm.DB {
return dbm.DBs[dbm.defaultDBType]
}