/
default.go
66 lines (53 loc) · 1.65 KB
/
default.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
package golug_db
import (
"os"
"path/filepath"
"strings"
"github.com/pubgo/dix"
"github.com/pubgo/golug/golug_app"
"github.com/pubgo/golug/golug_config"
"github.com/pubgo/golug/golug_consts"
"github.com/pubgo/golug/golug_types"
"github.com/pubgo/golug/pkg/golug_utils"
"github.com/pubgo/xerror"
"xorm.io/xorm"
xl "xorm.io/xorm/log"
"xorm.io/xorm/names"
)
var clientMap = golug_types.NewSyncMap()
func Get(names ...string) *xorm.Engine {
var name = golug_consts.Default
if len(names) > 0 && names[0] != "" {
name = names[0]
}
xerror.Assert(!clientMap.Has(name), "[db] %s not found", name)
return clientMap.Get(name).(*xorm.Engine)
}
func List() (dt map[string]*xorm.Engine) { clientMap.Map(&dt); return }
func initClient(name string, cfg Cfg) {
source := golug_config.Template(cfg.Source)
if strings.Contains(cfg.Driver, "sqlite") {
if _dir := filepath.Dir(source); !golug_utils.PathExist(_dir) {
_ = os.MkdirAll(_dir, 0755)
}
}
engine := xerror.PanicErr(xorm.NewEngine(cfg.Driver, source)).(*xorm.Engine)
engine.SetMaxOpenConns(cfg.MaxConnOpen)
engine.SetMaxIdleConns(cfg.MaxConnIdle)
engine.SetConnMaxLifetime(cfg.MaxConnTime)
engine.SetMapper(names.LintGonicMapper)
engine.Logger().SetLevel(xl.LOG_WARNING)
if golug_app.IsDev() || golug_app.IsTest() {
engine.Logger().SetLevel(xl.LOG_DEBUG)
}
xerror.Panic(engine.DB().Ping())
if val, ok := clientMap.Load(name); ok {
_ = val.(*xorm.Engine).Close()
}
clientMap.Set(name, engine)
// 初始化完毕之后, 更新到对象管理系统
updateEngine(name, engine)
}
func updateEngine(name string, engine *xorm.Engine) {
xerror.Panic(dix.Dix(map[string]*xorm.Engine{name: engine}))
}