1 Star 0 Fork 15

TerryLiu/gosql

forked from fifsky/gosql 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
connection.go 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
fifsky 提交于 2019-10-16 16:19 . support postgres sql quotes,fix #15
package gosql
import (
"errors"
"log"
"strings"
"time"
"github.com/jmoiron/sqlx"
)
//defaultLink set database default link name
var defaultLink = "default"
//If database fatal exit
var FatalExit = true
var dbService = make(map[string]*sqlx.DB, 0)
// DB gets the specified database engine,
// or the default DB if no name is specified.
func Sqlx(name ...string) *sqlx.DB {
dbName := defaultLink
if name != nil {
dbName = name[0]
}
engine, ok := dbService[dbName]
if !ok {
log.Fatalf("[db] the database link `%s` is not configured", dbName)
}
return engine
}
// List gets the list of database engines
func List() map[string]*sqlx.DB {
return dbService
}
//Connect database
func Connect(configs map[string]*Config) (err error) {
var errs []string
defer func() {
if len(errs) > 0 {
err = errors.New("[db] " + strings.Join(errs, "\n"))
if FatalExit {
log.Fatal(err)
}
}
}()
for key, conf := range configs {
if !conf.Enable {
continue
}
sess, err := sqlx.Connect(conf.Driver, conf.Dsn)
if err != nil {
errs = append(errs, err.Error())
continue
}
log.Println("[db] connect:" + key)
if conf.ShowSql {
logger.SetLogging(true)
}
sess.SetMaxOpenConns(conf.MaxOpenConns)
sess.SetMaxIdleConns(conf.MaxIdleConns)
if conf.MaxLifetime > 0 {
sess.SetConnMaxLifetime(time.Duration(conf.MaxLifetime) * time.Second)
}
if db, ok := dbService[key]; ok {
_ = db.Close()
}
dbService[key] = sess
}
return
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tela2013/gosql.git
git@gitee.com:tela2013/gosql.git
tela2013
gosql
gosql
master

搜索帮助