59018c5269
2.初始化加入可选文件载入,可自定义加载所需的数据库文件
104 lines
2.2 KiB
Go
104 lines
2.2 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
_ "github.com/go-sql-driver/mysql"
|
|
_ "github.com/lib/pq"
|
|
"golib.gaore.com/GaoreGo/grconfig"
|
|
"golib.gaore.com/GaoreGo/grlogs"
|
|
"path"
|
|
)
|
|
|
|
const DEFAULT = "default"
|
|
|
|
var DbPrefix map[string]string = make(map[string]string)
|
|
|
|
type dsnConfig struct {
|
|
Dsn string
|
|
Driver string
|
|
Item *DbItem
|
|
}
|
|
|
|
type DbItem struct {
|
|
User string `yaml:"user"`
|
|
Pass string `yaml:"pass"`
|
|
Host string `yaml:"host"`
|
|
Port int `yaml:"port"`
|
|
Name string `yaml:"name"`
|
|
Driver string `yaml:"driver"`
|
|
Prefix string `yaml:"prefix"`
|
|
MaxIdleConns int `yaml:"max_idle_conns"`
|
|
MaxOpenConns int `yaml:"max_open_conns"`
|
|
ConnMaxLifetime int64 `yaml:"conn_max_lifetime"`
|
|
Timeout int `yaml:"timeout"`
|
|
}
|
|
|
|
func (d *DbItem) Dsn() string {
|
|
if d.Timeout <= 0 {
|
|
d.Timeout = 5
|
|
}
|
|
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&loc=Local&autocommit=true&timeout=%ds", d.User, d.Pass, d.Host, d.Port, d.Name, d.Timeout)
|
|
}
|
|
|
|
func init() {
|
|
// Reload() 不再自动链接数据库了, 需要自己手动
|
|
}
|
|
|
|
func ReloadByDefault() {
|
|
Reload(nil)
|
|
}
|
|
|
|
func Reload(files []string, dir ...string) {
|
|
var err error
|
|
var configer *grconfig.Configer
|
|
logger := grlogs.GetAli("sql")
|
|
|
|
defer func() {
|
|
if err != nil {
|
|
logger.Critical(err.Error())
|
|
}
|
|
}()
|
|
|
|
if len(dir) == 0 {
|
|
configer = grconfig.New("conf/")
|
|
} else {
|
|
dir = append(dir, "conf/")
|
|
configer = grconfig.New(path.Join(dir...))
|
|
}
|
|
dsns, err := GetDsn(configer, files...)
|
|
if err = LoadXorm(dsns); err != nil {
|
|
logger.Critical(err.Error())
|
|
}
|
|
}
|
|
|
|
func GetDsn(configer *grconfig.Configer, dbfiles ...string) (DsnList map[string]dsnConfig, err error) {
|
|
var items map[string]*DbItem
|
|
DsnList = make(map[string]dsnConfig)
|
|
|
|
if nil == dbfiles || len(dbfiles) == 0 {
|
|
dbfiles = []string{"db"}
|
|
}
|
|
|
|
for _, dbfile := range dbfiles {
|
|
|
|
if dbfile == "" {
|
|
continue
|
|
}
|
|
|
|
err = configer.Item(dbfile, &items)
|
|
if err != nil {
|
|
return
|
|
}
|
|
for alias, v := range items {
|
|
dsn := v.Dsn()
|
|
driver := v.Driver
|
|
if driver == "" {
|
|
driver = "mysql"
|
|
}
|
|
DsnList[alias] = dsnConfig{Dsn: dsn, Driver: driver, Item: v}
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|