/
mysql.go
58 lines (46 loc) · 1.14 KB
/
mysql.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
package model
import (
"log"
"path"
"time"
"xorm.io/xorm"
xormLog "xorm.io/xorm/log"
"github.com/toolkits/pkg/file"
"github.com/toolkits/pkg/runner"
)
type MySQLConf struct {
Addr string `yaml:"addr"`
Max int `yaml:"max"`
Idle int `yaml:"idle"`
Debug bool `yaml:"debug"`
}
var DB = map[string]*xorm.Engine{}
func InitMySQL(names ...string) {
confdir := path.Join(runner.Cwd, "etc")
mysqlYml := path.Join(confdir, "mysql.local.yml")
if !file.IsExist(mysqlYml) {
mysqlYml = path.Join(confdir, "mysql.yml")
}
confs := make(map[string]MySQLConf)
err := file.ReadYaml(mysqlYml, &confs)
if err != nil {
log.Fatalf("cannot read yml[%s]: %v", mysqlYml, err)
}
count := len(names)
for i := 0; i < count; i++ {
conf, has := confs[names[i]]
if !has {
log.Fatalf("no such mysql conf: %s", names[i])
}
db, err := xorm.NewEngine("mysql", conf.Addr)
if err != nil {
log.Fatalf("cannot connect mysql[%s]: %v", conf.Addr, err)
}
db.SetMaxIdleConns(conf.Idle)
db.SetMaxOpenConns(conf.Max)
db.SetConnMaxLifetime(time.Hour)
db.ShowSQL(conf.Debug)
db.Logger().SetLevel(xormLog.LOG_INFO)
DB[names[i]] = db
}
}