--- name: DB Migration description: Add a PostgreSQL migration the Superbrain way — schema.sql + ordered additive migration file + convergence/atomicity proof. Use whenever a change alters the database schema. --- # DB migration workflow Superbrain has TWO paths to the same schema and both must stay in lockstep: - `db/schema.sql` — initializes a fresh database. - `db/migrations/NNN_*.sql` — ordered, additive migrations applied by `db/migrate.sh` in ONE transaction under a fixed advisory lock. `make db-converge` proves the two paths are equivalent and that apply/record is atomic. A change that edits only one path fails convergence. ## Steps 1. **Find the next number.** `ls db/migrations | sort | tail -1` → use the next zero-padded integer (currently 026, so the next is `027_.sql`). 2. **Edit `db/schema.sql`** so a fresh database gets the final shape (tables, columns, indexes, constraints). 3. **Add `db/migrations/027_.sql`** with the additive statements that bring an existing database from the previous shape to the new one. 4. **Run the gate:** `make db-converge` (runs `db/check-convergence.sh` plus `db/migrate-atomicity.sh` against scratch databases). It must pass. 5. If the change is behavioral, run the DB-backed tests: `docker compose run --rm tests go test -race -run TestName ./internal/http` (or `make integration` for the full suite). ## Hard rules (the runner enforces these) - **No `BEGIN`/`COMMIT`** in a migration file — `migrate.sh` wraps each file in one transaction. A file that manages its own transaction breaks the ledger. - **No `CREATE INDEX CONCURRENTLY`, `VACUUM`, or other statements that cannot run inside a transaction block** — handle those as explicit operator steps outside the ledger. - **Additive only.** Prefer `ADD COLUMN IF NOT EXISTS`, `CREATE TABLE IF NOT EXISTS`, etc. Migrations are checksummed and immutable once applied — never edit an existing migration file; add a new one. - **Idempotent by convention** (defense in depth; migration 001 must stay so for first ledger adoption on legacy-upgraded databases). - Every user belongs to exactly one tenant; single-tenant deployments use the implicit `tenant-default` row — do not special-case "no tenant". ## Reference - `db/migrate.sh` — runner + ledger + preflight rules (read its header). - `db/migrations/020_webdav_shares.sql`, `021_caldav_calendars.sql`, `022_carddav_shares.sql` — recent examples of the ledger/tombstone pattern. - Root `AGENTS.md` → "Database Layer".