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

91 lines
2.0 KiB
Go

package mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/mitchellh/mapstructure"
database2 "matrix-middle-service/pkg/config/database"
"matrix-middle-service/pkg/database"
"matrix-middle-service/pkg/database/driver/mysql/conf"
"matrix-middle-service/pkg/database/model"
"matrix-middle-service/pkg/logger"
fib "matrix-middle-service/pkg/utils/fiber"
"strings"
"xorm.io/xorm"
)
var dbEngine *xorm.EngineGroup
var dbInst *db
func init() {
// 初始化数据源
fib.Exec(func() {
logger.Log().Debug("添加 mysql 数据源支持")
})
database.Register("mysql", func(c database2.DataSourcesType[any]) database.DataBase {
mc := &conf.Config{}
_ = mapstructure.Decode(c.Config, &mc)
if dbEngine != nil {
_ = dbEngine.Close()
}
logger.Log().Debug("[mysql] 数据源初始化")
var err error
dbEngine, err = xorm.NewEngineGroup("mysql", mc.DataSources)
if err != nil {
logger.Log().Fatal(err)
}
dbInst = &db{
db: dbEngine,
config: mc,
}
return dbInst
})
}
type db struct {
db *xorm.EngineGroup
config *conf.Config
}
func (d *db) Close() error {
logger.Log().Debug("[mysql] 关闭数据库连接")
return d.db.Close()
}
func (d *db) Open() (err error) {
logger.Log().Debug("[mysql] 连接数据库")
// 自动创建数据库
for _, dsn := range d.config.DataSources {
dbName := ParseSqlConnDBName(dsn)
conn, err := sql.Open("mysql", strings.Split(dsn, "/")[0]+"/information_schema?charset=utf8mb4")
_, err = conn.Query(fmt.Sprintf("Create Database If Not Exists %s Character Set utf8mb4;", dbName))
if err != nil {
logger.Log().Fatal(err)
}
}
err = d.db.Ping()
if err != nil {
logger.Log().Fatalf("[mysql] 数据库连接失败, %s", err)
}
logger.Log().Debug("[mysql] 数据库 连接成功")
err = d.db.Sync2(
&model.QQBot{},
&model.WebHook{},
&model.BotType{},
&model.BotAccess{})
if err != nil {
logger.Log().Fatal(err)
}
logger.Log().Debug("[mysql] 数据表 同步成功")
return
}