[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AWCQJJS6WTK65RFYZW0884":3,"skill-same:01M7AWCQJJS6WTK65RFYZW0884":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M7AWCQJJS6WTK65RFYZW0884","database-migrations",null,"Database migration best practices for schema changes, data migrations, rollbacks, and zero-downtime deployments across PostgreSQL, MySQL, and common ORMs (Prisma, Drizzle, Kysely, Django, TypeORM, golang-migrate).","airclear\u002Fteamai-template-backend","airclear","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4103690?v=4","01M7AWCDWS6J2485AMNDCZBAB3","Airclear","01M7AWCDXY15J0SEMFE051STQS",0,"MIT","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fecc\u002Fdatabase-migrations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: database-migrations\ndescription: Database migration best practices for schema changes, data migrations, rollbacks, and zero-downtime deployments across PostgreSQL, MySQL, and common ORMs (Prisma, Drizzle, Kysely, Django, TypeORM, golang-migrate).\nmetadata:\n  origin: ECC\n---\n\n# Database Migration Patterns\n\nSafe, reversible database schema changes for production systems.\n\n## When to Activate\n\n- Creating or altering database tables\n- Adding\u002Fremoving columns or indexes\n- Running data migrations (backfill, transform)\n- Planning zero-downtime schema changes\n- Setting up migration tooling for a new project\n\n## Core Principles\n\n1. **Every change is a migration** — never alter production databases manually\n2. **Migrations are forward-only in production** — rollbacks use new forward migrations\n3. **Schema and data migrations are separate** — never mix DDL and DML in one migration\n4. **Test migrations against production-sized data** — a migration that works on 100 rows may lock on 10M\n5. **Migrations are immutable once deployed** — never edit a migration that has run in production\n\n## Migration Safety Checklist\n\nBefore applying any migration:\n\n- [ ] Migration has both UP and DOWN (or is explicitly marked irreversible)\n- [ ] No full table locks on large tables (use concurrent operations)\n- [ ] New columns have defaults or are nullable (never add NOT NULL without default)\n- [ ] Indexes created concurrently (not inline with CREATE TABLE for existing tables)\n- [ ] Data backfill is a separate migration from schema change\n- [ ] Tested against a copy of production data\n- [ ] Rollback plan documented\n\n## PostgreSQL Patterns\n\n### Adding a Column Safely\n\n```sql\n-- GOOD: Nullable column, no lock\nALTER TABLE users ADD COLUMN avatar_url TEXT;\n\n-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)\nALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;\n\n-- BAD: NOT NULL without default on existing table (requires full rewrite)\nALTER TABLE users ADD COLUMN role TEXT NOT NULL;\n-- This locks the table and rewrites every row\n```\n\n### Adding an Index Without Downtime\n\n```sql\n-- 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```\n\n### Renaming a Column (Zero-Downtime)\n\nNever rename directly in production. Use the expand-contract pattern:\n\n```sql\n-- Step 1: Add new column (migration 001)\nALTER TABLE users ADD COLUMN display_name TEXT;\n\n-- Step 2: Backfill data (migration 002, data migration)\nUPDATE users SET display_name = username WHERE display_name IS NULL;\n\n-- Step 3: Update application code to read\u002Fwrite both columns\n-- Deploy application changes\n\n-- Step 4: Stop writing to old column, drop it (migration 003)\nALTER TABLE users DROP COLUMN username;\n```\n\n### Removing a Column Safely\n\n```sql\n-- 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```\n\n### Large Data Migrations\n\n```sql\n-- 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```\n\n## Prisma (TypeScript\u002FNode.js)\n\n### Workflow\n\n```bash\n# 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```\n\n### Schema Example\n\n```prisma\nmodel 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```\n\n### Custom SQL Migration\n\nFor operations Prisma cannot express (concurrent indexes, data backfills):\n\n```bash\n# Create empty migration, then edit the SQL manually\nnpx prisma migrate dev --create-only --name add_email_index\n```\n\n```sql\n-- migrations\u002F20240115_add_email_index\u002Fmigration.sql\n-- Prisma cannot generate CONCURRENTLY, so we write it manually\nCREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);\n```\n\n## Drizzle (TypeScript\u002FNode.js)\n\n### Workflow\n\n```bash\n# 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```\n\n### Schema Example\n\n```typescript\nimport { pgTable, text, timestamp, uuid, boolean } from \"drizzle-orm\u002Fpg-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```\n\n## Kysely (TypeScript\u002FNode.js)\n\n### Workflow (kysely-ctl)\n\n```bash\n# 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```\n\n### Migration File\n\n```typescript\n\u002F\u002F migrations\u002F2024_01_15_001_create_user_profile.ts\nimport { type Kysely, sql } from 'kysely'\n\n\u002F\u002F IMPORTANT: Always use Kysely\u003Cany>, not your typed DB interface.\n\u002F\u002F Migrations are frozen in time and must not depend on current schema types.\nexport async function up(db: Kysely\u003Cany>): Promise\u003Cvoid> {\n  await db.schema\n    .createTable('user_profile')\n    .addColumn('id', 'serial', (col) => col.primaryKey())\n    .addColumn('email', 'varchar(255)', (col) => col.notNull().unique())\n    .addColumn('avatar_url', 'text')\n    .addColumn('created_at', 'timestamp', (col) =>\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\u003Cany>): Promise\u003Cvoid> {\n  await db.schema.dropTable('user_profile').execute()\n}\n```\n\n### Programmatic Migrator\n\n```typescript\nimport { Migrator, FileMigrationProvider } from 'kysely'\nimport { promises as fs } from 'fs'\nimport * as path from 'path'\n\u002F\u002F ESM only — CJS can use __dirname directly\nimport { fileURLToPath } from 'url'\nconst migrationFolder = path.join(\n  path.dirname(fileURLToPath(import.meta.url)),\n  '.\u002Fmigrations',\n)\n\n\u002F\u002F `db` is your Kysely\u003Cany> database instance\nconst migrator = new Migrator({\n  db,\n  provider: new FileMigrationProvider({\n    fs,\n    path,\n    migrationFolder,\n  }),\n  \u002F\u002F WARNING: Only enable in development. Disables timestamp-ordering\n  \u002F\u002F validation, which can cause schema drift between environments.\n  \u002F\u002F allowUnorderedMigrations: true,\n})\n\nconst { error, results } = await migrator.migrateToLatest()\n\nresults?.forEach((it) => {\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```\n\n## Django (Python)\n\n### Workflow\n\n```bash\n# 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```\n\n### Data Migration\n\n```python\nfrom 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```\n\n### SeparateDatabaseAndState\n\nRemove a column from the Django model without dropping it from the database immediately:\n\n```python\nclass 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```\n\n## golang-migrate (Go)\n\n### Workflow\n\n```bash\n# 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```\n\n### Migration Files\n\n```sql\n-- migrations\u002F000003_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\u002F000003_add_user_avatar.down.sql\nDROP INDEX IF EXISTS idx_users_avatar;\nALTER TABLE users DROP COLUMN IF EXISTS avatar_url;\n```\n\n## Zero-Downtime Migration Strategy\n\nFor critical production changes, follow the expand-contract pattern:\n\n```\nPhase 1: EXPAND\n  - Add new column\u002Ftable (nullable or with default)\n  - Deploy: app writes to BOTH old and new\n  - Backfill existing data\n\nPhase 2: MIGRATE\n  - Deploy: app reads from NEW, writes to BOTH\n  - Verify data consistency\n\nPhase 3: CONTRACT\n  - Deploy: app only uses NEW\n  - Drop old column\u002Ftable in separate migration\n```\n\n### Timeline Example\n\n```\nDay 1: Migration adds new_status column (nullable)\nDay 1: Deploy app v2 — writes to both status and new_status\nDay 2: Run backfill migration for existing rows\nDay 3: Deploy app v3 — reads from new_status only\nDay 7: Migration drops old status column\n```\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Better Approach |\n|-------------|-------------|-----------------|\n| Manual SQL in production | No audit trail, unrepeatable | Always use migration files |\n| Editing deployed migrations | Causes drift between environments | Create new migration instead |\n| NOT NULL without default | Locks table, rewrites all rows | Add nullable, backfill, then add constraint |\n| Inline index on large table | Blocks writes during build | CREATE INDEX CONCURRENTLY |\n| Schema + data in one migration | Hard to rollback, long transactions | Separate migrations |\n| Dropping column before removing code | Application errors on missing column | Remove code first, drop column next deploy |\n","# Database Migration Patterns\n\nSafe, reversible database schema changes for production systems.\n\n## When to Activate\n\n- Creating or altering database tables\n- Adding\u002Fremoving columns or indexes\n- Running data migrations (backfill, transform)\n- Planning zero-downtime schema changes\n- Setting up migration tooling for a new project\n\n## Core Principles\n\n1. **Every change is a migration** — never alter production databases manually\n2. **Migrations are forward-only in production** — rollbacks use new forward migrations\n3. **Schema and data migrations are separate** — never mix DDL and DML in one migration\n4. **Test migrations against production-sized data** — a migration that works on 100 rows may lock on 10M\n5. **Migrations are immutable once deployed** — never edit a migration that has run in production\n\n## Migration Safety Checklist\n\nBefore applying any migration:\n\n- [ ] Migration has both UP and DOWN (or is explicitly marked irreversible)\n- [ ] No full table locks on large tables (use concurrent operations)\n- [ ] New columns have defaults or are nullable (never add NOT NULL without default)\n- [ ] Indexes created concurrently (not inline with CREATE TABLE for existing tables)\n- [ ] Data backfill is a separate migration from schema change\n- [ ] Tested against a copy of production data\n- [ ] Rollback plan documented\n\n## PostgreSQL Patterns\n\n### Adding a Column Safely\n\n```sql\n-- GOOD: Nullable column, no lock\nALTER TABLE users ADD COLUMN avatar_url TEXT;\n\n-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)\nALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;\n\n-- BAD: NOT NULL without default on existing table (requires full rewrite)\nALTER TABLE users ADD COLUMN role TEXT NOT NULL;\n-- This locks the table and rewrites every row\n```\n\n### Adding an Index Without Downtime\n\n```sql\n-- 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```\n\n### Renaming a Column (Zero-Downtime)\n\nNever rename directly in production. Use the expand-contract pattern:\n\n```sql\n-- Step 1: Add new column (migration 001)\nALTER TABLE users ADD COLUMN display_name TEXT;\n\n-- Step 2: Backfill data (migration 002, data migration)\nUPDATE users SET display_name = username WHERE display_name IS NULL;\n\n-- Step 3: Update application code to read\u002Fwrite both columns\n-- Deploy application changes\n\n-- Step 4: Stop writing to old column, drop it (migration 003)\nALTER TABLE users DROP COLUMN username;\n```\n\n### Removing a Column Safely\n\n```sql\n-- 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```\n\n### Large Data Migrations\n\n```sql\n-- 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```\n\n## Prisma (TypeScript\u002FNode.js)\n\n### Workflow\n\n```bash\n# 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```\n\n### Schema Example\n\n```prisma\nmodel 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```\n\n### Custom SQL Migration\n\nFor operations Prisma cannot express (concurrent indexes, data backfills):\n\n```bash\n# Create empty migration, then edit the SQL manually\nnpx prisma migrate dev --create-only --name add_email_index\n```\n\n```sql\n-- migrations\u002F20240115_add_email_index\u002Fmigration.sql\n-- Prisma cannot generate CONCURRENTLY, so we write it manually\nCREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);\n```\n\n## Drizzle (TypeScript\u002FNode.js)\n\n### Workflow\n\n```bash\n# 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```\n\n### Schema Example\n\n```typescript\nimport { pgTable, text, timestamp, uuid, boolean } from \"drizzle-orm\u002Fpg-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```\n\n## Kysely (TypeScript\u002FNode.js)\n\n### Workflow (kysely-ctl)\n\n```bash\n# 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```\n\n### Migration File\n\n```typescript\n\u002F\u002F migrations\u002F2024_01_15_001_create_user_profile.ts\nimport { type Kysely, sql } from 'kysely'\n\n\u002F\u002F IMPORTANT: Always use Kysely\u003Cany>, not your typed DB interface.\n\u002F\u002F Migrations are frozen in time and must not depend on current schema types.\nexport async function up(db: Kysely\u003Cany>): Promise\u003Cvoid> {\n  await db.schema\n    .createTable('user_profile')\n    .addColumn('id', 'serial', (col) => col.primaryKey())\n    .addColumn('email', 'varchar(255)', (col) => col.notNull().unique())\n    .addColumn('avatar_url', 'text')\n    .addColumn('created_at', 'timestamp', (col) =>\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\u003Cany>): Promise\u003Cvoid> {\n  await db.schema.dropTable('user_profile').execute()\n}\n```\n\n### Programmatic Migrator\n\n```typescript\nimport { Migrator, FileMigrationProvider } from 'kysely'\nimport { promises as fs } from 'fs'\nimport * as path from 'path'\n\u002F\u002F ESM only — CJS can use __dirname directly\nimport { fileURLToPath } from 'url'\nconst migrationFolder = path.join(\n  path.dirname(fileURLToPath(import.meta.url)),\n  '.\u002Fmigrations',\n)\n\n\u002F\u002F `db` is your Kysely\u003Cany> database instance\nconst migrator = new Migrator({\n  db,\n  provider: new FileMigrationProvider({\n    fs,\n    path,\n    migrationFolder,\n  }),\n  \u002F\u002F WARNING: Only enable in development. Disables timestamp-ordering\n  \u002F\u002F validation, which can cause schema drift between environments.\n  \u002F\u002F allowUnorderedMigrations: true,\n})\n\nconst { error, results } = await migrator.migrateToLatest()\n\nresults?.forEach((it) => {\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```\n\n## Django (Python)\n\n### Workflow\n\n```bash\n# 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```\n\n### Data Migration\n\n```python\nfrom 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```\n\n### SeparateDatabaseAndState\n\nRemove a column from the Django model without dropping it from the database immediately:\n\n```python\nclass 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```\n\n## golang-migrate (Go)\n\n### Workflow\n\n```bash\n# 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```\n\n### Migration Files\n\n```sql\n-- migrations\u002F000003_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\u002F000003_add_user_avatar.down.sql\nDROP INDEX IF EXISTS idx_users_avatar;\nALTER TABLE users DROP COLUMN IF EXISTS avatar_url;\n```\n\n## Zero-Downtime Migration Strategy\n\nFor critical production changes, follow the expand-contract pattern:\n\n```\nPhase 1: EXPAND\n  - Add new column\u002Ftable (nullable or with default)\n  - Deploy: app writes to BOTH old and new\n  - Backfill existing data\n\nPhase 2: MIGRATE\n  - Deploy: app reads from NEW, writes to BOTH\n  - Verify data consistency\n\nPhase 3: CONTRACT\n  - Deploy: app only uses NEW\n  - Drop old column\u002Ftable in separate migration\n```\n\n### Timeline Example\n\n```\nDay 1: Migration adds new_status column (nullable)\nDay 1: Deploy app v2 — writes to both status and new_status\nDay 2: Run backfill migration for existing rows\nDay 3: Deploy app v3 — reads from new_status only\nDay 7: Migration drops old status column\n```\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Better Approach |\n|-------------|-------------|-----------------|\n| Manual SQL in production | No audit trail, unrepeatable | Always use migration files |\n| Editing deployed migrations | Causes drift between environments | Create new migration instead |\n| NOT NULL without default | Locks table, rewrites all rows | Add nullable, backfill, then add constraint |\n| Inline index on large table | Blocks writes during build | CREATE INDEX CONCURRENTLY |\n| Schema + data in one migration | Hard to rollback, long transactions | Separate migrations |\n| Dropping column before removing code | Application errors on missing column | Remove code first, drop column next deploy |\n",{"name":5,"metadata":24,"description":7},{"origin":25},"ECC","main","507da53e560c741cb6e607af48bac605209498b6","skills\u002Fecc\u002Fdatabase-migrations","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend","https:\u002F\u002Fgithub.com\u002Fairclear","2026-08-20 15:33:18",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add airclear\u002Fteamai-template-backend --skill database-migrations",{"tool":38,"command":39},"bunx","bunx skills add airclear\u002Fteamai-template-backend --skill database-migrations",{"tool":41,"command":42},"pnpm","pnpm dlx skills add airclear\u002Fteamai-template-backend --skill database-migrations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fecc\u002Fdatabase-migrations\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7AWDNDN2KH5Z8K39TH1WA2J","tdd","Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions \"red-green-refactor\", or wants integration tests.","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fmattpocock\u002Ftdd\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7AWDJJA0HS3TTV4DDAKFWG5","research","Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent.","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fmattpocock\u002Fresearch\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7AWDGE7BTWYQ5MDZBJ3E0P4","grilling","Grill 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.","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fmattpocock\u002Fgrilling\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7AWDE4VNKCJJP8E7XJAN47R","grill-me","A relentless interview to sharpen a plan or design.","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fmattpocock\u002Fgrill-me\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7AWDAKPN814GN86KAG5VYHD","domain-modeling","Build and sharpen a project's domain model. Use when the user wants to pin down domain terminology or a ubiquitous language, record an architectural decision, or when another skill needs to maintain the domain model.","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fmattpocock\u002Fdomain-modeling\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7AWD53VSVWTKC861CPX3E56","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002Fairclear\u002Fteamai-template-backend\u002Fblob\u002Fmain\u002Fskills\u002Fecc\u002Ftdd-workflow\u002FSKILL.md",[],[]]