Files
evig/docs/MIGRATIONS.md
CatoandClaude be2f01859d docs: correct drift — evig host, /opt/evig box paths, email provider, CI smoke target (#573)
- Production host is evig.orangecat.ch everywhere a doc presents the current
  address; revampit.orangecat.ch is the retired 308 redirect.
- Box was renamed /opt/revampit -> /opt/evig (systemd evig-app, evig-cron@*,
  evig-backup, scripts/selfhost-deploy-evig.sh); docs and the Layer B list
  still named the old paths and a deploy script that no longer exists.
- CLAUDE.md claimed auth-smoke/inventory-smoke target the old host; CI now
  defaults PLAYWRIGHT_BASE_URL to evig.orangecat.ch, so the redirect has no
  CI coverage. Say so.
- Local dev DB is the Docker Postgres on 5433, not Neon.
- Email is Resend first (src/config/email.ts), not Listmonk/Brevo.
- README: no "Swiss-compliant donation receipts" while in formation; real
  test layout, eight locales, actual CI jobs.
- CONTRIBUTING / PR template / REVIEW: evig name, pnpm, Node 22.13+,
  messages/ path; no donate link to Revamp-IT.
- ARCHITECTURE_QUICK_START: drop the example that granted staff by e-mail.
- Payment setup docs: canonical webhook URLs plus a note on providers
  configured before the rename.


Claude-Session: https://claude.ai/code/session_01PJkbo18cRNXtgPWZN2S9cD

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-19 12:51:27 +02:00

8.2 KiB

Database Migrations

Single source of truth for "how schema changes reach production."

Last Updated: 2026-07-04

Recent prod applies: 114_listing_questions.sql — manual on Hetzner 2026-07-04 (ahead of app deploy; idempotent CREATE TABLE IF NOT EXISTS).

CI drift check

Pull requests and pushes to main run the Migration Drift Check job in .github/workflows/ci.yml:

  1. Spins up pgvector/pgvector:pg17 (Hirn RAG needs CREATE EXTENSION vector).
  2. Runs scripts/db/apply-migrations-ci.sh, which applies every file in scripts/db/migrations/*.sql in sort -V order (skips superseded duplicate 005_messaging_system.sql).
  3. Fails the job if any migration errors — catches fresh-DB breakage before deploy.

Local repro:

docker run --rm -d --name mig -e POSTGRES_PASSWORD=ci -e POSTGRES_DB=revampit_drift -p 54328:5432 pgvector/pgvector:pg17
PGHOST=localhost PGPORT=54328 PGUSER=postgres PGPASSWORD=ci PGDATABASE=revampit_drift \
  bash scripts/db/apply-migrations-ci.sh

Production still uses scripts/db/run-migration.sh (tracked via schema_migrations); the CI script is a full replay on an empty database, not the prod runner.

TL;DR

Where What Status
scripts/db/migrations/*.sql Hand-written SQL migrations, sequentially numbered Canonical — every schema change goes here
scripts/db/run-migration.sh Dev runner against local Postgres, idempotent via schema_migrations tracking table (added in migration 075) Used in dev only
./drizzle/ Drizzle Kit-generated SQL + snapshot JSON Not used for migrations. Useful for drizzle-kit studio schema browsing; ignore for migration purposes.

To ship a schema change: add scripts/db/migrations/NNN_descriptive_name.sql, increment the number, run locally, push.

Why two folders

Earlier in the project Drizzle Kit's autogenerated migrations were trialled. They live in ./drizzle/ as historical artifact. The trial was retired in favour of hand-written SQL for three reasons:

  1. Production is the self-hosted Hetzner Postgres, and migrations apply on deploy — Drizzle Kit's drizzle-kit migrate flow assumes one canonical DB driven from a dev machine. Our actual flow is "apply locally via the runner, then let the deploy apply unrecorded migrations to the prod Hetzner DB" (see Apply to production below). The runner + deploy hook need bespoke logic, so the SQL files are authored by hand.
  2. Idempotency + tracking — migration 075 added schema_migrations(filename PRIMARY KEY, applied_at) so the runner skips already-applied files. Drizzle Kit's mechanism uses a different tracking table; running both would double-track and double-apply.
  3. Migrations frequently need raw SQL — EXCLUDE constraints, DO $$ ... $$ blocks for idempotent constraint adds, CREATE EXTENSION, partial unique indexes with WHERE clauses — all easier to write directly than coax from a schema diff.

Drizzle Kit itself remains installed (drizzle-kit in devDependencies) — it's still useful for drizzle-kit studio to browse the DB and for occasional schema introspection. Just don't run drizzle-kit generate and add the output to source control.

Adding a migration

  1. Pick a number. Look at the highest existing migration in scripts/db/migrations/. Add 1. Format: NNN_short_description.sql where NNN is zero-padded to 3 digits (e.g. 080_team_compensation_and_leave.sql).

  2. Write idempotent SQL. Every DDL statement should be safe to run twice:

    • CREATE TABLE IF NOT EXISTS …
    • ALTER TABLE … ADD COLUMN IF NOT EXISTS …
    • CREATE INDEX IF NOT EXISTS …
    • For ADD CONSTRAINT (no IF NOT EXISTS in Postgres), wrap in a DO $$ … $$ block that checks pg_constraint by name first.
    • For EXCLUDE / partial indexes / extensions, write the SQL directly.
  3. Update the Drizzle schema in src/db/schema/*.ts to mirror the migration. This is what TypeScript code reads — the two must stay in sync. Forgetting this is the most common foot-gun.

  4. Run locally: pnpm run db:up (starts the Docker Postgres), then bash scripts/db/run-migration.sh. The runner shows applied: N · skipped: M at the end; new migrations should appear in the applied count.

  5. Apply to production — automatic on deploy. Production runs a self-hosted Postgres 17 on the Hetzner box (DATABASE_URL=postgresql://…@localhost:5432/revampit). The deploy (scripts/selfhost-deploy-evig.sh) applies any unrecorded scripts/db/migrations/*.sql to the prod DB before activating the new release — each migration runs in its own transaction with ON_ERROR_STOP, and a failed migration aborts the deploy. So in the normal case you just push; the deploy lands the migration and records it in schema_migrations.

    To apply one manually (e.g. out-of-band): ssh ubuntu@167.233.22.31, read DATABASE_URL from /opt/evig/app/.env, then:

    psql "$DATABASE_URL" -f scripts/db/migrations/NNN_your_migration.sql
    

    The schema_migrations table exists on the prod DB, so this single command both runs the migration and records that it ran. (Extension/owner ops need sudo -u postgres psql -d revampit — the app user is not a superuser.)

What the runner does

scripts/db/run-migration.sh:

  1. Connects to $DB_HOST:$DB_PORT/$DB_NAME (defaults to localhost:5433/revampit_cms).
  2. CREATE TABLE IF NOT EXISTS schema_migrations (filename TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()) — defensive bootstrap for fresh databases.
  3. Reads all already-applied filenames from schema_migrations into a temp file.
  4. Iterates *.sql files in scripts/db/migrations/ in sort -V order.
  5. For each file not in the applied set: wraps it in BEGIN; \i file; INSERT INTO schema_migrations …; COMMIT;. A failure rolls back and the file is NOT recorded as applied.
  6. Reports applied: N · skipped: M at the end.

Naming conventions

  • Number first, descriptive name after — 080_team_compensation_and_leave.sql, not add-comp.sql.
  • Underscores in the descriptive part — match the rest of the directory.
  • Plural table names in the description when the migration touches a single table — 075_schema_migrations_tracking.sql.
  • No version suffixes — if migration 080 needs a follow-up, the follow-up is migration 081, not 080b. (The 004b_, 005c_ etc. files in history pre-date this rule.)

What goes in a migration vs in code

In a migration (SQL) In Drizzle schema (src/db/schema/*.ts) In an API route
CREATE TABLE, ALTER TABLE Column definitions matching the migration Reading/writing the data
CREATE INDEX, CREATE UNIQUE INDEX index(…) / uniqueIndex(…) calls in the (table) => [...] array —
CHECK constraints, EXCLUDE constraints Comment-only documentation (Drizzle .check() exists but is opt-in — see #5 sweep) —
FOREIGN KEY definitions with ON DELETE policy .references(() => other.id, { onDelete: 'cascade' }) —
Data backfills (UPDATE … to populate new columns from old ones) — —
INSERT INTO schema_migrations records — —

Common mistakes to avoid

  • Editing a migration that's already been applied. Once a file's name is in schema_migrations, the runner won't reapply it. Edits are dead. Always add a follow-up migration instead.
  • Forgetting to update src/db/schema/*.ts. The migration succeeds, but TypeScript code can't see the new column. Drift caught only at runtime.
  • Dropping things without IF EXISTS. Re-running the migration on a database that already had the drop fails. Use DROP TABLE IF EXISTS, DROP COLUMN IF EXISTS, DROP CONSTRAINT IF EXISTS.
  • Long-running data backfills inside the migration. A multi-second UPDATE locks the table. For large backfills, split into a separate non-blocking script and gate the schema change on its completion.

See also

  • scripts/db/migrations/075_schema_migrations_tracking.sql — the migration that introduced the tracking table + bootstrapped it with the 74 prior filenames.
  • scripts/db/run-migration.sh — the runner.
  • docs/ARCHITECTURE_DATABASE_BACKEND.md — schema overview at a higher level.