polish(database): 索引改名只在真正发生时打日志
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s

renameIndexTo 返回是否改动过;已对齐的库启动时完全静默。
This commit is contained in:
hermes
2026-11-21 22:48:56 +08:00
parent 1d4ad9bf54
commit 8acf72dd6e
2 changed files with 16 additions and 9 deletions
+3 -3
View File
@@ -725,13 +725,13 @@ func ensureDeviceSessionUniqueIndexName() {
if !DB.Migrator().HasTable("device_sessions") {
return
}
err := renameIndexTo("device_sessions", "idx_device_instance", "uni_device_sessions_instance_id", "instance_id")
renamed, err := renameIndexTo("device_sessions", "idx_device_instance", "uni_device_sessions_instance_id", "instance_id")
if err != nil {
log.Printf("[MIGRATE] device_sessions 唯一索引改名失败: %v", err)
return
}
if DB.Migrator().HasIndex("device_sessions", "uni_device_sessions_instance_id") {
log.Printf("[MIGRATE] device_sessions 唯一索引已对齐 uni_device_sessions_instance_id")
if renamed {
log.Printf("[MIGRATE] device_sessions 唯一索引已改名为 uni_device_sessions_instance_id")
}
}
+13 -6
View File
@@ -81,19 +81,26 @@ func hasColumn(table, column string) bool {
return ok
}
// renameIndexTo 幂等地把索引起到目标名(唯一索引需要给出唯一列)
func renameIndexTo(table, from, to, uniqueOn string) error {
// renameIndexTo 幂等地把索引起到目标名(唯一索引需要给出唯一列)。
// 返回是否真的改过名——调用方据此决定要不要打日志,避免每次启动都刷一行。
func renameIndexTo(table, from, to, uniqueOn string) (bool, error) {
if !DB.Migrator().HasIndex(table, from) {
return nil
return false, nil
}
if dialectName() == "mysql" {
return DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME INDEX %s TO %s", table, from, to)).Error
if err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME INDEX %s TO %s", table, from, to)).Error; err != nil {
return false, err
}
return true, nil
}
// sqlite 不支持重命名索引,删了重建
if err := DB.Exec(fmt.Sprintf("DROP INDEX IF EXISTS %s", from)).Error; err != nil {
return err
return false, err
}
return DB.Exec(fmt.Sprintf("CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s)", to, table, uniqueOn)).Error
if err := DB.Exec(fmt.Sprintf("CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s)", to, table, uniqueOn)).Error; err != nil {
return false, err
}
return true, nil
}
// ensureColumnType 确保列类型符合预期(只对能改类型的 MySQL 动手,sqlite 只做检查)