1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
sql.go 1.66 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-01-04 11:47 . alarm 扩展
/**
* @author huqiuyun
* 数据服务
*/
package db
import (
"fmt"
"gitee.com/h79/goutils/common/logger"
"gitee.com/h79/goutils/common/result"
"gitee.com/h79/goutils/dao/config"
"gitee.com/h79/goutils/dao/option"
"gitee.com/h79/goutils/dao/util"
"go.uber.org/zap"
)
var _ SqlDatabase = (*sqlGroup)(nil)
type sqlGroup struct {
selectName string
dbMap map[string]*Adapter
}
func NewDB(cfgs []config.Sql, opts ...option.Option) (SqlDatabase, error) {
logger.L().Info("DB", zap.Any("Config", cfgs))
gr := &sqlGroup{dbMap: map[string]*Adapter{}}
for _, cfg := range cfgs {
ad, err := NewAdapter(&cfg, opts...)
if err != nil {
util.Alarm(result.ErrDbOpenInternal, "", fmt.Sprintf("Open %s DB failure server", cfg.Master.Name), err)
return nil, err
}
gr.dbMap[cfg.Name] = ad
}
return gr, nil
}
func (gr *sqlGroup) Do(dbname string, call func(db Sql) error) error {
if len(dbname) == 0 {
dbname = gr.selectName
}
db, exists := gr.dbMap[dbname]
if exists == true {
return call(db)
}
return result.Errorf(result.ErrDbExistInternal, "'%s' database not exist,please check config!", dbname)
}
func (gr *sqlGroup) Get(dbname string) (Sql, error) {
if len(dbname) == 0 {
dbname = gr.selectName
}
if db, exists := gr.dbMap[dbname]; exists == true {
return db, nil
}
return nil, result.Error(result.ErrNotFound, "Not found")
}
func (gr *sqlGroup) Close(dbname string) {
if len(dbname) == 0 {
dbname = gr.selectName
}
db, exists := gr.dbMap[dbname]
if exists == true {
db.Close()
}
}
func (gr *sqlGroup) CloseAll() {
for _, db := range gr.dbMap {
db.Close()
}
gr.dbMap = nil
}
func (gr *sqlGroup) Select(name string) {
gr.selectName = name
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.21.12

搜索帮助