From d827d507c1ee5cf4d255553f0c956d61494aab46 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 07:17:56 -0700 Subject: [PATCH] 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 --- PLAN.md | 17 ++ README.md | 12 ++ cmd/supermarket/main.go | 4 + internal/db/db.go | 40 ++-- internal/db/dialect.go | 5 + internal/db/migrate_hook_test.go | 12 +- internal/db/migrations.go | 83 ++++++++ internal/db/migrations_test.go | 313 +++++++++++++++++++++++++++++++ internal/db/postgres.go | 54 +++++- 9 files changed, 508 insertions(+), 32 deletions(-) create mode 100644 internal/db/migrations.go create mode 100644 internal/db/migrations_test.go diff --git a/PLAN.md b/PLAN.md index 59b5b0b..80f8faf 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1909,6 +1909,23 @@ than planned: rather than helpers in every query, the SQL stays as it is - Left for part 3: migrations after schema 29 on both databases, and what replaces SQLite's backup before a migration. +**Part 3 built 2026-11-25** on `phase9`. +- Schema changes from 30 on are one list for both databases + (`internal/db/migrations.go`), written in SQLite's SQL. Postgres gets + them translated automatically (`db.PostgresSQL`: types, identity keys, + `nocase`, timestamp defaults), unless a migration gives its own. SQLite's + 29 migrations are closed. +- On Postgres, the whole migration (creating the schema, then each step) + is one transaction under an advisory lock: a failure leaves the database + as it was, and several copies of the app can start together. Each step + is recorded in `schema_migrations` (version, note, the app's version, + when), in place of SQLite's backup before a migration; the operator's + own Postgres backups cover the rest. The app logs a migration on both. +- `TestSchemasMatch` (on Postgres) compares the two schemas, with and + without a new migration: tables, columns in order, types, `NOT NULL`, + case-insensitivity and named indexes. Checked by feeding it drift on + purpose: a type, a missing index, a missing `nocase`. + Nothing changes for the local user; this makes the rest possible. A commit after each part; the whole test suite runs against both SQLite and Postgres from part 2 on. diff --git a/README.md b/README.md index dc1fc49..9982c1b 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,18 @@ collation. New SQL should run on both: use `db.Insert` (not `LastInsertId`), `ON CONFLICT … DO NOTHING` (not `INSERT OR IGNORE`), table-qualified columns in an upsert's `DO UPDATE`, and every selected column in `GROUP BY`. +**Changing the schema.** Add a `db.Migration` to `both` in +`internal/db/migrations.go`, written in SQLite's SQL. Postgres gets the same +statements translated (`INTEGER` → `BIGINT`, `INTEGER PRIMARY KEY` → an identity +column, `REAL` → `DOUBLE PRECISION`, `COLLATE NOCASE` → the `nocase` collation, +`strftime(… 'now')` defaults → `now()`). A migration that changes data with +SQL only SQLite has gives its `Postgres` SQL too. Never edit one that has +shipped. Run the tests on Postgres: `TestSchemasMatch` fails if the two +schemas differ in a table, column, type, `NOT NULL`, case-insensitivity or +index. On SQLite, a backup is made before migrating; on Postgres, the +migrations run in one transaction (several copies of the app can start +together), and each is recorded in `schema_migrations`. + | Path | What | |------|------| | `cmd/supermarket` | The server | diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 6661528..ed2b871 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -155,11 +155,15 @@ func run(log *slog.Logger) error { } return err } + db.AppVersion = version database, err := db.Open(filepath.Join(dataDir, "app.db")) if err != nil { return err } defer database.Close() + if database.MigratedFrom > 0 { + log.Info("database: migrated", "database", database.Dialect, "from", database.MigratedFrom, "to", db.Schema()) + } if n, err := content.RecoverInterrupted(database); err != nil { return err diff --git a/internal/db/db.go b/internal/db/db.go index 4249614..d52c958 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -1,4 +1,5 @@ -// Package db opens the app's SQLite database and keeps its schema current. +// Package db opens the app's database, SQLite (the local edition) or +// Postgres (server and multi-tenant), and keeps its schema current. package db import ( @@ -10,8 +11,9 @@ import ( _ "modernc.org/sqlite" // registers the "sqlite" driver (pure Go, no cgo) ) -// migrations are applied in order, once each. Never edit or reorder one that -// has shipped: add a new one instead. +// migrations are SQLite's schemas 1 to 29, applied in order, once each. +// They're closed: a change to the schema now goes in both (migrations.go), +// for SQLite and Postgres alike. var migrations = []string{ // 1: settings, inventory, the content pipeline's state, and the Hermes bridge ` @@ -685,15 +687,13 @@ CREATE TABLE list_members ( `, } - -// BeforeMigrate, if set, runs before an existing database is migrated to -// a newer schema (from and to are the schema versions): the app backs it -// up. A new, empty database isn't backed up. +// BeforeMigrate, if set, runs before an existing SQLite database is +// migrated to a newer schema (from and to are the schema versions): the +// app backs it up. A new, empty database isn't backed up. (Postgres is +// backed up by whoever runs it; its migrations are recorded in +// schema_migrations.) var BeforeMigrate func(d *sql.DB, from, to int) error -// Schema is the schema version this build migrates databases to. -func Schema() int { return len(migrations) } - // Open opens (creating if needed) the SQLite database at path and // migrates it. In tests run with SUPERMARKET_TEST_POSTGRES set, it opens a // new Postgres schema instead (see TestPostgres). @@ -728,10 +728,10 @@ func OpenSQLite(path string) (*DB, error) { sqldb.Close() return nil, err } - if version > 0 && version < len(migrations) { - if err := BeforeMigrate(sqldb, version, len(migrations)); err != nil { + if version > 0 && version < Schema() { + if err := BeforeMigrate(sqldb, version, Schema()); err != nil { sqldb.Close() - return nil, fmt.Errorf("backing up before migrating to schema %d: %w", len(migrations), err) + return nil, fmt.Errorf("backing up before migrating to schema %d: %w", Schema(), err) } } } @@ -743,19 +743,25 @@ func OpenSQLite(path string) (*DB, error) { } func (d *DB) migrate() error { + if err := checkMigrations(); err != nil { + return err + } var version int if err := d.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil { return err } - if version > len(migrations) { - return fmt.Errorf("the database is from a newer Supermarket (schema %d, this version knows %d); update Supermarket", version, len(migrations)) + if version > Schema() { + return fmt.Errorf("the database is from a newer Supermarket (schema %d, this version knows %d); update Supermarket", version, Schema()) } - for i := version; i < len(migrations); i++ { + if version > 0 && version < Schema() { + d.MigratedFrom = version + } + for i := version; i < Schema(); i++ { tx, err := d.SQL.Begin() if err != nil { return err } - if _, err := tx.Exec(migrations[i]); err != nil { + if _, err := tx.Exec(sqliteStep(i)); err != nil { tx.Rollback() return fmt.Errorf("migration %d: %w", i+1, err) } diff --git a/internal/db/dialect.go b/internal/db/dialect.go index 6231688..cc9607f 100644 --- a/internal/db/dialect.go +++ b/internal/db/dialect.go @@ -35,6 +35,11 @@ type DB struct { SQL *sql.DB Dialect Dialect + // MigratedFrom is the schema version the database was at when opened, + // if Open migrated it (0 if it was new or already current), for the + // log. + MigratedFrom int + closeHook func() error // tests on Postgres: drop the test's schema } diff --git a/internal/db/migrate_hook_test.go b/internal/db/migrate_hook_test.go index aefed38..2f0d6d6 100644 --- a/internal/db/migrate_hook_test.go +++ b/internal/db/migrate_hook_test.go @@ -34,25 +34,25 @@ func TestBeforeMigrate(t *testing.T) { // One migration behind: backed up first, before the migration runs. old := filepath.Join(dir, "old.db") raw, _ := sql.Open("sqlite", "file:"+old) - for _, m := range migrations[:len(migrations)-1] { - if _, err := raw.Exec(m); err != nil { + 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`, len(migrations)-1)) + 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", len(migrations)-1, len(migrations), len(migrations)-1) - if len(calls) != 1 || calls[0] != want || Schema() != len(migrations) { + 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`, len(migrations)-1)) + 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") { diff --git a/internal/db/migrations.go b/internal/db/migrations.go new file mode 100644 index 0000000..a1feb7c --- /dev/null +++ b/internal/db/migrations.go @@ -0,0 +1,83 @@ +package db + +import ( + "fmt" + "regexp" + "strings" +) + +// Migration is a change to the schema from schema 30 on, for both +// databases. It's written once, in SQLite's SQL; Postgres gets the same +// statements with SQLite's types and defaults translated (see PostgresSQL). +// A migration that changes data with SQL only SQLite has gives Postgres +// its own. +// +// Never edit or reorder one that has shipped: add a new one instead. +type Migration struct { + Note string // what it does, for the record (Postgres' schema_migrations) + SQLite string + Postgres string // empty: PostgresSQL(SQLite) +} + +// both are the migrations after schema 29, on both databases: schema 30 +// is both[0]. (migrations, before them, are SQLite's own; Postgres starts +// from postgres.sql, which is schema 29 as a whole.) +var both = []Migration{} + +// Schema is the schema version this build migrates databases to. +func Schema() int { return len(migrations) + len(both) } + +// sqliteStep is the SQL that takes SQLite from schema i to i+1. +func sqliteStep(i int) string { + if i < len(migrations) { + return migrations[i] + } + return both[i-len(migrations)].SQLite +} + +// postgresStep is the migration that takes Postgres from schema i to i+1 +// (i is pgBaseline or later). +func postgresStep(i int) (Migration, string) { + m := both[i-pgBaseline] + if m.Postgres != "" { + return m, m.Postgres + } + return m, PostgresSQL(m.SQLite) +} + +var ( + ddlIntegerKey = regexp.MustCompile(`(?i)\bINTEGER\s+PRIMARY\s+KEY\b`) + ddlInteger = regexp.MustCompile(`(?i)\bINTEGER\b`) + ddlReal = regexp.MustCompile(`(?i)\bREAL\b`) + ddlBlob = regexp.MustCompile(`(?i)\bBLOB\b`) + ddlNow = regexp.MustCompile(`(?i)strftime\('%Y-%m-%dT%H:%M:%SZ',\s*'now'\)`) + // A column whose COLLATE comes after its constraints: Postgres wants it + // right after the type. + ddlCollateLate = regexp.MustCompile(`(?i)\bTEXT((?:\s+(?:NOT\s+NULL|UNIQUE|PRIMARY\s+KEY|DEFAULT\s+(?:'(?:[^']|'')*'|\([^)]*\)|[^\s,]+)))+)\s+COLLATE\s+NOCASE\b`) + ddlCollate = regexp.MustCompile(`(?i)\bCOLLATE\s+NOCASE\b`) +) + +// PostgresSQL translates SQLite's DDL (CREATE TABLE, CREATE INDEX, ALTER +// TABLE … ADD COLUMN) to Postgres': 64-bit integers, identity keys, +// doubles, the nocase collation in its place, and timestamps from now(). +func PostgresSQL(sqlite string) string { + s := ddlIntegerKey.ReplaceAllString(sqlite, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY") + s = ddlInteger.ReplaceAllString(s, "BIGINT") + s = ddlReal.ReplaceAllString(s, "DOUBLE PRECISION") + s = ddlBlob.ReplaceAllString(s, "BYTEA") + s = ddlNow.ReplaceAllString(s, `to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`) + s = ddlCollateLate.ReplaceAllString(s, "TEXT COLLATE nocase$1") + s = ddlCollate.ReplaceAllString(s, "COLLATE nocase") + return s +} + +// checkMigrations catches a mistake in the list before it reaches a +// database: an empty step. +func checkMigrations() error { + for i, m := range both { + if strings.TrimSpace(m.SQLite) == "" || strings.TrimSpace(m.Note) == "" { + return fmt.Errorf("migration %d needs its SQLite SQL and a note", len(migrations)+i+1) + } + } + return nil +} diff --git a/internal/db/migrations_test.go b/internal/db/migrations_test.go new file mode 100644 index 0000000..f618eb6 --- /dev/null +++ b/internal/db/migrations_test.go @@ -0,0 +1,313 @@ +package db + +import ( + "database/sql" + "fmt" + "net/url" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" +) + +func TestPostgresSQL(t *testing.T) { + in := `CREATE TABLE t ( + id INTEGER PRIMARY KEY, + n INTEGER NOT NULL DEFAULT 0, + score REAL, + raw BLOB, + email TEXT NOT NULL DEFAULT '' COLLATE NOCASE, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + slug TEXT COLLATE NOCASE NOT NULL, + at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + PRIMARY KEY (n, name) +); +CREATE INDEX t_by_name ON t (name COLLATE NOCASE); +ALTER TABLE t ADD COLUMN size INTEGER NOT NULL DEFAULT 0;` + want := `CREATE TABLE t ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + n BIGINT NOT NULL DEFAULT 0, + score DOUBLE PRECISION, + raw BYTEA, + email TEXT COLLATE nocase NOT NULL DEFAULT '', + name TEXT COLLATE nocase NOT NULL UNIQUE, + slug TEXT COLLATE nocase NOT NULL, + at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + PRIMARY KEY (n, name) +); +CREATE INDEX t_by_name ON t (name COLLATE nocase); +ALTER TABLE t ADD COLUMN size BIGINT NOT NULL DEFAULT 0;` + if got := PostgresSQL(in); got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } +} + +// withMigration adds a migration (schema 30, …) for one test. +func withMigration(t *testing.T, m Migration) { + t.Helper() + saved := both + both = append(slices.Clone(both), m) + t.Cleanup(func() { both = saved }) +} + +var testMigration = Migration{ + Note: "test: a table", + SQLite: `CREATE TABLE test_widgets ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL DEFAULT '' COLLATE NOCASE, + at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) +); +CREATE INDEX test_widgets_by_name ON test_widgets (name); +ALTER TABLE settings ADD COLUMN test_flag INTEGER NOT NULL DEFAULT 0;`, +} + +// A migration after schema 29 runs on SQLite, new and existing. +func TestMigrationOnSQLite(t *testing.T) { + dir := t.TempDir() + old, err := OpenSQLite(filepath.Join(dir, "old.db")) // at the current schema + if err != nil { + t.Fatal(err) + } + old.Close() + withMigration(t, testMigration) + for _, name := range []string{"old.db", "new.db"} { + d, err := OpenSQLite(filepath.Join(dir, name)) + if err != nil { + t.Fatal(name, err) + } + if v, _ := d.SchemaVersion(); v != Schema() { + t.Errorf("%s: schema %d, want %d", name, v, Schema()) + } + if want := map[string]int{"old.db": Schema() - 1, "new.db": 0}[name]; d.MigratedFrom != want { + t.Errorf("%s: migrated from %d, want %d", name, d.MigratedFrom, want) + } + if _, err := d.Exec(`INSERT INTO test_widgets (name) VALUES ('A')`); err != nil { + t.Error(name, err) + } + var n int + if err := d.QueryRow(`SELECT count(*) FROM test_widgets WHERE name = 'a'`).Scan(&n); err != nil || n != 1 { + t.Errorf("%s: %d %v", name, n, err) + } + d.Close() + } +} + +// pgTestSchema makes an empty schema in the test Postgres, and the +// address that opens it; it's dropped after the test. +func pgTestSchema(t *testing.T) string { + t.Helper() + base := os.Getenv(TestPostgres) + if base == "" { + t.Skip("set " + TestPostgres + " to test on Postgres") + } + admin, err := sql.Open("pgx", base) + if err != nil { + t.Fatal(err) + } + schema := fmt.Sprintf("test_m_%d", os.Getpid()) + admin.Exec(`DROP SCHEMA IF EXISTS ` + schema + ` CASCADE`) + if _, err := admin.Exec(`CREATE SCHEMA ` + schema); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`) + admin.Close() + }) + u, _ := url.Parse(base) + q := u.Query() + q.Set("search_path", schema) + u.RawQuery = q.Encode() + return u.String() +} + +// A migration after schema 29 runs on Postgres, on a database made by an +// earlier version, and each step is recorded. +func TestMigrationOnPostgres(t *testing.T) { + addr := pgTestSchema(t) + d, err := OpenPostgres(addr) // made at the current schema + if err != nil { + t.Fatal(err) + } + if d.MigratedFrom != 0 { + t.Errorf("a new database was migrated from %d", d.MigratedFrom) + } + d.Close() + withMigration(t, testMigration) + d, err = OpenPostgres(addr) + if err != nil { + t.Fatal(err) + } + defer d.Close() + if v, _ := d.SchemaVersion(); v != Schema() || d.MigratedFrom != Schema()-1 { + t.Errorf("schema %d, migrated from %d", v, d.MigratedFrom) + } + if _, err := d.Exec(`INSERT INTO test_widgets (name) VALUES ('A')`); err != nil { + t.Fatal(err) + } + var n int + if err := d.QueryRow(`SELECT count(*) FROM test_widgets WHERE name = 'a' AND at LIKE '20%Z'`).Scan(&n); err != nil || n != 1 { + t.Errorf("%d %v", n, err) + } + var steps []string + rows, err := d.SQL.Query(`SELECT version, note FROM schema_migrations ORDER BY version`) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var v int + var note string + rows.Scan(&v, ¬e) + steps = append(steps, fmt.Sprint(v, " ", note)) + } + rows.Close() + if len(steps) < 2 || !strings.HasPrefix(steps[0], "29 created") || steps[len(steps)-1] != fmt.Sprint(Schema(), " test: a table") { + t.Errorf("recorded: %q", steps) + } + + // A migration that fails leaves the database as it was. + withMigration(t, Migration{Note: "test: broken", SQLite: `CREATE TABLE test_ok (id INTEGER); CREATE TABLE settings (x TEXT);`}) + if _, err := OpenPostgres(addr); err == nil || !strings.Contains(err.Error(), "test: broken") { + t.Fatalf("open: %v", err) + } + var exists bool + d.QueryRow(`SELECT to_regclass('test_ok') IS NOT NULL`).Scan(&exists) + if v, _ := d.SchemaVersion(); exists || v != Schema()-1 { + t.Errorf("after a failed migration: schema %d, test_ok %v", v, exists) + } +} + +// column is one column of a table, as both databases can say it. +type column struct { + Name, Type string + NotNull bool + NoCase bool +} + +// sqliteColumns are SQLite's tables and their columns. +func sqliteColumns(t *testing.T, d *DB) (map[string][]column, []string) { + t.Helper() + tables := map[string][]column{} + rows, err := d.SQL.Query(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) + if err != nil { + t.Fatal(err) + } + defs := map[string]string{} + for rows.Next() { + var name, def string + rows.Scan(&name, &def) + defs[name] = def + } + rows.Close() + types := map[string]string{"INTEGER": "bigint", "TEXT": "text", "REAL": "double precision", "BLOB": "bytea"} + for name, def := range defs { + cols, err := d.SQL.Query(`SELECT name, type, "notnull", pk FROM pragma_table_info(?)`, name) + if err != nil { + t.Fatal(err) + } + for cols.Next() { + var c column + var ty string + var notNull, pk int + cols.Scan(&c.Name, &ty, ¬Null, &pk) + c.Type = types[strings.ToUpper(ty)] + c.NotNull = notNull == 1 || pk > 0 + // Its definition, up to the next column: does it ignore case? + re := regexp.MustCompile(`(?i)(?:^|[(,\n])\s*"?` + regexp.QuoteMeta(c.Name) + `"?\s+[^,\n]*COLLATE\s+NOCASE`) + c.NoCase = re.MatchString(def) + tables[name] = append(tables[name], c) + } + cols.Close() + } + var indexes []string + rows, err = d.SQL.Query(`SELECT name FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL`) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var n string + rows.Scan(&n) + indexes = append(indexes, n) + } + rows.Close() + slices.Sort(indexes) + return tables, indexes +} + +// postgresColumns are Postgres' tables and their columns. +func postgresColumns(t *testing.T, d *DB) (map[string][]column, []string) { + t.Helper() + tables := map[string][]column{} + rows, err := d.SQL.Query(`SELECT table_name, column_name, data_type, is_nullable = 'NO', coalesce(collation_name, '') = 'nocase' + FROM information_schema.columns WHERE table_schema = current_schema() + AND table_name NOT IN ('schema_version', 'schema_migrations') ORDER BY table_name, ordinal_position`) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var table string + var c column + rows.Scan(&table, &c.Name, &c.Type, &c.NotNull, &c.NoCase) + tables[table] = append(tables[table], c) + } + rows.Close() + var indexes []string + rows, err = d.SQL.Query(`SELECT i.relname FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid + JOIN pg_namespace n ON n.oid = i.relnamespace + WHERE n.nspname = current_schema() AND NOT x.indisprimary + AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = x.indexrelid)`) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var n string + rows.Scan(&n) + indexes = append(indexes, n) + } + rows.Close() + slices.Sort(indexes) + return tables, indexes +} + +// The two databases have the same schema: tables, columns in order, their +// types, NOT NULL, which ignore case, and named indexes. With a migration +// added too, as a new one would be. +func TestSchemasMatch(t *testing.T) { + for _, extra := range []bool{false, true} { + t.Run(fmt.Sprint("with a migration: ", extra), func(t *testing.T) { + addr := pgTestSchema(t) + if extra { + withMigration(t, testMigration) + } + lite, err := OpenSQLite(filepath.Join(t.TempDir(), "app.db")) + if err != nil { + t.Fatal(err) + } + defer lite.Close() + pg, err := OpenPostgres(addr) + if err != nil { + t.Fatal(err) + } + defer pg.Close() + lt, li := sqliteColumns(t, lite) + pt, pi := postgresColumns(t, pg) + for name, cols := range lt { + if !slices.Equal(cols, pt[name]) { + t.Errorf("table %s:\n SQLite %v\n Postgres %v", name, cols, pt[name]) + } + } + for name := range pt { + if _, ok := lt[name]; !ok { + t.Errorf("table %s is only on Postgres", name) + } + } + if !slices.Equal(li, pi) { + t.Errorf("indexes:\n SQLite %v\n Postgres %v", li, pi) + } + if len(lt) < 39 { + t.Errorf("only %d tables", len(lt)) + } + }) + } +} diff --git a/internal/db/postgres.go b/internal/db/postgres.go index 25e1792..679d1f5 100644 --- a/internal/db/postgres.go +++ b/internal/db/postgres.go @@ -45,10 +45,18 @@ func OpenPostgres(url string) (*DB, error) { return d, nil } -// migratePostgres creates the schema in an empty database, and checks an -// existing one isn't newer than this version knows. One copy of the app -// at a time does it (an advisory lock), so several can start together. +// AppVersion is the app's version, recorded with each Postgres migration. +var AppVersion = "dev" + +// migratePostgres creates the schema in an empty database, at schema 29 +// (postgres.sql), then applies the migrations after it, all in one +// transaction: a failure leaves the database as it was. One copy of the +// app at a time does it (an advisory lock), so several can start +// together. Each step is recorded in schema_migrations. func (d *DB) migratePostgres() error { + if err := checkMigrations(); err != nil { + return err + } tx, err := d.SQL.Begin() if err != nil { return err @@ -57,10 +65,23 @@ func (d *DB) migratePostgres() error { if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421)`); err != nil { // any fixed number: "the schema" return err } + if _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( + version integer PRIMARY KEY, + note text NOT NULL, + app text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT now() + )`); err != nil { + return err + } + record := func(version int, note string) error { + _, err := tx.Exec(`INSERT INTO schema_migrations (version, note, app) VALUES ($1, $2, $3)`, version, note, AppVersion) + return err + } var exists bool if err := tx.QueryRow(`SELECT to_regclass('schema_version') IS NOT NULL`).Scan(&exists); err != nil { return err } + version := pgBaseline if !exists { if _, err := tx.Exec(pgSchema); err != nil { return fmt.Errorf("creating the schema: %w", err) @@ -71,17 +92,32 @@ func (d *DB) migratePostgres() error { if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, pgBaseline); err != nil { return err } - return tx.Commit() - } - var version int - if err := tx.QueryRow(`SELECT version FROM schema_version`).Scan(&version); err != nil { + if err := record(pgBaseline, "created: schema 29 as a whole (postgres.sql)"); err != nil { + return err + } + } else if err := tx.QueryRow(`SELECT version FROM schema_version`).Scan(&version); err != nil { return err } if version > Schema() { return fmt.Errorf("the database is from a newer Supermarket (schema %d, this version knows %d); update Supermarket", version, Schema()) } - if version < Schema() { - return fmt.Errorf("the database is at schema %d and this version needs %d, but Postgres has no migrations past %d yet", version, Schema(), pgBaseline) + if version < pgBaseline { + return fmt.Errorf("the database says schema %d, older than any Postgres database Supermarket made", version) + } + if exists && version < Schema() { + d.MigratedFrom = version + } + for i := version; i < Schema(); i++ { + m, q := postgresStep(i) + if _, err := tx.Exec(q); err != nil { + return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err) + } + if _, err := tx.Exec(`UPDATE schema_version SET version = $1`, i+1); err != nil { + return err + } + if err := record(i+1, m.Note); err != nil { + return err + } } return tx.Commit() }