Fix local pricelist uniqueness and preserve config project on update
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -47,6 +48,11 @@ var localMigrations = []localMigration{
|
||||
name: "Attach existing configurations to latest local pricelist and recalc usage",
|
||||
run: backfillConfigurationPricelists,
|
||||
},
|
||||
{
|
||||
id: "2026_02_06_pricelist_index_fix",
|
||||
name: "Use unique server_id for local pricelists and allow duplicate versions",
|
||||
run: fixLocalPricelistIndexes,
|
||||
},
|
||||
}
|
||||
|
||||
func runLocalMigrations(db *gorm.DB) error {
|
||||
@@ -237,3 +243,52 @@ func chooseNonZeroTime(candidate time.Time, fallback time.Time) time.Time {
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
func fixLocalPricelistIndexes(tx *gorm.DB) error {
|
||||
type indexRow struct {
|
||||
Name string `gorm:"column:name"`
|
||||
Unique int `gorm:"column:unique"`
|
||||
}
|
||||
var indexes []indexRow
|
||||
if err := tx.Raw("PRAGMA index_list('local_pricelists')").Scan(&indexes).Error; err != nil {
|
||||
return fmt.Errorf("list local_pricelists indexes: %w", err)
|
||||
}
|
||||
|
||||
for _, idx := range indexes {
|
||||
if idx.Unique == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
type indexInfoRow struct {
|
||||
Name string `gorm:"column:name"`
|
||||
}
|
||||
var info []indexInfoRow
|
||||
if err := tx.Raw(fmt.Sprintf("PRAGMA index_info('%s')", strings.ReplaceAll(idx.Name, "'", "''"))).Scan(&info).Error; err != nil {
|
||||
return fmt.Errorf("load index info for %s: %w", idx.Name, err)
|
||||
}
|
||||
if len(info) != 1 || info[0].Name != "version" {
|
||||
continue
|
||||
}
|
||||
|
||||
quoted := strings.ReplaceAll(idx.Name, `"`, `""`)
|
||||
if err := tx.Exec(fmt.Sprintf(`DROP INDEX IF EXISTS "%s"`, quoted)).Error; err != nil {
|
||||
return fmt.Errorf("drop unique version index %s: %w", idx.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_pricelists_server_id
|
||||
ON local_pricelists(server_id)
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("ensure unique index local_pricelists(server_id): %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_local_pricelists_version
|
||||
ON local_pricelists(version)
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("ensure index local_pricelists(version): %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user