Files
supermarket/internal/db/migrate_hook_test.go
T
davidandClaude Opus 5.5 d827d507c1 Phase 9, part 3: schema migrations for both databases
Migrations from schema 30 on are one list (internal/db/migrations.go),
written in SQLite's SQL and translated for Postgres (db.PostgresSQL)
unless one gives its own. On Postgres the whole migration is one
transaction under an advisory lock, and each step is recorded in
schema_migrations. TestSchemasMatch compares the two schemas (tables,
columns, types, NOT NULL, nocase, indexes), with and without a new
migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:17:56 -07:00

62 lines
1.6 KiB
Go

package db
import (
"database/sql"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
)
func TestBeforeMigrate(t *testing.T) {
defer func() { BeforeMigrate = nil }()
var calls []string
BeforeMigrate = func(d *sql.DB, from, to int) error {
var n int
d.QueryRow(`PRAGMA user_version`).Scan(&n)
calls = append(calls, fmt.Sprintf("%d→%d at %d", from, to, n))
return nil
}
dir := t.TempDir()
// A new database: nothing to back up.
d, err := OpenSQLite(filepath.Join(dir, "new.db"))
if err != nil {
t.Fatal(err)
}
d.Close()
// Already current: nothing either.
d, _ = OpenSQLite(filepath.Join(dir, "new.db"))
d.Close()
if len(calls) != 0 {
t.Fatalf("called for a new or current database: %v", calls)
}
// One migration behind: backed up first, before the migration runs.
old := filepath.Join(dir, "old.db")
raw, _ := sql.Open("sqlite", "file:"+old)
for i := 0; i < Schema()-1; i++ {
if _, err := raw.Exec(sqliteStep(i)); err != nil {
t.Fatal(err)
}
}
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, Schema()-1))
raw.Close()
d, err = OpenSQLite(old)
if err != nil {
t.Fatal(err)
}
d.Close()
want := fmt.Sprintf("%d→%d at %d", Schema()-1, Schema(), Schema()-1)
if len(calls) != 1 || calls[0] != want || false {
t.Errorf("calls: %v, want %s", calls, want)
}
// A failed backup stops the migration.
raw, _ = sql.Open("sqlite", "file:"+old)
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, Schema()-1))
raw.Close()
BeforeMigrate = func(*sql.DB, int, int) error { return errors.New("disk full") }
if _, err := OpenSQLite(old); err == nil || !strings.Contains(err.Error(), "disk full") {
t.Errorf("open: %v", err)
}
}