/
manager.go
193 lines (168 loc) · 5.32 KB
/
manager.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package db
import (
"fmt"
"github.com/abolfazlbeh/zhycan/internal/config"
"github.com/abolfazlbeh/zhycan/internal/utils"
"go.mongodb.org/mongo-driver/mongo"
"gorm.io/gorm"
"log"
"reflect"
"strings"
"sync"
)
// Mark: manager
// manager object
type manager struct {
name string
lock sync.Mutex
sqliteDbInstances map[string]*SqlWrapper[Sqlite]
mysqlDbInstances map[string]*SqlWrapper[Mysql]
postgresDbInstances map[string]*SqlWrapper[Postgresql]
mongoDbInstances map[string]*MongoWrapper
supportedDBs []string
isManagerInitialized bool
}
// MARK: Module variables
var managerInstance *manager = nil
var once sync.Once
// Module init function
func init() {
log.Println("DB Manager Package Initialized...")
}
// init - Manager Constructor - It initializes the manager configuration params
func (m *manager) init() {
m.name = "db"
m.isManagerInitialized = false
m.lock.Lock()
defer m.lock.Unlock()
m.supportedDBs = []string{"sqlite", "mysql", "postgresql", "mongodb"}
// read configs
connectionsObj, err := config.GetManager().Get(m.name, "connections")
if err != nil {
return
}
m.sqliteDbInstances = make(map[string]*SqlWrapper[Sqlite])
m.mysqlDbInstances = make(map[string]*SqlWrapper[Mysql])
m.postgresDbInstances = make(map[string]*SqlWrapper[Postgresql])
m.mongoDbInstances = make(map[string]*MongoWrapper)
for _, item := range connectionsObj.([]interface{}) {
dbInstanceName := item.(string)
dbTypeKey := fmt.Sprintf("%s.%s", dbInstanceName, "type")
dbTypeInf, err := config.GetManager().Get(m.name, dbTypeKey)
if err != nil {
continue
}
// create a new instance based on type
dbType := strings.ToLower(dbTypeInf.(string))
if utils.ArrayContains(&m.supportedDBs, dbType) {
switch dbType {
case "sqlite":
obj, err := NewSqlWrapper[Sqlite](fmt.Sprintf("db/%s", dbInstanceName), dbType)
if err != nil {
// TODO: log error here
continue
}
m.sqliteDbInstances[dbInstanceName] = reflect.ValueOf(obj).Interface().(*SqlWrapper[Sqlite])
break
case "mysql":
obj, err := NewSqlWrapper[Mysql](fmt.Sprintf("db/%s", dbInstanceName), dbType)
if err != nil {
// TODO: log error here
continue
}
m.mysqlDbInstances[dbInstanceName] = reflect.ValueOf(obj).Interface().(*SqlWrapper[Mysql])
break
case "postgresql":
obj, err := NewSqlWrapper[Postgresql](fmt.Sprintf("db/%s", dbInstanceName), dbType)
if err != nil {
// TODO: log error here
continue
}
m.postgresDbInstances[dbInstanceName] = reflect.ValueOf(obj).Interface().(*SqlWrapper[Postgresql])
break
case "mongodb":
obj, err := NewMongoWrapper(fmt.Sprintf("db/%s", dbInstanceName))
if err != nil {
// TODO: log error here
continue
}
m.mongoDbInstances[dbInstanceName] = obj
}
}
}
m.isManagerInitialized = true
}
// restartOnChangeConfig - subscribe a function for when the config is changed
func (m *manager) restartOnChangeConfig() {
// Config config server to reload
wrapper, err := config.GetManager().GetConfigWrapper(m.name)
if err == nil {
wrapper.RegisterChangeCallback(func() interface{} {
if m.isManagerInitialized {
m.init()
}
return nil
})
} else {
// TODO: make some logs
}
}
// MARK: Public Functions
// GetManager - This function returns singleton instance of Db Manager
func GetManager() *manager {
// once used for prevent race condition and manage critical section.
once.Do(func() {
managerInstance = &manager{}
managerInstance.init()
managerInstance.restartOnChangeConfig()
})
return managerInstance
}
// GetDb - Get *gorm.DB instance from the underlying interfaces
func (m *manager) GetDb(instanceName string) (*gorm.DB, error) {
if m.isManagerInitialized {
if v, ok := m.sqliteDbInstances[instanceName]; ok {
return v.GetDb()
} else if v, ok := m.mysqlDbInstances[instanceName]; ok {
return v.GetDb()
} else if v, ok := m.postgresDbInstances[instanceName]; ok {
return v.GetDb()
}
}
return nil, NewNotExistServiceNameErr(instanceName)
}
// GetMongoDb - Get *mongo.Client instance from the underlying interfaces
func (m *manager) GetMongoDb(instanceName string) (*mongo.Client, error) {
if m.isManagerInitialized {
if v, ok := m.mongoDbInstances[instanceName]; ok {
return v.GetDb()
}
}
return nil, NewNotExistServiceNameErr(instanceName)
}
// Migrate - migrate models on specific database
func (m *manager) Migrate(instanceName string, models ...interface{}) error {
if m.isManagerInitialized {
if v, ok := m.sqliteDbInstances[instanceName]; ok {
return v.Migrate(models)
} else if v, ok := m.mysqlDbInstances[instanceName]; ok {
return v.Migrate(models)
} else if v, ok := m.postgresDbInstances[instanceName]; ok {
return v.Migrate(models)
}
}
return NewNotExistServiceNameErr(instanceName)
}
// AttachMigrationFunc - attach migration function to be called by end user
func (m *manager) AttachMigrationFunc(instanceName string, f func(migrator gorm.Migrator) error) error {
if m.isManagerInitialized {
if v, ok := m.sqliteDbInstances[instanceName]; ok {
return v.AttachMigrationFunc(f)
} else if v, ok := m.mysqlDbInstances[instanceName]; ok {
return v.AttachMigrationFunc(f)
} else if v, ok := m.postgresDbInstances[instanceName]; ok {
return v.AttachMigrationFunc(f)
}
}
return NewNotExistServiceNameErr(instanceName)
}