Files
supermarket/internal/db/postgres.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

199 lines
5.6 KiB
Go

package db
import (
"crypto/rand"
"database/sql"
_ "embed"
"encoding/hex"
"errors"
"fmt"
"net/url"
"os"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
// pgSchema is the whole schema at pgBaseline, for a new Postgres database.
//
//go:embed postgres.sql
var pgSchema string
// pgBaseline is the SQLite schema version postgres.sql matches.
const pgBaseline = 29
// OpenPostgres opens the Postgres database at url (postgres://…), creating
// the schema in an empty one.
func OpenPostgres(url string) (*DB, error) {
sqldb, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
sqldb.SetMaxOpenConns(20)
sqldb.SetMaxIdleConns(5)
sqldb.SetConnMaxIdleTime(5 * time.Minute)
if err := sqldb.Ping(); err != nil {
sqldb.Close()
return nil, fmt.Errorf("opening Postgres: %w", err)
}
d := &DB{SQL: sqldb, Dialect: Postgres}
if err := d.migratePostgres(); err != nil {
sqldb.Close()
return nil, err
}
return d, nil
}
// 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
}
defer tx.Rollback()
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)
}
if _, err := tx.Exec(`CREATE TABLE schema_version (version integer NOT NULL)`); err != nil {
return err
}
if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, pgBaseline); err != nil {
return err
}
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 < 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()
}
// SchemaVersion is the database's schema version.
func (d *DB) SchemaVersion() (int, error) {
var v int
if d.Dialect == Postgres {
err := d.SQL.QueryRow(`SELECT version FROM schema_version`).Scan(&v)
return v, err
}
err := d.SQL.QueryRow(`PRAGMA user_version`).Scan(&v)
return v, err
}
// TestPostgres, set to a Postgres address, makes Open give each test its
// own new schema in that database instead of a SQLite file, so the whole
// suite runs on Postgres:
//
// SUPERMARKET_TEST_POSTGRES=postgres://postgres:test@localhost:55432/sm go test ./...
//
// The schema is dropped when the test closes the database.
const TestPostgres = "SUPERMARKET_TEST_POSTGRES"
// openTestSchema opens a new, empty schema in the test database.
func openTestSchema(base string) (*DB, error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return nil, err
}
schema := "test_" + hex.EncodeToString(b)
admin, err := sql.Open("pgx", base)
if err != nil {
return nil, err
}
if _, err := admin.Exec(`CREATE SCHEMA ` + schema); err != nil {
admin.Close()
return nil, err
}
u, err := url.Parse(base)
if err != nil {
admin.Close()
return nil, err
}
q := u.Query()
q.Set("search_path", schema)
u.RawQuery = q.Encode()
d, err := OpenPostgres(u.String())
if err != nil {
admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
admin.Close()
return nil, err
}
d.SQL.SetMaxOpenConns(4)
d.closeHook = func() error {
defer admin.Close()
_, err := admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
return err
}
return d, nil
}
// testPostgres is the test database's address, when tests run on Postgres.
func testPostgres() string {
if !testing.Testing() {
return ""
}
return os.Getenv(TestPostgres)
}
// OnPostgres says whether tests are running on Postgres, for the few that
// test SQLite itself (backups).
func OnPostgres() bool { return testPostgres() != "" }
var errSQLiteOnly = errors.New("this works only on the local edition's SQLite database")
// SQLiteOnly is the error for what only works on SQLite.
func SQLiteOnly() error { return errSQLiteOnly }