54 lines
1017 B
Go
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
|
|
}
|