/ship-pipeline:db-migration-safetyfrom ship-pipeline
Write or review Prisma and Supabase database migrations safely using the expand-contract pattern, idempotent SQL, and batched backfills. Use when adding/changing columns or tables, writing a migration PR, or reviewing one before merge — especially against Neon Postgres or Supabase in production.
Ships in ship-pipeline. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
The two failure modes this guards against: a migration that locks a large table for the duration of a deploy (site goes down), and a migration that succeeds but corrupts or loses data because it wasn't idempotent or wasn't backed up. Neither is recoverable by "just re-running the migration" — the first needs the expand-contract pattern, the second needs a MANDATORY backup confirmation before anything touches production.
Never do add-column + backfill + make-required in one migration against a live table with real traffic. Split into phases, each independently deployable:
NOT NULL constraint / drop the old table.Each phase is its own migration and its own deploy. Collapsing steps 1 and 4 into one migration is the single most common cause of an avoidable outage.
Classify the migration before writing it:
CONCURRENTLY) → generally safe, low risk.NOT NULL, UNIQUE, FK) → needs expand-contract, do last, after backfill confirmed.DROP COLUMN, DROP TABLE, type change) → needs expand-contract and a deprecation window (keep the old column at least one deploy cycle after the last read of it is removed from code).Avoid long table locks:
SET lock_timeout = '5s'; (tune to the app). Without it, an ALTER TABLE queued behind a long-running transaction blocks every query that arrives after it. If it times out, retry at a quieter time; do not raise the timeout to force it through.ALTER TABLE ... ADD COLUMN with a default on Postgres 11+ is fast (no full rewrite) as long as the default isn't a volatile expression — safe by default in most Prisma migrations.CREATE INDEX CONCURRENTLY for existing tables with real data — Prisma's default migration won't do this automatically, hand-edit the generated SQL:
-- CreateIndex
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_subscription_customer_id" ON "Subscription"("customerId");
Note: CONCURRENTLY cannot run inside a transaction block, and Prisma Migrate never generates it — you hand-edit it in:
migration.sql files applied by prisma migrate deploy): Prisma sends migration.sql to Postgres one statement at a time instead of as one script, so CREATE INDEX CONCURRENTLY works inside the migration file (prisma-engines#5767, shipped in Prisma 7.4.0). The catch: the file is no longer all-or-nothing. A failure partway through leaves the earlier statements applied, so write every statement to be safe to re-run (IF NOT EXISTS, IF EXISTS, guarded DO blocks) before you retry.CONCURRENTLY fails. Run the statement by hand (psql), then record the migration with prisma migrate resolve --applied <migration_name>.migrate deploy becomes db migrate; in CI and production it runs as npx prisma db migrate --to <ref> — Prisma docs, How migrations work): Prisma's docs say one db migrate run on Postgres is one transaction, so a raw-SQL step cannot run CREATE INDEX CONCURRENTLY, and createIndex is a plain CREATE INDEX that blocks writes while it builds (Prisma docs, Editing a migration). For a large table, build the index outside Prisma with psql, then follow the repo's own documented process to keep Prisma's record in sync. Prisma 8 was a release candidate in Prisma's 2026-08-02 changelog and its behavior may still change, so check the repo's installed Prisma version and the current docs before relying on any of this.CONCURRENTLY.CONCURRENTLY build leaves an INVALID index behind, and a re-run with IF NOT EXISTS silently skips it. Find it with \d <table> in psql (the index is listed as INVALID), DROP INDEX CONCURRENTLY it, and rebuild.NOT NULL: ADD CONSTRAINT c CHECK (col IS NOT NULL) NOT VALID; → VALIDATE CONSTRAINT c; → ALTER COLUMN col SET NOT NULL; (Postgres 12+ uses the validated check and skips the full-table scan) → drop c.ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID, then VALIDATE CONSTRAINT in a separate step.CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... UNIQUE USING INDEX.Batch backfills — never a single UPDATE touching the whole table:
-- Backfill in batches of 1000, sleeping isn't needed on Neon/Supabase managed Postgres
-- but keep batch size small enough that each statement is sub-second.
UPDATE "User" SET "normalizedEmail" = LOWER("email")
WHERE id IN (
SELECT id FROM "User" WHERE "normalizedEmail" IS NULL LIMIT 1000
);
-- repeat until 0 rows affected
For large tables, drive this from a script (Node/Prisma or a uv-run Python script) with a loop and a small delay between batches, logging progress so it's resumable if interrupted.
Idempotent SQL always — every migration must be safely re-runnable:
CREATE TABLE IF NOT EXISTS "WebhookEvent" (...);
ALTER TABLE "Subscription" ADD COLUMN IF NOT EXISTS "trialEndsAt" TIMESTAMP;
DROP TABLE IF EXISTS "LegacyBilling";
CREATE INDEX CONCURRENTLY IF NOT EXISTS ...;
Supabase migrations especially — the CLI can partially apply and re-run, so IF NOT EXISTS / IF EXISTS guards are not optional.
MANDATORY pre-flight backup confirmation before any migration touches production data (this is a hard gate, not a suggestion):
neon snapshots create --branch main --name pre-migration-<date> or neon branches create --parent main --name pre-migration-<date>.supabase backups list --project-ref <ref>, or Dashboard → Database → Backups). There is no way to trigger a manual backup; if the daily one is stale, take a dump (supabase db dump, plus --data-only for the rows, or pg_dump).pg_dump manually and confirm the file is non-empty before proceeding.Run in staging/branch first — Neon and Supabase both support branching; apply the migration to a branch, run the app's test suite and a manual smoke check against it, before applying to production.
IF NOT EXISTS/IF EXISTS on every DDL statement)NOT NULL/UNIQUE/FK constraint added in the same migration as the column that needs backfillinglock_timeout set before DDL on existing tablesCONCURRENTLY, run outside a transactionNOT NULL / FK / UNIQUE on a populated table added via NOT VALID + VALIDATE (or a unique index built CONCURRENTLY)DROP COLUMN/DROP TABLE) are in a separate, later migration than the code that stops using that columnPass: every box ticked. Fail: any box left open — fix it, or record in the PR why it does not apply.
NOT NULL constraint in one migration on a table that already has rows.CREATE INDEX the ORM generated against a large table.CONCURRENTLY build and trusting IF NOT EXISTS to repair the INVALID index.Sources: PostgreSQL docs for CREATE INDEX, ALTER TABLE and lock_timeout; Prisma docs on editing a migration and coming from Prisma ORM 7; Supabase docs on database backups.
Show the user: the classification (additive/constraint/destructive), the backup confirmation (snapshot ID + timestamp), the branch test result, and — for backfills — row counts before/after and how long the batched run took.
User, Customer, Subscription) — escalate to a second reviewer regardless of how small the change looks.What SKILL.md sets; muted values are Claude Code's defaults
16 skills in this plugin
/analytics-instrumentationPostHog event taxonomy and instrumentation review - object_verb naming, flat property schemas, identify/reset/group calls, PII exclusion, LLM usage events, a starter dashboard set (activation, retention, feature funnel), and a per-feature checklist. Use when instrumenting a new feature, auditing existing PostHog events, or setting up analytics for a new product, e.g. "add tracking", "what events should we fire", "review our PostHog events", "is there PII in analytics"./api-designREST conventions for Next.js App Router route handlers — resource naming, versioning, cursor pagination, one error envelope, Zod request/response validation, status-code rules, OpenAPI generated from Zod, and response scrubbing (no secrets, hashes, or other users' data). Use when asked to "design an API route", "add a new endpoint", "review this route handler", "fix our error responses", or "generate API docs"./backup-verifyConfirm database backups exist AND actually restore, by enumerating Neon branch snapshots / Supabase scheduled backups / pg_dump artifacts, restoring into a scratch branch, running smoke queries, and recording timestamped evidence. Use before any risky migration or production mutation, and on a monthly cadence regardless.npx claudepluginhub stylusnexus/agent-plugins --plugin ship-pipeline