2023-02-26 21:10:43 +08:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
"github.com/mitchellh/mapstructure"
|
|
|
|
"matrix-middle-service/pkg/config"
|
|
|
|
"matrix-middle-service/pkg/database"
|
2023-02-26 21:20:11 +08:00
|
|
|
"matrix-middle-service/pkg/database/driver/mysql/conf"
|
2023-02-26 21:10:43 +08:00
|
|
|
"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 config.DataSourcesType[any]) database.DataBase {
|
|
|
|
mc := &conf.Config{}
|
|
|
|
_ = mapstructure.Decode(c.Config, &mc)
|
|
|
|
|
|
|
|
if dbEngine != nil {
|
|
|
|
_ = dbEngine.Close()
|
|
|
|
}
|
|
|
|
|
2023-02-26 21:34:53 +08:00
|
|
|
logger.Log().Debug("[mysql] 数据源初始化")
|
2023-02-26 21:10:43 +08:00
|
|
|
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 {
|
2023-02-26 21:34:53 +08:00
|
|
|
logger.Log().Debug("[mysql] 关闭数据库连接")
|
2023-02-26 21:10:43 +08:00
|
|
|
return d.db.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *db) Open() (err error) {
|
2023-02-26 21:34:53 +08:00
|
|
|
logger.Log().Debug("[mysql] 连接数据库")
|
2023-02-26 21:10:43 +08:00
|
|
|
// 自动创建数据库
|
|
|
|
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 {
|
2023-02-26 21:34:53 +08:00
|
|
|
logger.Log().Fatalf("[mysql] 数据库连接失败, %s", err)
|
2023-02-26 21:10:43 +08:00
|
|
|
}
|
2023-02-26 21:34:53 +08:00
|
|
|
logger.Log().Debug("[mysql] 数据库连接成功")
|
2023-02-26 21:10:43 +08:00
|
|
|
return
|
|
|
|
}
|