database-migrations
Skill1 starsChanged 15 days agoMITView on GitHub
Safe, reversible database migration patterns: forward-only production changes, expand-contract zero-downtime renames, concurrent indexes, batched backfills, and per-tool workflows for PostgreSQL, Prisma, and Drizzle. Use when writing a schema or data migration, adding a column or index to a large table, planning a rollback, or preparing a zero-downtime deploy.
71 other projects use a version of this, 42 of them edited.
Adopted by
Most recently taken up by
- KevinLoichot/everything-claude-codeedited, first seen Nov 29, 2026
- aayushsoam/clawbot-plusedited, first seen Nov 29, 2026
- multiplex-ai/muggle-ai-teamsedited, first seen Nov 29, 2026
- Cyvid7-Darus10/claude-code-configedited, first seen Nov 29, 2026
- satvikgbusiness-jpg/Claude-skillsedited, first seen Nov 29, 2026
- leileigwl/claude-skillsedited, first seen Nov 29, 2026
Used with
Projects with it also use docker-and-compose, add-a-use-case and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
JameMy0001Skilldocker-and-compose
Production containerization patterns, multi-stage Dockerfiles, Docker Compose orchestrations, non-root security hardening, and cache optimization.
Also in 6 projects that use this
LeanMeanCleanAppsSkilladd-a-use-case
How to add a command or query to the Application layer as a vertical slice (request, handler, validator, tests) using source-generated Mediator. Use when adding a new feature, a new query, or a new write operation.
Also in 5 projects that use this
LeanMeanCleanAppsSkillbranches-and-pull-requests
Branch naming (feature/, fix/, chore/), how labels and release notes follow from the branch, the pull request template, and how changes get merged in the template repository. Use when creating a branch, writing a commit or opening a pull request.
Also in 5 projects that use this
- +9 more from LeanMeanCleanApps
Other versions71 projects use a version of this.
Word for word · 0
None found.
Edited · 42
- loulanyue/awesome-claude-notes★ 27249% same
- Fmarzochi/EGC★ 6149% same
- skateddu/claude-code-python-setup★ 2863% same
- gongyijie85/dsh-ecc★ 849% same
- zero-click/zero-ratchet★ 849% same
- Ronnasayd/aipp★ 531% same
- chadixearth/graphyloop★ 347% same
- aayushsoam/clawbot-plus★ 260% same
- Badhon-00/MDCP★ 252% same
- cyruspastelero/dot-agent★ 260% same
32 more not listed
Wrote their own version · 29
- LeanMeanCleanApps/CleanMinimalApi★ 401same name
- langchain-ai/skills-benchmarks★ 116same name
- LeanMeanCleanApps/CleanGraphQLApi★ 13same name
- wpank/ai★ 11same name
- reddygopalkrishna/developer-agent-skills★ 8same name
- LeanMeanCleanApps/CleanWebApi★ 4same name
- matt-riley/agent-skills★ 4same name
- sponge-b0b/Polaris★ 4same name
- kimtth/agent-skill-100-lines-or-less★ 2same name
- LeanMeanCleanApps/CleanModelContextProtocol★ 2same name
19 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository6 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- client-tzSkill
- new-projectSkill
- time-registerSkill
- docker-patternsSkill
- security-reviewSkill
The file
We split this skill into the rules it gives an agent
3 rules. 1 is common, 2 are distinctive, and 0 are very specific to this project.
1
Common
Most of the 68 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Common: line 31
Before applying any migration:
- Distinctive: line 59
After the backfill is verified.
- Distinctive: line 92
Never rename directly in production.
“Common” is measured: kept by at least 6 in 10 of the 68 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Project rules (AGENTS.md, CLAUDE.md), the base rules in ~/.claude/rules and the existing repo contract win over this skill. Apply it to new and changed code only.
Database Migration Patterns
Safe, reversible database schema changes for production systems.
When to Activate
- Creating or altering database tables
- Adding/removing columns or indexes
- Running data backfills or transforms (batched scripts, not migrations)
- Planning zero-downtime schema changes
- Setting up migration tooling for a new project
Core Principles
- Every schema change is a migration — never alter production databases manually
- Migrations are forward-only in production — rollbacks use new forward migrations
- A backfill is not a migration — the migration holds the DDL; the data backfill is a separate batched script in the repo, run outside the migration: safe to rerun,
--dry-runwith counts, prints the target DB name (no URL) before writing and exits if it is the wrong one - Test migrations against production-sized data — a migration that works on 100 rows may lock on 10M
- Migrations are immutable once deployed — never edit a migration that has run in production
Migration Safety Checklist
Before applying any migration:
- No full table locks on large tables (use concurrent operations)
- New columns have defaults or are nullable; NOT NULL on a large or hot table via
CHECK (col IS NOT NULL) NOT VALID→VALIDATE CONSTRAINT→SET NOT NULL(see below) lock_timeoutset for DDL on a large or hot table- Before a DROP or SET NOT NULL that depends on a backfill: the backfill is done and verified (count of rows where the new column IS NULL or differs = 0) and a backup is taken
- Indexes created concurrently (not inline with CREATE TABLE for existing tables)
- Tested against a copy of production data
- Rollback plan documented
PostgreSQL Patterns
Adding a Column Safely
-- GOOD: Nullable column, no lock
ALTER TABLE users ADD COLUMN avatar_url TEXT;
-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;
-- BAD: NOT NULL without default on existing table (requires full rewrite)
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
-- This locks the table and rewrites every rowSetting NOT NULL on a Large Table
After the backfill is verified. Each step is its own migration (own transaction):
-- Migration A: instant, no scan
SET lock_timeout = '5s';
ALTER TABLE users ADD CONSTRAINT users_role_not_null CHECK (role IS NOT NULL) NOT VALID;
-- Migration B: scans the table without blocking reads or writes
SET lock_timeout = '5s';
ALTER TABLE users VALIDATE CONSTRAINT users_role_not_null;
-- Migration C: PG12+ uses the validated CHECK, so SET NOT NULL does not scan;
-- then the helper CHECK is dropped
SET lock_timeout = '5s';
ALTER TABLE users ALTER COLUMN role SET NOT NULL;
ALTER TABLE users DROP CONSTRAINT users_role_not_null;Adding an Index Without Downtime
-- BAD: Blocks writes on large tables
CREATE INDEX idx_users_email ON users (email);
-- GOOD: Non-blocking, allows concurrent writes
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
-- Note: CONCURRENTLY cannot run inside a transaction block
-- Most migration tools need special handling for thisRenaming a Column (Zero-Downtime)
Never rename directly in production. Use the expand-contract pattern:
-- Step 1: Add new column (migration 001)
ALTER TABLE users ADD COLUMN display_name TEXT;
-- Step 2: Backfill existing rows with a separate batched script, not a migration
-- (batched pattern in "Large Data Migrations" below)
-- Step 3: Update application code to read/write both columns
-- Deploy application changes
-- Step 4: Before the drop: backfill verified (this count is 0) and a backup taken
SELECT count(*) FROM users WHERE display_name IS DISTINCT FROM username;
-- Then stop writing to old column, drop it (migration 002)
ALTER TABLE users DROP COLUMN username;Removing a Column Safely
-- Step 1: Remove all application references to the column
-- Step 2: Deploy application without the column reference
-- Step 3: Drop column in next migration
ALTER TABLE orders DROP COLUMN legacy_status;Large Data Migrations
-- BAD: Updates all rows in one transaction (locks table)
UPDATE users SET normalized_email = LOWER(email);
-- GOOD: Batch update with progress, run as a separate script, not inside a migration:
-- COMMIT inside DO fails in a transaction block, and migration tools wrap each migration in one
DO $$
DECLARE
batch_size INT := 10000;
rows_updated INT;
BEGIN
LOOP
UPDATE users
SET normalized_email = LOWER(email)
WHERE id IN (
SELECT id FROM users
WHERE normalized_email IS NULL
AND email IS NOT NULL -- processed rows must drop out, or the loop never ends
LIMIT batch_size
FOR UPDATE SKIP LOCKED
);
GET DIAGNOSTICS rows_updated = ROW_COUNT;
RAISE NOTICE 'Updated % rows', rows_updated;
EXIT WHEN rows_updated = 0;
COMMIT;
END LOOP;
END $$;Prisma (TypeScript/Node.js)
Workflow
# Create migration from schema changes
npx prisma migrate dev --name add_user_avatar
# Apply pending migrations in production
npx prisma migrate deploy
# Reset database (dev only)
npx prisma migrate reset
# Generate client after schema changes
npx prisma generateSchema Example
model User {
id String @id @default(cuid())
email String @unique
name String?
avatarUrl String? @map("avatar_url")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
orders Order[]
@@map("users")
@@index([email])
}Custom SQL Migration
For operations Prisma cannot express (concurrent indexes):
# Create empty migration, then edit the SQL manually
npx prisma migrate dev --create-only --name add_email_index-- migrations/20240115_add_email_index/migration.sql
-- Prisma cannot generate CONCURRENTLY, so we write it manually
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);Drizzle (TypeScript/Node.js)
Workflow
# Generate migration from schema changes
npx drizzle-kit generate
# Apply migrations
npx drizzle-kit migrate
# Push schema directly (dev only, no migration file)
npx drizzle-kit pushSchema Example
import { pgTable, text, timestamp, uuid, boolean } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
email: text("email").notNull().unique(),
name: text("name"),
isActive: boolean("is_active").notNull().default(true),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
});Zero-Downtime Migration Strategy
For critical production changes, follow the expand-contract pattern:
Phase 1: EXPAND
- Add new column/table (nullable or with default)
- Deploy: app writes to BOTH old and new
- Backfill existing data (separate batched script, not a migration)
Phase 2: MIGRATE
- Deploy: app reads from NEW, writes to BOTH
- Verify data consistency
Phase 3: CONTRACT
- Deploy: app only uses NEW
- Before the drop: backfill verified (rows where NEW IS NULL or differs = 0), backup taken
- Drop old column/table in separate migrationTimeline Example
Day 1: Migration adds new_status column (nullable)
Day 1: Deploy app v2 — writes to both status and new_status
Day 2: Run the batched backfill script for existing rows (not a migration)
Day 3: Deploy app v3 — reads from new_status only
Day 7: Backfill check is 0 and a backup is taken; migration drops old status columnAnti-Patterns
| Anti-Pattern | Why It Fails | Better Approach |
| Manual SQL in production | No audit trail, unrepeatable | Migration files for schema; a data backfill is a repo script as in principle 3 |
| Editing deployed migrations | Causes drift between environments | Create new migration instead |
| NOT NULL without default | Locks table, rewrites all rows | Add nullable, backfill by batched script, then CHECK (col IS NOT NULL) NOT VALID → VALIDATE CONSTRAINT → SET NOT NULL |
| Inline index on large table | Blocks writes during build | CREATE INDEX CONCURRENTLY |
| Backfill inside a migration | Hard to rollback, long transactions, locks | Separate batched script outside the migration |
| Dropping column before removing code | Application errors on missing column | Remove code first, drop column next deploy |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

