12619aa4ab
- Implemented repairSmokeAIAdviceIndexes to manage the unique index for fa_smoke_ai_advice. - Added unit tests for the new function to ensure correct index recreation and validation. - Updated AutoMigrate to include the new index repair function.
103 lines
2.3 KiB
Go
103 lines
2.3 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type mysqlIndexColumn struct {
|
|
KeyName string `gorm:"column:Key_name"`
|
|
SeqInIndex int `gorm:"column:Seq_in_index"`
|
|
ColumnName string `gorm:"column:Column_name"`
|
|
}
|
|
|
|
func repairSmokeAINextSmokeIndexes(db *gorm.DB) error {
|
|
if db == nil {
|
|
return nil
|
|
}
|
|
|
|
const (
|
|
tableName = "fa_smoke_ai_next_smoke"
|
|
indexName = "uniq_smoke_ai_next_node"
|
|
)
|
|
|
|
var rows []mysqlIndexColumn
|
|
if err := db.Raw(fmt.Sprintf("SHOW INDEX FROM `%s` WHERE Key_name = ?", tableName), indexName).Scan(&rows).Error; err != nil {
|
|
return fmt.Errorf("inspect %s: %w", indexName, err)
|
|
}
|
|
|
|
expected := []string{"ai_advice_id", "node_type", "node_at"}
|
|
actual := make([]string, 0, len(rows))
|
|
for _, row := range rows {
|
|
actual = append(actual, row.ColumnName)
|
|
}
|
|
|
|
if slices.Equal(actual, expected) {
|
|
return nil
|
|
}
|
|
|
|
if len(rows) > 0 {
|
|
if err := db.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP INDEX `%s`", tableName, indexName)).Error; err != nil {
|
|
return fmt.Errorf("drop %s: %w", indexName, err)
|
|
}
|
|
}
|
|
|
|
if err := db.Exec(
|
|
fmt.Sprintf(
|
|
"ALTER TABLE `%s` ADD UNIQUE KEY `%s` (`ai_advice_id`,`node_type`,`node_at`)",
|
|
tableName,
|
|
indexName,
|
|
),
|
|
).Error; err != nil {
|
|
return fmt.Errorf("create %s: %w", indexName, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func repairSmokeAIAdviceIndexes(db *gorm.DB) error {
|
|
if db == nil {
|
|
return nil
|
|
}
|
|
|
|
const (
|
|
tableName = "fa_smoke_ai_advice"
|
|
indexName = "uniq_smoke_ai_advice"
|
|
)
|
|
|
|
var rows []mysqlIndexColumn
|
|
if err := db.Raw(fmt.Sprintf("SHOW INDEX FROM `%s` WHERE Key_name = ?", tableName), indexName).Scan(&rows).Error; err != nil {
|
|
return fmt.Errorf("inspect %s: %w", indexName, err)
|
|
}
|
|
|
|
expected := []string{"uid", "type", "advice_date", "prompt_version"}
|
|
actual := make([]string, 0, len(rows))
|
|
for _, row := range rows {
|
|
actual = append(actual, row.ColumnName)
|
|
}
|
|
|
|
if slices.Equal(actual, expected) {
|
|
return nil
|
|
}
|
|
|
|
if len(rows) > 0 {
|
|
if err := db.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP INDEX `%s`", tableName, indexName)).Error; err != nil {
|
|
return fmt.Errorf("drop %s: %w", indexName, err)
|
|
}
|
|
}
|
|
|
|
if err := db.Exec(
|
|
fmt.Sprintf(
|
|
"ALTER TABLE `%s` ADD UNIQUE KEY `%s` (`uid`,`type`,`advice_date`,`prompt_version`)",
|
|
tableName,
|
|
indexName,
|
|
),
|
|
).Error; err != nil {
|
|
return fmt.Errorf("create %s: %w", indexName, err)
|
|
}
|
|
|
|
return nil
|
|
}
|