This commit is contained in:
@@ -3,6 +3,7 @@ package cool
|
||||
import (
|
||||
_ "blazing/contrib/drivers/pgsql"
|
||||
"blazing/cool/cooldb"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/v2/encoding/gjson"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
@@ -10,6 +11,11 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
autoMigrateMu sync.Mutex
|
||||
autoMigrateModels []IModel
|
||||
)
|
||||
|
||||
// 初始化数据库连接供gorm使用
|
||||
func InitDB(group string) (*gorm.DB, error) {
|
||||
// var ctx context.Context
|
||||
@@ -54,9 +60,33 @@ func getDBbyModel(model IModel) *gorm.DB {
|
||||
|
||||
// 根据entity结构体创建表
|
||||
func CreateTable(model IModel) error {
|
||||
if Config.AutoMigrate {
|
||||
autoMigrateMu.Lock()
|
||||
autoMigrateModels = append(autoMigrateModels, model)
|
||||
autoMigrateMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunAutoMigrate 显式执行已注册模型的建表/迁移。
|
||||
func RunAutoMigrate() error {
|
||||
if !Config.AutoMigrate {
|
||||
return nil
|
||||
}
|
||||
autoMigrateMu.Lock()
|
||||
models := append([]IModel(nil), autoMigrateModels...)
|
||||
autoMigrateMu.Unlock()
|
||||
|
||||
seen := make(map[string]struct{}, len(models))
|
||||
for _, model := range models {
|
||||
key := model.GroupName() + ":" + model.TableName()
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
|
||||
db := getDBbyModel(model)
|
||||
return db.AutoMigrate(model)
|
||||
if err := db.AutoMigrate(model); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user