2020-07-02 15:59:04 +08:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"golib.gaore.com/GaoreGo/grconfig"
|
|
|
|
"golib.gaore.com/GaoreGo/grlogs"
|
2020-07-06 11:29:59 +08:00
|
|
|
"path"
|
2020-07-02 15:59:04 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const DEFAULT = "default"
|
|
|
|
|
|
|
|
var DbPrefix map[string]string = make(map[string]string)
|
|
|
|
|
|
|
|
type dsnConfig struct {
|
|
|
|
Dsn string
|
|
|
|
Driver string
|
|
|
|
Item *DbItem
|
|
|
|
}
|
|
|
|
|
|
|
|
type DbItem struct {
|
2020-08-11 14:31:27 +08:00
|
|
|
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"`
|
2020-07-02 15:59:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *DbItem) Dsn() string {
|
2020-08-11 14:31:27 +08:00
|
|
|
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)
|
2020-07-02 15:59:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
2020-07-06 11:29:59 +08:00
|
|
|
Reload()
|
|
|
|
}
|
2020-07-02 15:59:04 +08:00
|
|
|
|
2020-07-06 11:29:59 +08:00
|
|
|
func Reload(dir ...string) {
|
2020-07-02 15:59:04 +08:00
|
|
|
var err error
|
2020-07-06 11:29:59 +08:00
|
|
|
var configer *grconfig.Configer
|
2020-07-02 15:59:04 +08:00
|
|
|
logger := grlogs.GetAli("sql")
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
logger.Critical(err.Error())
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-07-06 11:29:59 +08:00
|
|
|
if len(dir) == 0 {
|
|
|
|
configer = grconfig.New("conf/")
|
|
|
|
} else {
|
|
|
|
dir = append(dir, "conf/")
|
|
|
|
configer = grconfig.New(path.Join(dir...))
|
|
|
|
}
|
|
|
|
dsns, err := GetDsn(configer)
|
2020-07-02 15:59:04 +08:00
|
|
|
if err = LoadXorm(dsns); err != nil {
|
|
|
|
logger.Critical(err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-06 11:29:59 +08:00
|
|
|
func GetDsn(configer *grconfig.Configer) (DsnList map[string]dsnConfig, err error) {
|
2020-07-02 15:59:04 +08:00
|
|
|
var items map[string]*DbItem
|
|
|
|
DsnList = make(map[string]dsnConfig)
|
|
|
|
err = configer.Item("db", &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
|
|
|
|
}
|