Files

135 lines
4.1 KiB
Go

package main
import (
"fmt"
"io/fs"
"time"
qfassets "git.mchus.pro/mchus/quoteforge"
"git.mchus.pro/mchus/quoteforge/internal/appstate"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"git.mchus.pro/mchus/quoteforge/internal/models"
mysqlDriver "github.com/go-sql-driver/mysql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Server (MariaDB) migration commands. Each runs only the embedded migrations/*.sql
// files tracked in qt_schema_migrations — never GORM AutoMigrate, which can silently
// retype production columns to match whatever models the running binary was built with.
// See bible-local/03-database.md "Migrations".
// openMigrationDB opens a dedicated MariaDB connection for migrations. The app's shared
// connection (localdb.GetDSN) has 3s read/write timeouts for offline-first sync; a
// backfill UPDATE over qt_pricelist_items needs minutes, and a client-side timeout
// mid-statement leaves the file half-applied and unrecorded.
func openMigrationDB(local *localdb.LocalDB) (*gorm.DB, error) {
dsn, err := local.GetDSN()
if err != nil {
return nil, fmt.Errorf("server connection settings: %w", err)
}
cfg, err := mysqlDriver.ParseDSN(dsn)
if err != nil {
return nil, fmt.Errorf("parse DSN: %w", err)
}
cfg.Timeout = 10 * time.Second
cfg.ReadTimeout = 0
cfg.WriteTimeout = 0
db, err := gorm.Open(mysql.Open(cfg.FormatDSN()), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
return nil, fmt.Errorf("connect to server: %w", err)
}
sqlDB, err := db.DB()
if err != nil {
return nil, fmt.Errorf("migration pool: %w", err)
}
sqlDB.SetMaxOpenConns(1)
sqlDB.SetMaxIdleConns(1)
return db, nil
}
// runMigrateStatus prints every server migration and whether it is applied.
func runMigrateStatus(db *gorm.DB) error {
migrations, err := qfassets.MigrationsFS()
if err != nil {
return err
}
states, err := models.SQLMigrationStatus(db, migrations)
if err != nil {
return err
}
pending := 0
for _, st := range states {
if st.AppliedAt != nil {
fmt.Printf(" applied %s (%s)\n", st.Filename, st.AppliedAt.Format("2006-01-02 15:04"))
} else {
fmt.Printf(" PENDING %s\n", st.Filename)
pending++
}
}
fmt.Printf("%d migrations, %d pending\n", len(states), pending)
return nil
}
// runMigrateApply applies pending server migrations. Refuses on a server with no
// migration history at all: its schema was built by other means, so every file would be
// re-run — record a baseline with -migrate-baseline first.
func runMigrateApply(db *gorm.DB, localDBPath string) error {
migrations, err := qfassets.MigrationsFS()
if err != nil {
return err
}
if err := requireMigrationHistory(db, migrations); err != nil {
return err
}
backupRoot, err := appstate.ServerMigrationBackupDir(localDBPath)
if err != nil {
return err
}
applied, err := models.RunSQLMigrations(db, migrations, func(filename string) {
fmt.Printf(" applying %s ...\n", filename)
}, backupRoot)
if err != nil {
return err
}
if len(applied) == 0 {
fmt.Println("server schema is up to date — nothing to apply")
return nil
}
fmt.Printf("applied %d migration(s)\n", len(applied))
return nil
}
// runMigrateBaseline records migrations up to and including upto as applied without
// running them.
func runMigrateBaseline(db *gorm.DB, upto string) error {
migrations, err := qfassets.MigrationsFS()
if err != nil {
return err
}
recorded, err := models.BaselineSQLMigrations(db, migrations, upto)
for _, f := range recorded {
fmt.Printf(" recorded %s (not executed)\n", f)
}
if err != nil {
return err
}
fmt.Printf("baseline: %d migration(s) recorded as applied, up to %s\n", len(recorded), upto)
return nil
}
func requireMigrationHistory(db *gorm.DB, migrations fs.FS) error {
states, err := models.SQLMigrationStatus(db, migrations)
if err != nil {
return err
}
for _, st := range states {
if st.AppliedAt != nil {
return nil
}
}
return fmt.Errorf("qt_schema_migrations has no applied migrations, so all %d files would run against this server. "+
"Record what the server already has first: qfs -migrate-baseline <last-applied-file.sql> (make migrate-baseline UPTO=...)", len(states))
}