moto/common/db/db.go

59 lines
1.3 KiB
Go

package db
import (
"context"
"git.nobla.cn/golang/moto/config"
"git.nobla.cn/golang/rest/types"
"github.com/go-sql-driver/mysql"
mysqlDriver "gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
var (
db *gorm.DB
)
func Init(ctx context.Context, cfg config.Database, plugins ...gorm.Plugin) (err error) {
dbCfg := &mysql.Config{
Net: "tcp",
Addr: cfg.Address,
User: cfg.Username,
Passwd: cfg.Password,
DBName: cfg.Database,
AllowNativePasswords: true,
AllowOldPasswords: true,
Collation: "utf8mb4_unicode_ci",
Loc: time.Local,
CheckConnLiveness: true,
Params: make(map[string]string),
ParseTime: true,
MaxAllowedPacket: 4 << 20,
}
dbCfg.Params["charset"] = "utf8mb4"
if db, err = gorm.Open(mysqlDriver.Open(dbCfg.FormatDSN())); err != nil {
return
}
db = db.WithContext(ctx)
for _, plugin := range plugins {
if err = db.Use(plugin); err != nil {
return
}
}
if err = db.AutoMigrate(&types.Schema{}); err != nil {
return
}
return
}
func DB() *gorm.DB {
if db == nil {
panic("database component not initialized")
}
return db
}
func WithContext(ctx context.Context) *gorm.DB {
return DB().WithContext(ctx)
}