Docs truth-sweep against ground truth (package.json, CI workflows): - npm → pnpm across evergreen docs (pnpm 11.25.0 is the package manager; npx tsx → pnpm exec tsx, npx ts-prune/jscpd → pnpm dlx, npm ci → pnpm install --frozen-lockfile, package-lock.json → pnpm-lock.yaml) - Jest → Vitest in README, CONTRIBUTING, COMMANDS (vitest 4 is installed) - Node claims: README 20+ → 22.13+ (engines) with CI/deploy on 24; deployment.md "Setup Node 20 (npm cache)" → Node 24 (pnpm cache), and the pipeline line now shows `pnpm run verify` as CI actually runs - TypeScript 5.x claims → 6 (typescript ^6.0.3); Next.js 14 → 16 in BLOG_SYSTEM, guides/ARCHITECTURE, AI_BOT_SYSTEM_PROMPT - COMMANDS.md: dropped nonexistent `dev:cms` script; services list fixed to db/meilisearch/listmonk (no redis in compose) - HR_RUNBOOK: `npm run test -- src/…` → `pnpm run test src/…` (pnpm passes args without the `--` separator) Historical records (docs/archive/**, dated audit reports, UPGRADE_PLAN) left as-is — they describe what was true when written. Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
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:
- Spins up
pgvector/pgvector:pg17(Hirn RAG needsCREATE EXTENSION vector). - Runs
scripts/db/apply-migrations-ci.sh, which applies every file inscripts/db/migrations/*.sqlinsort -Vorder (skips superseded duplicate005_messaging_system.sql). - 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:
- Production is the self-hosted Hetzner Postgres, and migrations apply on deploy — Drizzle Kit's
drizzle-kit migrateflow 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. - 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. - Migrations frequently need raw SQL —
EXCLUDEconstraints,DO $$ ... $$blocks for idempotent constraint adds,CREATE EXTENSION, partial unique indexes withWHEREclauses — 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
-
Pick a number. Look at the highest existing migration in
scripts/db/migrations/. Add 1. Format:NNN_short_description.sqlwhere NNN is zero-padded to 3 digits (e.g.080_team_compensation_and_leave.sql). -
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 aDO $$ … $$block that checkspg_constraintby name first. - For
EXCLUDE/ partial indexes / extensions, write the SQL directly.
-
Update the Drizzle schema in
src/db/schema/*.tsto mirror the migration. This is what TypeScript code reads — the two must stay in sync. Forgetting this is the most common foot-gun. -
Run locally:
pnpm run db:up(starts the Docker Postgres), thenbash scripts/db/run-migration.sh. The runner showsapplied: N · skipped: Mat the end; new migrations should appear in the applied count. -
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 unrecordedscripts/db/migrations/*.sqlto the prod DB before activating the new release — each migration runs in its own transaction withON_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 inschema_migrations.To apply one manually (e.g. out-of-band): ssh
ubuntu@167.233.22.31, readDATABASE_URLfrom/opt/revampit/app/.env, then:psql "$DATABASE_URL" -f scripts/db/migrations/NNN_your_migration.sqlThe
schema_migrationstable exists on the prod DB, so this single command both runs the migration and records that it ran. (Extension/owner ops needsudo -u postgres psql -d revampit— the app user is not a superuser.)
What the runner does
scripts/db/run-migration.sh:
- Connects to
$DB_HOST:$DB_PORT/$DB_NAME(defaults tolocalhost:5433/revampit_cms). CREATE TABLE IF NOT EXISTS schema_migrations (filename TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())— defensive bootstrap for fresh databases.- Reads all already-applied filenames from
schema_migrationsinto a temp file. - Iterates
*.sqlfiles inscripts/db/migrations/insort -Vorder. - 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. - Reports
applied: N · skipped: Mat the end.
Naming conventions
- Number first, descriptive name after —
080_team_compensation_and_leave.sql, notadd-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. (The004b_,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. UseDROP TABLE IF EXISTS,DROP COLUMN IF EXISTS,DROP CONSTRAINT IF EXISTS. - Long-running data backfills inside the migration. A multi-second
UPDATElocks 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.