1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
sql.go 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-11-24 23:56 . db tls
/**
* @author huqiuyun
* 数据服务
*/
package db
import (
"context"
"gitee.com/h79/goutils/common/debug"
"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/plugins"
"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 {
d := debug.New(result.ErrDbOpenInternal).
WithDetailFormat("Open %s DB failure server", cfg.Master.Name).
WithError(err).
WithLevel(debug.DFatalLevel)
_ = plugins.DoWithError(plugins.KAlarm, context.Background(), d)
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.10.0

搜索帮助

A270a887 8829481 3d7a4017 8829481