polish(database): 索引改名只在真正发生时打日志
renameIndexTo 返回是否改动过;已对齐的库启动时完全静默。
This commit is contained in:
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 只做检查)
|
||||
|
||||
Reference in New Issue
Block a user