{"slug":"database-migrations-3","title":"database-migrations","summary":"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, Drizzle, Kysely, Django, and golang-migrate. Use when writing a schema or da","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:03.896367Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: database-migrations\ndescription: \"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, Drizzle, Kysely, Django, and golang-migrate. 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.\"\nmetadata:\norigin: ECC</h2>\n<h1>Database Migration Patterns</h1>\n<p>Safe, reversible database schema changes for production systems.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Creating or altering database tables</li>\n<li>Adding/removing columns or indexes</li>\n<li>Running data migrations (backfill, transform)</li>\n<li>Planning zero-downtime schema changes</li>\n<li>Setting up migration tooling for a new project</li>\n</ul>\n<h2>Core Principles</h2>\n<ol>\n<li><strong>Every change is a migration</strong> — never alter production databases manually</li>\n<li><strong>Migrations are forward-only in production</strong> — rollbacks use new forward migrations</li>\n<li><strong>Schema and data migrations are separate</strong> — never mix DDL and DML in one migration</li>\n<li><strong>Test migrations against production-sized data</strong> — a migration that works on 100 rows may lock on 10M</li>\n<li><strong>Migrations are immutable once deployed</strong> — never edit a migration that has run in production</li>\n</ol>\n<h2>Migration Safety Checklist</h2>\n<p>Before applying any migration:</p>\n<ul>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Migration has both UP and DOWN (or is explicitly marked irreversible)</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Lock modes and expected hold times reviewed; use concurrent operations where supported</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> On populated tables, new columns are nullable or have defaults compatible with their constraints</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Indexes created concurrently (not inline with CREATE TABLE for existing tables)</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Data backfill is a separate migration from schema change</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Tested against a copy of production data</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Rollback plan documented</li>\n</ul>\n<h2>PostgreSQL Patterns</h2>\n<h3>Adding a Column Safely</h3>\n<pre><code>-- Nullable column: no table rewrite, but takes ACCESS EXCLUSIVE lock\nALTER TABLE users ADD COLUMN avatar_url TEXT;\n\n-- PostgreSQL 11+: a non-volatile default avoids a table rewrite\n-- Still takes ACCESS EXCLUSIVE lock and may wait for other transactions\nALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;\n\n-- BAD on a populated table: existing rows would have NULL in the new column\nALTER TABLE users ADD COLUMN role TEXT NOT NULL;\n-- Fails with not_null_violation (SQLSTATE 23502); does not backfill existing rows\n</code></pre>\n<p>Avoiding a table rewrite does not mean avoiding locks. These <code>ADD COLUMN</code>\noperations take an <code>ACCESS EXCLUSIVE</code> lock, held until the transaction ends.\nKeep the transaction short and use an appropriate <code>lock_timeout</code> to bound lock\nacquisition waits. A volatile default such as <code>clock_timestamp()</code> requires a\ntable rewrite; the PostgreSQL 11+ fast path applies to non-volatile defaults.\nAdding a <code>NOT NULL</code> column without a default can succeed on an empty table.</p>\n<p>Run the self-checking <a href=\"examples/postgres-add-column.sql\">reproduction SQL</a> on\nPostgreSQL 11+:</p>\n<pre><code>psql -X -v ON_ERROR_STOP=1 -f examples/postgres-add-column.sql\n</code></pre>\n<p>It uses a temporary table, rolls back the ALTERs, and drops the fixture, checking\nlock acquisition, rewrites, and the expected constraint violation.</p>\n<p>Reference: <a href=\"https://www.postgresql.org/docs/current/sql-altertable.html\">PostgreSQL ALTER TABLE</a>.</p>\n<h3>Adding an Index Without Downtime</h3>\n<pre><code>-- BAD: Blocks writes on large tables\nCREATE INDEX idx_users_email ON users (email);\n\n-- GOOD: Non-blocking, allows concurrent writes\nCREATE INDEX CONCURRENTLY idx_users_email ON users (email);\n\n-- Note: CONCURRENTLY cannot run inside a transaction block\n-- Most migration tools need special handling for this\n</code></pre>\n<h3>Renaming a Column (Zero-Downtime)</h3>\n<p>For a pure rename (both columns represent the same value), use expand-contract.\nKeep <code>username</code> authoritative until the read cutover:</p>\n<pre><code>-- Step 1: Expand (migration 001)\nALTER TABLE users ADD COLUMN display_name TEXT;\n\n-- Step 2: Deploy app v2: read username, write BOTH columns atomically.\n-- Cover every INSERT/UPDATE path, including jobs, imports, and admin tools.\n-- Drain old-only writers and their in-flight transactions before backfilling.\n\n-- Step 3: Backfill in bounded primary-key ranges (separate data migration).\n-- Example range; advance bounds to cover every existing id.\nBEGIN;\nSET TRANSACTION ISOLATION LEVEL READ COMMITTED;\nSET LOCAL lock_timeout = '2s';\nUPDATE users SET display_name = username\nWHERE id &gt; 0 AND id &lt;= 10000\n  AND display_name IS DISTINCT FROM username;\nCOMMIT;\n\n-- Step 4: Validate AFTER all ranges complete, while dual writes continue.\n-- Require zero mismatches before switching reads.\nSELECT count(*) AS mismatched_rows FROM users\nWHERE display_name IS DISTINCT FROM username;\n\n-- Step 5: Deploy app v3: read display_name, still write BOTH columns.\n-- Keep dual writes throughout the rollback window.\n\n-- Step 6: After the rollback window, stop backfill/reconciliation workers.\n-- Transfer required constraints/indexes/dependencies to the new column.\n-- Make old-column constraints compatible with new-only INSERTs/UPDATEs.\n-- Drain non-app readers of username and their in-flight transactions first.\n-- Then deploy app v4 using ONLY display_name; drain remaining old-column users.\n\n-- Step 7: Contract in a separate migration after checking dependencies.\nALTER TABLE users DROP COLUMN username;\n</code></pre>\n<p>Commit each range independently; checkpoint only after commit and retry failed\nbatch transactions. Choose bounds for the actual key space (including zero or\nnegative IDs if present). <code>IS DISTINCT FROM</code> repairs stale non-NULL values and\nhandles NULL pairs without repeatedly updating them. Do not fetch <code>username</code>\ninto application memory and later write that stale snapshot: copy the target\nrow's current value in the same <code>UPDATE</code>. At Read Committed, concurrent updates\nserialize on the row and PostgreSQL rechecks the predicate after waiting.</p>\n<p>Deploying dual writes does not repair earlier drift by itself. Finish draining\nold-only writers before backfill, and validate parity before read cutover. Once\nnew-only writes start, the old column may be stale: do not restart this backfill\nor roll back to old readers without a reconciliation plan. The timeline below\nrepresents deployment gates, not guaranteed elapsed time or lock-free DDL.</p>\n<p>The <a href=\"examples/postgres-column-rename.sql\">self-checking SQL example</a> reproduces\nthe stale-value failure and verifies reconciliation, retries, and NULL handling:</p>\n<pre><code>psql -X -v ON_ERROR_STOP=1 -f examples/postgres-column-rename.sql\n</code></pre>\n<p>Reference: <a href=\"https://www.postgresql.org/docs/current/transaction-iso.html#XACT-READ-COMMITTED\">PostgreSQL Read Committed behavior</a>.</p>\n<h3>Removing a Column Safely</h3>\n<pre><code>-- Step 1: Remove all application references to the column\n-- Step 2: Deploy application without the column reference\n-- Step 3: Drop column in next migration\nALTER TABLE orders DROP COLUMN legacy_status;\n\n-- For Django: use SeparateDatabaseAndState to remove from model\n-- without generating DROP COLUMN (then drop in next migration)\n</code></pre>\n<h3>Large Data Migrations</h3>\n<pre><code>-- BAD: Updates all rows in one transaction (locks table)\nUPDATE users SET normalized_email = LOWER(email);\n\n-- GOOD: Batch update with progress\nDO $$\nDECLARE\n  batch_size INT := 10000;\n  rows_updated INT;\nBEGIN\n  LOOP\n    UPDATE users\n    SET normalized_email = LOWER(email)\n    WHERE id IN (\n      SELECT id FROM users\n      WHERE normalized_email IS NULL\n      LIMIT batch_size\n      FOR UPDATE SKIP LOCKED\n    );\n    GET DIAGNOSTICS rows_updated = ROW_COUNT;\n    RAISE NOTICE 'Updated % rows', rows_updated;\n    EXIT WHEN rows_updated = 0;\n    COMMIT;\n  END LOOP;\nEND $$;\n</code></pre>\n<h2>Prisma (TypeScript/Node.js)</h2>\n<h3>Workflow</h3>\n<pre><code># Create migration from schema changes\nnpx prisma migrate dev --name add_user_avatar\n\n# Apply pending migrations in production\nnpx prisma migrate deploy\n\n# Reset database (dev only)\nnpx prisma migrate reset\n\n# Generate client after schema changes\nnpx prisma generate\n</code></pre>\n<h3>Schema Example</h3>\n<pre><code>model User {\n  id        String   @id @default(cuid())\n  email     String   @unique\n  name      String?\n  avatarUrl String?  @map(\"avatar_url\")\n  createdAt DateTime @default(now()) @map(\"created_at\")\n  updatedAt DateTime @updatedAt @map(\"updated_at\")\n  orders    Order[]\n\n  @@map(\"users\")\n  @@index([email])\n}\n</code></pre>\n<h3>Custom SQL Migration</h3>\n<p>For operations Prisma cannot express (concurrent indexes, data backfills):</p>\n<pre><code># Create empty migration, then edit the SQL manually\nnpx prisma migrate dev --create-only --name add_email_index\n</code></pre>\n<pre><code>-- migrations/20240115_add_email_index/migration.sql\n-- Prisma cannot generate CONCURRENTLY, so we write it manually\nCREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);\n</code></pre>\n<h2>Drizzle (TypeScript/Node.js)</h2>\n<h3>Workflow</h3>\n<pre><code># Generate migration from schema changes\nnpx drizzle-kit generate\n\n# Apply migrations\nnpx drizzle-kit migrate\n\n# Push schema directly (dev only, no migration file)\nnpx drizzle-kit push\n</code></pre>\n<h3>Schema Example</h3>\n<pre><code>import { pgTable, text, timestamp, uuid, boolean } from \"drizzle-orm/pg-core\";\n\nexport const users = pgTable(\"users\", {\n  id: uuid(\"id\").primaryKey().defaultRandom(),\n  email: text(\"email\").notNull().unique(),\n  name: text(\"name\"),\n  isActive: boolean(\"is_active\").notNull().default(true),\n  createdAt: timestamp(\"created_at\").notNull().defaultNow(),\n  updatedAt: timestamp(\"updated_at\").notNull().defaultNow(),\n});\n</code></pre>\n<h2>Kysely (TypeScript/Node.js)</h2>\n<h3>Workflow (kysely-ctl)</h3>\n<pre><code># Initialize config file (kysely.config.ts)\nkysely init\n\n# Create a new migration file\nkysely migrate make add_user_avatar\n\n# Apply all pending migrations\nkysely migrate latest\n\n# Rollback last migration\nkysely migrate down\n\n# Show migration status\nkysely migrate list\n</code></pre>\n<h3>Migration File</h3>\n<pre><code>// migrations/2024_01_15_001_create_user_profile.ts\nimport { type Kysely, sql } from 'kysely'\n\n// IMPORTANT: Always use Kysely&lt;any&gt;, not your typed DB interface.\n// Migrations are frozen in time and must not depend on current schema types.\nexport async function up(db: Kysely&lt;any&gt;): Promise&lt;void&gt; {\n  await db.schema\n    .createTable('user_profile')\n    .addColumn('id', 'serial', (col) =&gt; col.primaryKey())\n    .addColumn('email', 'varchar(255)', (col) =&gt; col.notNull().unique())\n    .addColumn('avatar_url', 'text')\n    .addColumn('created_at', 'timestamp', (col) =&gt;\n      col.defaultTo(sql`now()`).notNull()\n    )\n    .execute()\n\n  await db.schema\n    .createIndex('idx_user_profile_avatar')\n    .on('user_profile')\n    .column('avatar_url')\n    .execute()\n}\n\nexport async function down(db: Kysely&lt;any&gt;): Promise&lt;void&gt; {\n  await db.schema.dropTable('user_profile').execute()\n}\n</code></pre>\n<h3>Programmatic Migrator</h3>\n<pre><code>import { Migrator, FileMigrationProvider } from 'kysely'\nimport { promises as fs } from 'fs'\nimport * as path from 'path'\n// ESM only — CJS can use __dirname directly\nimport { fileURLToPath } from 'url'\nconst migrationFolder = path.join(\n  path.dirname(fileURLToPath(import.meta.url)),\n  './migrations',\n)\n\n// `db` is your Kysely&lt;any&gt; database instance\nconst migrator = new Migrator({\n  db,\n  provider: new FileMigrationProvider({\n    fs,\n    path,\n    migrationFolder,\n  }),\n  // WARNING: Only enable in development. Disables timestamp-ordering\n  // validation, which can cause schema drift between environments.\n  // allowUnorderedMigrations: true,\n})\n\nconst { error, results } = await migrator.migrateToLatest()\n\nresults?.forEach((it) =&gt; {\n  if (it.status === 'Success') {\n    console.log(`migration \"${it.migrationName}\" executed successfully`)\n  } else if (it.status === 'Error') {\n    console.error(`failed to execute migration \"${it.migrationName}\"`)\n  }\n})\n\nif (error) {\n  console.error('migration failed', error)\n  process.exit(1)\n}\n</code></pre>\n<h2>Django (Python)</h2>\n<h3>Workflow</h3>\n<pre><code># Generate migration from model changes\npython manage.py makemigrations\n\n# Apply migrations\npython manage.py migrate\n\n# Show migration status\npython manage.py showmigrations\n\n# Generate empty migration for custom SQL\npython manage.py makemigrations --empty app_name -n description\n</code></pre>\n<h3>Data Migration</h3>\n<pre><code>from django.db import migrations\n\ndef backfill_display_names(apps, schema_editor):\n    User = apps.get_model(\"accounts\", \"User\")\n    batch_size = 5000\n    users = User.objects.filter(display_name=\"\")\n    while users.exists():\n        batch = list(users[:batch_size])\n        for user in batch:\n            user.display_name = user.username\n        User.objects.bulk_update(batch, [\"display_name\"], batch_size=batch_size)\n\ndef reverse_backfill(apps, schema_editor):\n    pass  # Data migration, no reverse needed\n\nclass Migration(migrations.Migration):\n    dependencies = [(\"accounts\", \"0015_add_display_name\")]\n\n    operations = [\n        migrations.RunPython(backfill_display_names, reverse_backfill),\n    ]\n</code></pre>\n<h3>SeparateDatabaseAndState</h3>\n<p>Remove a column from the Django model without dropping it from the database immediately:</p>\n<pre><code>class Migration(migrations.Migration):\n    operations = [\n        migrations.SeparateDatabaseAndState(\n            state_operations=[\n                migrations.RemoveField(model_name=\"user\", name=\"legacy_field\"),\n            ],\n            database_operations=[],  # Don't touch the DB yet\n        ),\n    ]\n</code></pre>\n<h2>golang-migrate (Go)</h2>\n<h3>Workflow</h3>\n<pre><code># Create migration pair\nmigrate create -ext sql -dir migrations -seq add_user_avatar\n\n# Apply all pending migrations\nmigrate -path migrations -database \"$DATABASE_URL\" up\n\n# Rollback last migration\nmigrate -path migrations -database \"$DATABASE_URL\" down 1\n\n# Force version (fix dirty state)\nmigrate -path migrations -database \"$DATABASE_URL\" force VERSION\n</code></pre>\n<h3>Migration Files</h3>\n<pre><code>-- migrations/000003_add_user_avatar.up.sql\nALTER TABLE users ADD COLUMN avatar_url TEXT;\nCREATE INDEX CONCURRENTLY idx_users_avatar ON users (avatar_url) WHERE avatar_url IS NOT NULL;\n\n-- migrations/000003_add_user_avatar.down.sql\nDROP INDEX IF EXISTS idx_users_avatar;\nALTER TABLE users DROP COLUMN IF EXISTS avatar_url;\n</code></pre>\n<h2>Zero-Downtime Migration Strategy</h2>\n<p>For critical production changes, follow the expand-contract pattern:</p>\n<pre><code>Phase 1: EXPAND\n  - Add new column/table (nullable or with default)\n  - Deploy: app reads OLD, writes BOTH atomically\n  - Drain old-only writers and in-flight transactions\n  - Backfill in committed batches, then verify parity\n\nPhase 2: MIGRATE\n  - Deploy: app reads from NEW, writes to BOTH\n  - Monitor parity and retain dual writes throughout the rollback window\n\nPhase 3: CONTRACT\n  - End rollback window; stop backfill and migrate constraints/dependencies\n  - Drain non-app old-column readers and their in-flight transactions\n  - Deploy: app only uses NEW; drain remaining old-column users\n  - Drop old column/table in separate migration\n</code></pre>\n<h3>Timeline Example</h3>\n<pre><code>Day 1: Migration adds new_status column (nullable)\nDay 1: Deploy app v2 — reads status, writes both columns atomically\nDay 2: Drain old-only writers; backfill in batches; require zero mismatches\nDay 3: Deploy app v3 — reads new_status, still writes both columns\nDay 7: End rollback window; stop backfill; migrate constraints/dependencies\nDay 7: Drain non-app old-column readers and their in-flight transactions\nDay 7: Deploy app v4 — only uses new_status; drain remaining old-column users\nLater: Separate migration drops status after all contract gates pass\n</code></pre>\n<h2>Anti-Patterns</h2>\n<table>\n<thead>\n<tr>\n<th>Anti-Pattern</th>\n<th>Why It Fails</th>\n<th>Better Approach</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Manual SQL in production</td>\n<td>No audit trail, unrepeatable</td>\n<td>Always use migration files</td>\n</tr>\n<tr>\n<td>Editing deployed migrations</td>\n<td>Causes drift between environments</td>\n<td>Create new migration instead</td>\n</tr>\n<tr>\n<td>Adding NOT NULL column without default to populated table</td>\n<td>Fails because existing rows would contain NULL</td>\n<td>Add nullable, backfill, then set NOT NULL</td>\n</tr>\n<tr>\n<td>Inline index on large table</td>\n<td>Blocks writes during build</td>\n<td>CREATE INDEX CONCURRENTLY</td>\n</tr>\n<tr>\n<td>Schema + data in one migration</td>\n<td>Hard to rollback, long transactions</td>\n<td>Separate migrations</td>\n</tr>\n<tr>\n<td>Dropping column before removing code</td>\n<td>Application errors on missing column</td>\n<td>Remove code first, drop column next deploy</td>\n</tr>\n</tbody>\n</table>\n","files":[{"path":"examples/postgres-add-column.sql","sizeBytes":2186,"isText":false},{"path":"examples/postgres-column-rename.sql","sizeBytes":3191,"isText":false},{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":16232,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:53:28.004186Z","sha256":"67F222E1E9C8E988A800FCCE512308A4CD5A8758B81D5C6DAF967C538E51341E","sizeBytes":9144},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/database-migrations","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"4BE260A85B84149EBEC009A7D6E5D55B2C634A141C28714DEA933747658B9BC0","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T16:53:55.524439Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/database-migrations"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}