diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cbd2a4e..31c18a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v7.0.1 - - uses: jdx/mise-action@v5.2.7 + - uses: jdx/mise-action@v5.2.9 - name: mise run check run: mise run check diff --git a/README.md b/README.md index bccc15a..c4e51ff 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,8 @@ Three conventions the library keeps are stricter than a reader might expect: third-party migration dependency. - `sqltest` is the scripted `database/sql` driver for hermetic tests. - `postgres` (sub-module) is the PostgreSQL dialect: placeholders, error classification, the - advisory lock, and the engine's native forms. + advisory lock, and the engine's native forms. Its `pgtest` package gives an integration test + its own throwaway database, migrated or empty, dropped when the test ends. - `sqlint` (sub-module) is the conventions linter as a package, with the command at `sqlint/cmd/sqlint`. diff --git a/compose/postgres/Dockerfile b/compose/postgres/Dockerfile index e8f5fe9..80f88d7 100644 --- a/compose/postgres/Dockerfile +++ b/compose/postgres/Dockerfile @@ -1,6 +1,6 @@ # The development stack's PostgreSQL: the database the integration tier # connects to through SQLATE_DSN. This FROM line is PostgreSQL's one pin. -FROM postgres:18.6-alpine +FROM postgres:18.7-alpine # The user, password, and database SQLATE_DSN names; development values, not # secrets. diff --git a/docs/features.md b/docs/features.md index 5b36fb7..0d5e491 100644 --- a/docs/features.md +++ b/docs/features.md @@ -630,3 +630,18 @@ agrees with its total when writes commit between the statement and the caller, w read as its own statement does not; that it agrees under concurrent writers; and that the counted page scans its base once under one window while the uncounted page keeps the key's index order. `mise run acceptance` runs them against a compose PostgreSQL and tears it down. + +### pgtest: a test's throwaway database + +`pgtest` gives an integration test its own PostgreSQL database, so no test depends on the +state of a shared database or on another test. `Create(t, env, prefix)` creates +`_test_` on the server whose admin DSN the environment variable `env` holds, and +fails the test when `env` is unset. It returns a `*Database` holding a pinged pool over the new +database (`Pool`) and the admin DSN pointed at it (`DSN`), which a test hands to a process it +starts. `Migrated(t, env, prefix, sets...)` is `Create` with the `migrate.Set`s applied in order +under the PostgreSQL dialect, and `Database.Session()` wraps the pool under `Dialect`. + +When the test ends the pool is closed and the database dropped `WITH (FORCE)`, so a session +still open on it, such as a started process's pool, is ended rather than holding the drop back; +the drop is retried while the server reports a session still closing. The package imports +`testing`, so only test files import it. diff --git a/docs/quick-start.md b/docs/quick-start.md index 8585682..024ae8f 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -83,7 +83,7 @@ image's one pin. `compose/postgres/Dockerfile`: ```dockerfile -FROM postgres:18.6-alpine +FROM postgres:18.7-alpine ENV POSTGRES_USER=app \ POSTGRES_PASSWORD=app \ diff --git a/postgres/CHANGELOG.md b/postgres/CHANGELOG.md index 52fa7d1..6652593 100644 --- a/postgres/CHANGELOG.md +++ b/postgres/CHANGELOG.md @@ -7,6 +7,21 @@ changelog covers this sub-module only; the base module keeps its own. ## [Unreleased] +## [v0.8.0] - 2026-11-17 + +### Added + +- Package `pgtest`, an integration test's throwaway database over pgx's `database/sql` driver. + `Create(t, env, prefix)` creates `_test_` on the server whose admin DSN the + environment variable `env` holds, failing the test when it is unset, and returns a + `*Database` holding the pool and the DSN pointed at the new database; `Migrated` is `Create` + with `migrate.Set`s applied under the PostgreSQL dialect, and `Database.Session` wraps the + pool under `Dialect`. When the test ends the pool is closed and the database dropped + `WITH (FORCE)`, retried while the server reports a closing session, so a session still open on + it does not hold the drop back; a `CREATE` that timed out is dropped too. +- Live proof that a migrated `pgtest` database is dropped at its test's cleanup with another + pool's session still open on it. + ## [v0.7.0] - 2026-11-11 ### Changed @@ -127,7 +142,8 @@ The first release of the PostgreSQL dialect, against `github.com/standards-lab/s - The integration tier: the migrate and query proofs against a live engine, behind the `integration` build tag. -[Unreleased]: https://github.com/standards-lab/sqlate/compare/postgres/v0.7.0...HEAD +[Unreleased]: https://github.com/standards-lab/sqlate/compare/postgres/v0.8.0...HEAD +[v0.8.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.7.0...postgres/v0.8.0 [v0.7.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.6.0...postgres/v0.7.0 [v0.6.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.5.0...postgres/v0.6.0 [v0.5.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.4.0...postgres/v0.5.0 diff --git a/postgres/pgtest/doc.go b/postgres/pgtest/doc.go new file mode 100644 index 0000000..184a800 --- /dev/null +++ b/postgres/pgtest/doc.go @@ -0,0 +1,19 @@ +// Package pgtest gives an integration test its own throwaway PostgreSQL +// database: created on the server an environment variable names, reached +// over pgx's database/sql driver, and dropped when the test ends, with +// FORCE so a session still open on it, such as a service process's pool, +// does not hold the drop back. +// +// The package exports: +// +// - [Database], one test's database: the pool over it and its DSN +// - [Create], which creates _test_ on the server whose admin +// DSN the named environment variable holds, failing the test when the +// variable is unset +// - [Migrated], which is Create with migration sets applied through the +// migrate package under the PostgreSQL dialect +// - [Database.Session], which wraps the pool under postgres.Dialect +// +// It imports testing, so it belongs only in a consumer's test builds: a +// test file imports it, and no production package should. +package pgtest diff --git a/postgres/pgtest/pgtest.go b/postgres/pgtest/pgtest.go new file mode 100644 index 0000000..69a1840 --- /dev/null +++ b/postgres/pgtest/pgtest.go @@ -0,0 +1,153 @@ +package pgtest + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/hex" + "net/url" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5" + _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver + "github.com/standards-lab/sqlate" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/postgres" +) + +// timeout bounds each statement the package runs against the server, and +// each attempt of the drop separately. +const timeout = 30 * time.Second + +// Database is one test's throwaway database: the pool over it and the DSN +// that names it. +type Database struct { + Pool *sql.DB + DSN string +} + +// Session wraps the pool under postgres.Dialect. +func (d *Database) Session() *sqlate.DB { + return sqlate.Wrap(d.Pool, postgres.Dialect{}) +} + +// Create creates a uniquely named, empty database, _test_, on +// the server whose admin DSN the environment variable env holds, and +// returns a pinged pool over it and the admin DSN pointed at it. An unset +// env fails the test: the caller's integration tier states that the server +// is expected. When the test ends the pool is closed and the database +// dropped, ending any session still open on it. +func Create(t testing.TB, env, prefix string) *Database { + t.Helper() + admin := os.Getenv(env) + if admin == "" { + t.Fatalf("%s is not set; run with the PostgreSQL it names up", env) + } + name := scratch(t, admin, prefix) + dsn := databaseDSN(t, admin, name) + return &Database{Pool: pool(t, dsn), DSN: dsn} +} + +// Migrated is Create with sets applied, in order, through migrate.New and +// Up under postgres.Dialect. +func Migrated(t testing.TB, env, prefix string, sets ...migrate.Set) *Database { + t.Helper() + d := Create(t, env, prefix) + m, err := migrate.New(d.Session(), sets, migrate.Options{}) + if err != nil { + t.Fatalf("migrate.New: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if err := m.Up(ctx); err != nil { + t.Fatalf("migrate Up: %v", err) + } + return d +} + +// scratch creates the database _test_ over a connection to +// admin and returns its name, registering its drop as a cleanup. The name +// is quoted, so it reaches the server exactly as the DSN spells it. +func scratch(t testing.TB, admin, prefix string) string { + t.Helper() + name := prefix + "_test_" + suffix(t) + ident := pgx.Identifier{name}.Sanitize() + db, err := sql.Open("pgx", admin) + if err != nil { + t.Fatalf("open admin connection: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if _, err := db.ExecContext(ctx, "CREATE DATABASE "+ident); err != nil { + // A create that timed out can still finish on the server, so the + // database is dropped if it exists, on a context of its own: ctx + // may be the one that expired. + dctx, dcancel := context.WithTimeout(context.Background(), timeout) + _, _ = db.ExecContext(dctx, "DROP DATABASE IF EXISTS "+ident+" WITH (FORCE)") + dcancel() + _ = db.Close() + t.Fatalf("create database %s: %v", name, err) + } + t.Cleanup(func() { + // WITH (FORCE) ends the database's other sessions, and the server + // can still report one closing, so the drop retries, each attempt + // with a deadline of its own so one stall does not use up the rest. + var err error + for attempt := range 4 { + if attempt > 0 { + time.Sleep(200 * time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + _, err = db.ExecContext(ctx, "DROP DATABASE "+ident+" WITH (FORCE)") + cancel() + if err == nil { + break + } + } + if err != nil { + t.Errorf("drop database %s: %v", name, err) + } + _ = db.Close() + }) + return name +} + +// pool opens a pool on dsn and pings it. Its cleanup is registered after +// the drop's, so it runs first: the pool closes before the database drops. +func pool(t testing.TB, dsn string) *sql.DB { + t.Helper() + p, err := sql.Open("pgx", dsn) + if err != nil { + t.Fatalf("open test database: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if err := p.PingContext(ctx); err != nil { + t.Fatalf("ping test database: %v", err) + } + return p +} + +// databaseDSN returns admin with its database replaced by name. +func databaseDSN(t testing.TB, admin, name string) string { + t.Helper() + u, err := url.Parse(admin) + if err != nil { + t.Fatalf("parse admin DSN: %v", err) + } + u.Path = "/" + name + return u.String() +} + +// suffix returns eight random hex characters, so parallel tests and +// packages never pick the same database name. +func suffix(t testing.TB) string { + var b [4]byte + if _, err := rand.Read(b[:]); err != nil { + t.Fatalf("random suffix: %v", err) + } + return hex.EncodeToString(b[:]) +} diff --git a/postgres/pgtest/pgtest_live_test.go b/postgres/pgtest/pgtest_live_test.go new file mode 100644 index 0000000..62fe1e8 --- /dev/null +++ b/postgres/pgtest/pgtest_live_test.go @@ -0,0 +1,109 @@ +//go:build integration + +// The live proof of pgtest runs against the PostgreSQL named by SQLATE_DSN +// (the compose stack: `mise run db:up`, then `mise run integration`) and +// skips when it is unset, the module's live-test convention. +package pgtest_test + +import ( + "context" + "database/sql" + "net/url" + "os" + "strings" + "testing" + + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/postgres/pgtest" +) + +const env = "SQLATE_DSN" + +// Proof: Migrated creates _test_, applies the set to it, and +// the database is dropped when the test that made it ends, even with a +// session of another pool still open on it. +func TestLive_MigratedDroppedWithSessionOpen(t *testing.T) { + admin := os.Getenv(env) + if admin == "" { + t.Skip(env + " not set") + } + ctx := context.Background() + set := migrate.Set{Name: "pgtest", Migrations: []migrate.Migration{{ + Version: 1, + Name: "widgets", + Up: "CREATE TABLE widgets (id integer PRIMARY KEY)", + Down: "DROP TABLE widgets", + Transactional: true, + }}} + + var name string + var held *sql.DB + var conn *sql.Conn + t.Cleanup(func() { + if conn != nil { + _ = conn.Close() + } + if held != nil { + _ = held.Close() + } + }) + t.Run("database", func(t *testing.T) { + d := pgtest.Migrated(t, env, "pgtest", set) + u, err := url.Parse(d.DSN) + if err != nil { + t.Fatal(err) + } + name = strings.TrimPrefix(u.Path, "/") + if !strings.HasPrefix(name, "pgtest_test_") { + t.Errorf("database name %q, want the pgtest_test_ prefix", name) + } + if !exists(t, admin, name) { + t.Fatalf("database %s does not exist after Migrated", name) + } + if _, err := d.Session().ExecContext(ctx, "INSERT INTO widgets (id) VALUES (1)"); err != nil { + t.Fatalf("the migrated table is not usable: %v", err) + } + + // A second pool, outside pgtest's cleanup, holds a session open on + // the database past the end of the subtest. + held, err = sql.Open("pgx", d.DSN) + if err != nil { + t.Fatal(err) + } + conn, err = held.Conn(ctx) + if err != nil { + t.Fatalf("hold a session: %v", err) + } + if err := conn.PingContext(ctx); err != nil { + t.Fatalf("ping the held session: %v", err) + } + }) + if name == "" || conn == nil { + t.Fatal("the subtest did not create a database and hold a session on it") + } + if exists(t, admin, name) { + t.Errorf("database %s still exists after its test's cleanup", name) + } + // The drop ended the held session rather than waiting for it. + if err := conn.PingContext(ctx); err == nil { + t.Error("the held session survived the drop") + } +} + +// exists reports whether the server admin connects to has the database. +func exists(t testing.TB, admin, name string) bool { + t.Helper() + db, err := sql.Open("pgx", admin) + if err != nil { + t.Fatal(err) + } + defer func() { _ = db.Close() }() + var found bool + err = db.QueryRowContext(context.Background(), + "SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1)", name).Scan(&found) + if err != nil { + t.Fatalf("read the database list: %v", err) + } + return found +}