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

92 lines
1.8 KiB
Go
Raw Normal View History

package database
import (
"github.com/mitchellh/mapstructure"
2023-03-15 11:34:15 +08:00
"matrix-middle-service/internel/controller/record/location/dto"
"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
2023-03-15 11:34:15 +08:00
GetLocationRecord(record *dto.GetDto) ([]*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
}