Files
QuoteForge/internal/models/sql_migration_maintenance.go
T

45 lines
1.5 KiB
Go

package models
import (
"crypto/sha256"
"fmt"
"strings"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// migrationJournalName uses the configured endpoint, which survives server restarts.
func migrationJournalName(db *gorm.DB, schema string) (string, error) {
dialect, ok := db.Dialector.(*mysql.Dialector)
if !ok || dialect.DSNConfig == nil {
return "", fmt.Errorf("migration requires a MariaDB DSN")
}
identity := dialect.DSNConfig.Net + "/" + dialect.DSNConfig.Addr + "/" + schema
return fmt.Sprintf("qfs-migration-v1-%x.pending", sha256.Sum256([]byte(identity))), nil
}
func requireExclusiveMigrationSession(db *gorm.DB) error {
var grants []string
if err := db.Session(&gorm.Session{NewDB: true}).Raw("SHOW GRANTS FOR CURRENT_USER").Scan(&grants).Error; err != nil {
return fmt.Errorf("read maintenance privileges: %w", err)
}
allowed := false
for _, grant := range grants {
if strings.Contains(grant, " ON *.* ") && strings.Contains(grant, "ALL PRIVILEGES") {
allowed = true
}
}
if !allowed {
return fmt.Errorf("migration recovery requires a DBA with directly granted global ALL PRIVILEGES to inspect all objects and clients")
}
var clients int64
if err := db.Session(&gorm.Session{NewDB: true}).Raw("SELECT COUNT(*) FROM information_schema.PROCESSLIST WHERE ID<>CONNECTION_ID() AND DB=DATABASE()").Scan(&clients).Error; err != nil {
return fmt.Errorf("check maintenance clients: %w", err)
}
if clients != 0 {
return fmt.Errorf("migration requires maintenance window: %d other connections use this schema", clients)
}
return nil
}