[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FAHF8CDM696C7ECH4V7S05":3,"skill-same:01M7FAHF8CDM696C7ECH4V7S05":49},{"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":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":31,"ownerHtmlUrl":32,"ownerBlogUrl":6,"ownerDescription":33,"updatedAt":34,"install":35,"resources":48},"01M7FAHF8CDM696C7ECH4V7S05","database-migrations",null,"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.","siddu1004\u002FSFP","siddu1004","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F260113491?v=4","01M7F8W1SAJAR49097VRTE1TW5","Siddhardh Vanguri","01M7F8W1SYGY7JE15AHAECCT9R",5,"MIT","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fbackend\u002Fskills\u002Fdatabase-migrations\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: 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:\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","15fa5201935d2b1d172b4e61c2360c908d876d20","plugins\u002Fbackend\u002Fskills\u002Fdatabase-migrations",0,"https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP","https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fsfp-hive","https:\u002F\u002Fgithub.com\u002Fsiddu1004","I am a student at Amrita Vishwa Vidyapeetham pursuing my BTECH degree in Electronics and Electrical Engineering (2024-2028).","2026-11-09 16:04:40",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add siddu1004\u002FSFP --skill database-migrations",{"tool":41,"command":42},"bunx","bunx skills add siddu1004\u002FSFP --skill database-migrations",{"tool":44,"command":45},"pnpm","pnpm dlx skills add siddu1004\u002FSFP --skill database-migrations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fbackend\u002Fskills\u002Fdatabase-migrations\u002FSKILL.md",true,[],[50,57,64,71,78,85],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M7FEEDADZBNBVY19H3XZKCBQ","scientific-schematics","Generates scientific diagram drafts using Nano Banana 2 AI with smart iterative refinement. Uses Gemini 3.7 Flash for quality review. Refines when the review requests improvement, with at most two generations. Specialized in neural network architectures, system diagrams, flowcharts, biological pathways, and complex scientific visualizations.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fscientific-schematics\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M7FEE0JS04FE58MST48D0MMC","polyhaven-texture-apply","Apply realistic PBR textures from PolyHaven to any Blender object. Supports metals, wood, concrete, fabric, and more. Trigger when asked to texture an object, apply a material from PolyHaven, make something look like metal\u002Fwood\u002Fmarble, or change object surface.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-texture-apply\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7FEDJRWV194TY411WVRS84W","polyhaven-studio-setup","Set up a professional product photography studio in Blender using PolyHaven HDRIs and PBR ground materials. Trigger when asked to create a studio setup, add HDRI lighting, set up product photography, or create a showroom scene.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-studio-setup\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7FED5H2FGS50XGETMGSM0RV","polyhaven-scene-builder","Build complete product scenes using PolyHaven assets — HDRI environment, textured ground\u002Fpedestal, and optional props from the 3D model library. Trigger when asked to build a product scene, create a showcase setup, add a pedestal, or compose a product shot.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-scene-builder\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7FECSNZ2CJA7Z8TPE5R844R","polyhaven-material-swap","Cycle through multiple PolyHaven materials on a product and render each variant. Great for showing color\u002Ffinish options. Trigger when asked to show material variants, swap textures, create color options, show finish comparisons, or render product in different materials.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-material-swap\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7FECBPQ6YWH48PYAMS0C5CE","polyhaven-hdri-showcase","Render the same product across multiple HDRI environments and output a comparison grid. Trigger when asked to compare lighting setups, test different environments, show product in multiple settings, or create an HDRI comparison.","https:\u002F\u002Fgithub.com\u002Fsiddu1004\u002FSFP\u002Fblob\u002Fmain\u002Fplugins\u002Fscience-hardware\u002Fskills\u002Fpolyhaven-hdri-showcase\u002FSKILL.md",[],[]]