[优化] 修复迁移

This commit is contained in:
ryan
2026-06-01 18:43:10 +08:00
parent 8f08a962e6
commit eed227b999
5 changed files with 117 additions and 6 deletions
+22
View File
@@ -123,9 +123,21 @@ func openDatabase() (*gorm.DB, string, error) {
}
func autoMigrateAll(db *gorm.DB) error {
return autoMigrateAllExcept(db, nil)
}
func autoMigrateAllExcept(db *gorm.DB, excludedTables map[string]bool) error {
models := registeredModels()
for i, item := range models {
name := fmt.Sprintf("%T", item)
tableName, err := tableNameForModel(item)
if err != nil {
return fmt.Errorf("resolve table name for %s failed: %w", name, err)
}
if excludedTables[tableName] {
slog.Info("autoMigrateAll: skipped model", "index", fmt.Sprintf("%d/%d", i+1, len(models)), "model", name, "table", tableName)
continue
}
slog.Info("autoMigrateAll: migrating model", "index", fmt.Sprintf("%d/%d", i+1, len(models)), "model", name)
if err := db.AutoMigrate(item); err != nil {
return fmt.Errorf("AutoMigrate %s failed: %w", name, err)
@@ -135,6 +147,16 @@ func autoMigrateAll(db *gorm.DB) error {
return nil
}
func tableNameForModel(item any) (string, error) {
namer := schema.NamingStrategy{}
cache := &sync.Map{}
parsed, err := schema.Parse(item, cache, namer)
if err != nil {
return "", err
}
return parsed.Table, nil
}
func isDatabaseEmpty(db *gorm.DB) (bool, error) {
models, err := buildDBModels()
if err != nil {