sk-matrix-project/backend/golang/matrix-middle-service/pkg/database/database.go
Shikong c5c3633ac4 添加 数据源配置
数据源初始化
多数据源初步支持
2023-02-26 21:10:43 +08:00

54 lines
1017 B
Go

package database
import (
"github.com/mitchellh/mapstructure"
"matrix-middle-service/pkg/config"
"matrix-middle-service/pkg/logger"
)
var SupportDataSources = make(map[string]InitDSFn)
var drivers []DataBase
type InitDSFn = func(conf config.DataSourcesType[any]) DataBase
type DataBase interface {
Open() error
Close() error
}
func Init(conf []interface{}) {
drivers = make([]DataBase, 0, len(SupportDataSources))
logger.Log().Debug("[数据源] 初始化")
for _, item := range conf {
dst := config.DataSourcesType[any]{}
_ = mapstructure.Decode(item, &dst)
logger.Log().Infof("%+v", dst)
fn, ok := SupportDataSources[dst.Type]
if !ok {
logger.Log().Fatalf("不支持的数据源类型 %s", dst.Type)
}
if !dst.Enable {
continue
}
drivers = append(drivers, fn(dst))
}
}
func Register(name string, fn InitDSFn) {
SupportDataSources[name] = fn
}
func Open() (err error) {
for _, driver := range drivers {
err = driver.Open()
if err != nil {
return
}
}
return
}