sk-matrix-project/backend/golang/matrix-middle-service/pkg/database/database.go

90 lines
1.7 KiB
Go
Raw Normal View History

package database
import (
"github.com/mitchellh/mapstructure"
"matrix-middle-service/pkg/config/database"
2023-02-27 17:18:31 +08:00
"matrix-middle-service/pkg/database/model"
"matrix-middle-service/pkg/logger"
)
var SupportDataSources = make(map[string]InitDSFn)
var drivers []DataBase
type InitDSFn = func(conf database.DataSourcesType[any]) DataBase
type DataBase interface {
Open() error
Close() error
2023-02-27 17:18:31 +08:00
GetAllBotTypes() ([]*model.BotType, error)
2023-02-28 00:03:02 +08:00
AddBotType(bt *model.BotType) error
DeleteBotTypeById(id string) error
2023-03-14 20:19:38 +08:00
RecordLocation(record *model.LocationRecord) error
}
func Init(conf []interface{}) {
drivers = make([]DataBase, 0, len(SupportDataSources))
logger.Log().Debug("[数据源] 初始化")
for _, item := range conf {
dst := database.DataSourcesType[any]{}
_ = mapstructure.Decode(item, &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
}
2023-02-26 21:34:53 +08:00
2023-02-27 17:18:31 +08:00
func Exec(fn func(db DataBase) error) error {
if len(drivers) > 0 {
return fn(drivers[0])
} else {
logger.Log().Error("[database] 没有可用的数据源")
}
return nil
}
func ExecMulti(fn func(db DataBase) error) error {
if len(drivers) == 0 {
logger.Log().Error("[database] 没有可用的数据源")
}
for _, driver := range drivers {
err := fn(driver)
if err != nil {
return err
}
}
return nil
}
2023-02-26 21:34:53 +08:00
func Close() {
for _, driver := range drivers {
_ = driver.Close()
}
return
}