Nothing said how a migration run ended. On failure, the CLI printed the
PostgreSQL error with the failing SQL, but not which migration failed or
whether anything was saved.
After a failed run, the reporter asks PostgreSQL how the transaction
ended (`pg_xact_status` on the captured transaction ID, plus the saved
schema version). Every run logs one outcome line: committed, rolled
back, committed before failure, unknown, lock timeout, dirty schema, or
failed before start. Every failure line has an `error` field.
The error names the failed migration and gives PostgreSQL's short
message and SQLSTATE, without the SQL or detail text, which can contain
row values.
```
[info] committed database migrations status=success count=2 from_version=1 final_version=3 transaction_status=committed total_duration_ms=0
[erro] migration failed, transaction rolled back, no changes saved status=failure count=1 version=3 name=step_3 final_version=1 sqlstate=23505 transaction_status=aborted total_duration_ms=0 failed_duration_ms=0 error="migration 3 (step_3): migration failed: duplicate key value violates unique constraint \"a_pkey\" (sqlstate=23505)"
```
Closes ENT-236
_Written with Claude Code and Coder Agents, reviewed and tested by
@kirstaeff._
Migrations run at server startup with no output, so admins can't tell
which migration is running, whether it waits on a lock, or how far it
got.
This adds a reporter to the migration driver. It logs:
- the pending migrations, and each step with its position and duration;
- the migration lock (debug level);
- a heartbeat every 10s during a lock wait or a long step, with the
connection state from `pg_stat_activity` and the blocking sessions.
The migration transaction is named `coder-migrate/<version>`, so other
instances and admins can see it. Heartbeat queries run on their own
connection and never delay the migration.
API: `Up(db, opts...)`, with `WithFS` (replaces `UpWithFS`) and
`WithLogger`. Without a logger, nothing is logged. Server startup turns
it on in #31790.
```
[info] database migration required from_version=1 target_version=3 pending=2
[info] applying database migration version=3 name=step_3 position=2 total=2
[info] still applying database migration elapsed_ms=1000 state=waiting_on_lock wait_event=relation blocked_by=[blocker] version=3 name=step_3 position=2 total=2
[info] database migration applied, pending commit version=3 name=step_3 position=2 total=2 duration_ms=1000
```
Tests compare log output with golden files in
`coderd/database/migrations/testdata/reporter`.
Closes ENT-235
_Written with Claude Code and Coder Agents, reviewed and tested by
@kirstaeff._
## Problem
`TestMigrate/Parallel` flakes with:
```
timeout: can't acquire database lock
```
## Root Cause
The test runs two concurrent `migrations.Up(db)` calls on the same
database. golang-migrate wraps every `Lock()` call with a [15-second
timeout](https://github.com/golang-migrate/migrate/blob/v4.19.0/migrate.go#L29)
(`DefaultLockTimeout`). Our `pgTxnDriver.Lock()` uses
`pg_advisory_xact_lock`, which blocks until the lock is available. With
430+ migrations, the first caller can hold the lock well beyond 15s (the
failing test ran for 25.88s), causing the second caller to hit the
timeout.
## Fix
Set `m.LockTimeout = 2 * time.Minute` after creating the
`migrate.Migrate` instance in `setup()`. Since `pg_advisory_xact_lock`
releases automatically when the transaction commits, there's no risk of
a stuck lock — we just need to wait long enough for a concurrent
migration to finish.
This PR is the first in a series aimed at closing
[#15109](https://github.com/coder/coder/issues/15109).
### Changes
- **Template Database Creation:**
`dbtestutil.Open` now has the ability to create a template database if
none is provided via `DB_FROM`. The template database’s name is derived
from a hash of the migration files, ensuring that it can be reused
across tests and is automatically updated whenever migrations change.
- **Optimized Database Handling:**
Previously, `dbtestutil.Open` would spin up a new container for each
test when `DB_FROM` was unset. Now, it first checks for an active
PostgreSQL instance on `localhost:5432`. If none is found, it creates a
single container that remains available for subsequent tests,
eliminating repeated container startups.
These changes address the long individual test times (10+ seconds)
reported by some users, likely due to the time Docker took to start and
complete migrations.
Updates coder/customers#365
This PR updates our migration framework to run all migrations in a single transaction. This is the same behavior we had in v1 and ensures that failed migrations don't bring the whole deployment down. If a migration fails now, it will automatically be rolled back to the previous version, allowing the deployment to continue functioning.