/ai-stuff:postgres-safe-migrationsfrom ai-stuff
Write and review PostgreSQL schema migrations that run on a live database without blocking traffic: lock_timeout and retries, the DDL lock queue, which ALTERs rewrite the table, adding columns/defaults/NOT NULL, constraints and foreign keys with NOT VALID + VALIDATE, CREATE/DROP INDEX CONCURRENTLY and invalid indexes, int-to-bigint conversions, batched backfills, renames, table swaps, enums, and partition attach/detach. Use whenever you write, generate, or review a migration (raw SQL, Rails, Django, Alembic, Prisma, Flyway, etc.) that targets a Postgres database with real traffic or large tables.
Ships in ai-stuff. 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.
A playbook distilled from Scaling Postgres (2018–2026). Evidence, incidents
and version history are in reference.md. For what the target
schema should look like, use postgres-schema-design.
lock_timeout, and the migration
retries on timeout.
ALTER TABLE forms need ACCESS EXCLUSIVE, even the instant ones.SELECT included, then queues behind the DDL.
A metadata-only change becomes an outage.lock_timeout between 100 ms and 2 s. Lower it for hot tables.
Keep it below deadlock_timeout (default 1 s) when you can.statement_timeout for the migration session too, so nothing
runs unbounded.
0, only for steps that are expected to be long
and that don't block: CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT,
and backfill batches.pg_stat_activity (xact_start, state). Don't run DDL
while pg_dump or a big batch job is running.Template for a migration step:
SET lock_timeout = '1s'; -- per session/transaction, not global
SET statement_timeout = '15s';
ALTER TABLE orders ADD COLUMN note text; -- one change
-- on lock_not_available (SQLSTATE 55P03): roll back, sleep with jitter, retry
LOOP that catches lock_not_available also works. Each
exception block is a subtransaction, and the outer transaction keeps any
locks it already took, so keep that loop to a single statement.| Operation | Safe? | How |
|---|---|---|
ADD COLUMN nullable, no default | Instant | lock_timeout + retry |
ADD COLUMN ... DEFAULT <constant/non-volatile> | Instant (PG11+) | lock_timeout + retry |
ADD COLUMN ... DEFAULT <volatile> (random(), clock_timestamp(), uuidv7()) | Rewrites table | Add nullable, set default, backfill in batches, then NOT NULL recipe |
DROP COLUMN | Instant (space not reclaimed) | lock_timeout; remove app references first |
ALTER COLUMN TYPE (int→bigint, int→text, …) | Rewrites table + indexes | Expand/contract recipe below |
varchar(n) → wider varchar / text | Instant [uncited, standard behavior] | lock_timeout |
SET DEFAULT / DROP DEFAULT | Instant | lock_timeout (hot tables need tight timeout + many retries) |
SET NOT NULL | Full scan under ACCESS EXCLUSIVE | CHECK NOT VALID → VALIDATE → SET NOT NULL (PG12+), or PG18 NOT NULL ... NOT VALID |
ADD CHECK / ADD FOREIGN KEY | Full scan under lock | NOT VALID, then VALIDATE CONSTRAINT separately |
ADD UNIQUE / PRIMARY KEY | Index build under lock | CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... USING INDEX |
CREATE INDEX | Blocks writes | CREATE INDEX CONCURRENTLY |
DROP INDEX | Takes ACCESS EXCLUSIVE | DROP INDEX CONCURRENTLY |
REINDEX | Blocks writes | REINDEX ... CONCURRENTLY (PG12+, partitioned PG14+) |
| Rename column / table | Instant, but breaks running app code | Expand/contract or a view shim (below) |
VACUUM FULL / CLUSTER / SET TABLESPACE / SET (UN)LOGGED | Rewrite under ACCESS EXCLUSIVE | pg_repack / pg_squeeze, PG19 REPACK CONCURRENTLY, or a maintenance window |
Enum ADD VALUE | Instant | OK in a transaction on PG12+; usable in the same transaction on PG17+; values can't be dropped or reordered |
Not sure whether something rewrites? Run it on a throwaway copy and compare
SELECT pg_relation_filenode('t') before and after. A new filenode means the
table was rewritten.
ALTER TABLE t ADD CONSTRAINT t_c_not_null CHECK (c IS NOT NULL) NOT VALID; -- brief lock
ALTER TABLE t VALIDATE CONSTRAINT t_c_not_null; -- scans, doesn't block writes
ALTER TABLE t ALTER COLUMN c SET NOT NULL; -- uses the validated CHECK, no scan
ALTER TABLE t DROP CONSTRAINT t_c_not_null;
ALTER TABLE t ADD CONSTRAINT t_c_nn NOT NULL c NOT VALID;
followed by VALIDATE CONSTRAINT.ALTER TABLE child ADD CONSTRAINT child_parent_fk
FOREIGN KEY (parent_id) REFERENCES parent(id) NOT VALID; -- brief lock on BOTH tables
ALTER TABLE child VALIDATE CONSTRAINT child_parent_fk; -- separate step
child(parent_id) first, with CREATE INDEX CONCURRENTLY.lock_timeout on each.CREATE UNIQUE INDEX CONCURRENTLY t_email_key ON t (email);
ALTER TABLE t ADD CONSTRAINT t_email_key UNIQUE USING INDEX t_email_key;
-- or: ADD CONSTRAINT t_pkey PRIMARY KEY USING INDEX t_pkey_idx (columns must be NOT NULL)
CREATE/DROP INDEX CONCURRENTLY and REINDEX CONCURRENTLY can't run inside
a transaction block. Disable the framework's per-migration transaction:
disable_ddl_transaction!atomic = Falsewith op.get_context().autocommit_block()statement_timeout. Set it to 0 for that step only.SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;DROP INDEX CONCURRENTLY, then rebuild.CREATE INDEX CONCURRENTLY IF NOT EXISTS. After a failure it
silently skips the rebuild and leaves the invalid index in place.pg_stat_progress_create_index.CREATE INDEX ... ON ONLY parent (creates it invalid, instantly).CREATE INDEX CONCURRENTLY on each partition.ALTER INDEX parent_idx ATTACH PARTITION child_idx for each one.CHECK constraint matching the partition
bound first, so ATTACH PARTITION skips the validation scan.DETACH PARTITION ... CONCURRENTLY (PG14+). It can't run in
a transaction block, and it fails if a default partition exists.ADD COLUMN new_id bigint (with lock_timeout).id into new_id on INSERT/UPDATE.CREATE UNIQUE INDEX CONCURRENTLY on new_id. Add NOT NULL via the
CHECK recipe.lock_timeout:
ADD CONSTRAINT ... PRIMARY KEY USING INDEXEmergency, the sequence is nearly exhausted: restart it in the negative range to buy time.
ALTER SEQUENCE t_id_seq MINVALUE -2147483648 INCREMENT BY -1 RESTART WITH -1;
This is standard Postgres syntax, not taken from the transcripts. Code that
sorts by id to mean "newest" breaks, so use it only as a stopgap.
Never run one giant UPDATE. It holds row locks, triggers checkpoint and WAL
storms, lags replicas, and bloats the table.
Walk the key in keyset batches:
UPDATE t SET new_col = <expr>
WHERE id > $last AND id <= $last + 5000 AND new_col IS DISTINCT FROM <expr>;
COMMIT in the loop, or a driver
script. A function can't commit.Run VACUUM (and ANALYZE) between rounds on big backfills. Reindex
afterwards if bloat is large.
Static tables can be walked faster by ctid page ranges.
CREATE VIEW old_name AS SELECT * FROM new_name. Simple views are
updatable. Deploy code that uses the new name, then drop the view.DROP COLUMN under a view fails until you drop
and recreate the view.Use it for volatile defaults, column reorders, or shrinking a huge table.
Grants, RLS policies, triggers, FKs, publications, statistics objects, and dependent views/functions are tied to the old table's OID and do not follow the name. Recreate them all. This needs about 2x disk.
lock_timeout and has a retry path.ALTER COLUMN TYPE, volatile default, or SET NOT NULL on a large
table without the recipes above.NOT VALID then validated.CONCURRENTLY, outside a transaction. There is no
IF NOT EXISTS on concurrent builds, and a check for invalid indexes
follows.strong_migrations (Rails) flags unsafe operations, but add lock_timeout
yourself.pgroll does reversible, versioned-view migrations.pg_repack and pg_squeeze do online rewrites. They need about 2x disk and
take brief ACCESS EXCLUSIVE locks.REPACK CONCURRENTLY makes a single swap attempt with no retry. It
is not MVCC-safe for older repeatable-read snapshots.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub pauldotsh/ai-stuff --plugin ai-stuff25 skills in this plugin
/brainstormingYou MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation./codebase-designShared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary./dispatching-parallel-agentsUse ONLY when the developer has explicitly told you to dispatch subagents — never infer or self-authorize it. Splits 2+ independent tasks across isolated subagents, assigns them cheap models, and polls at a per-harness cadence that preserves prompt cache (Claude Code vs Codex/opencode)./frontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults./grillingGrill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases./handoffCompact the current conversation into a handoff document for another agent to pick up.