beegoinit/db/db.go

80 lines
1.6 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"`
}
func (d *DbItem) Dsn() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&loc=Local&autocommit=true&timeout=5s", d.User, d.Pass, d.Host, d.Port, d.Name)
}
func init() {
Reload()
}
func Reload(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)
if err = LoadXorm(dsns); err != nil {
logger.Critical(err.Error())
}
}
func GetDsn(configer *grconfig.Configer) (DsnList map[string]dsnConfig, err error) {
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
}