[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70FSKBPZR0GW6NZVRFCX9AM":3,"skill-same:01M70FSKBPZR0GW6NZVRFCX9AM":81},{"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":31,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":59,"commitSha":60,"skillDirectory":61,"forksCount":62,"repositoryHtmlUrl":63,"repositoryHomepageUrl":6,"ownerHtmlUrl":64,"ownerBlogUrl":6,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M70FSKBPZR0GW6NZVRFCX9AM","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.","mdnaimul22\u002Fhuman-skills","mdnaimul22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F64520358?v=4","01M70FH95MH2H796Q01TYSFZ03","Naimul","01M70FH96798CQR4YHA13F17GA",3,"MIT","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fdatabase-migrations\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"database migrations","migrations","database","ZeRO","django","table","data migration","database migration","patterns","data","safe","kysely","postgresql","prisma","migrate","when","workflows","writing","only","expand","2026-11-10 10:12:30",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":57,"description":7},{"origin":58},"ECC","main","74715deacdc69119d739f38916f8ee4f0f979ebf","skills\u002Fstorage\u002Faffaan-m_ECC\u002Fdatabase-migrations",0,"https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills","https:\u002F\u002Fgithub.com\u002Fmdnaimul22","AI Agents Workflows Automation | Specializing in Python, FastAPI, MCP Agents & Custom ERP.","2026-11-11 21:16:57",{"source":8,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add mdnaimul22\u002Fhuman-skills --skill database-migrations",{"tool":73,"command":74},"bunx","bunx skills add mdnaimul22\u002Fhuman-skills --skill database-migrations",{"tool":76,"command":77},"pnpm","pnpm dlx skills add mdnaimul22\u002Fhuman-skills --skill database-migrations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fdatabase-migrations\u002FSKILL.md",true,[],[82,90,114,136,155,170],{"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":89},"01M72JT3YP1SQHD0MANGDXQ4RT","higgsfield-websites","Build, edit, and deploy full-stack websites, apps and games via the Higgsfield CLI (`higgsfield website …`). Each is a React 19 + TanStack Start SSR app in one Cloudflare Worker (D1\u002FR2\u002FKV\u002FDO\u002FContainers). THREE product types, picked via `--type` on create: `website` (standalone, no Higgsfield integration — references\u002Fwebsite-flow.md), `app` (Sign in with Higgsfield + fnf SDK, Quanta — references\u002Fapp-flow.md), `game` (realtime multiplayer rooms — references\u002Fgame-flow.md). Routes to the right flow; each carries its own rules and deploy\u002Fpublish gates.\nUse when: \"build me a website\", \"make a landing page\", \"create a web app\", \"build a SaaS dashboard \u002F portfolio\", \"make me a game\", \"deploy this site\", \"publish\". Also owns GAME ART: \"make a spritesheet\", \"tileable texture\", \"animate a 3D character\", game music\u002FSFX — see the game-* references.\nNOT for: single image\u002Fvideo\u002Faudio generation (higgsfield-generate), product photos (higgsfield-product-photoshoot), marketplace cards (higgsfield-marketplace-cards).","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fhiggsfield-ai_skills\u002Fhiggsfield-websites\u002FSKILL.md",[],[],"2026-11-10 22:39:42",{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":106,"publishedAt":52},"01M70JPK8HAXXA85P7Q8NKZZYG","writing-skills","Use when creating new skills, editing existing skills, or verifying skills work before deployment","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fwriting-skills\u002FSKILL.md",[96,99,102,103],{"categoryNo":97,"categoryName":98,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":100,"categoryName":101,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000036","内容创作者",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":104,"categoryName":105,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",[49,107,108,109,110,111,112,47,113],"writing skills","editing","deployment","use","Existing","new","work",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":125,"publishedAt":52},"01M70JP4PHBH1CQVVDWZ94W159","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fwriting-plans\u002FSKILL.md",[120,121,122],{"categoryNo":97,"categoryName":98,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":100,"categoryName":101,"taxonomyType":29,"taxonomyTypeDesc":30},{"categoryNo":123,"categoryName":124,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000030","开发工程师",[49,126,127,128,47,129,130,110,131,132,133,134,135],"writing plans","plans","you","code","for","requirements","task","multi","spec","multi-step task",{"skillNo":137,"name":138,"nameZh":6,"description":139,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":140,"categories":141,"keywords":142,"publishedAt":52},"01M70JNTYVGXFZT8PASZ844TH8","verification-before-completion","Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fverification-before-completion\u002FSKILL.md",[],[143,144,145,146,147,148,110,149,150,151,47,152,113,153,154],"verification","verification before completion","complete","about","output","assertions","prs","evidence","claim","claims","commands","running",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":162,"publishedAt":52},"01M70JNGVSQDESWN0Q5BPJ875V","using-superpowers","Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fusing-superpowers\u002FSKILL.md",[161],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[163,164,165,166,110,47,167,168,169],"using superpowers","superpowers","conversation","how to","how","find","questions",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":52},"01M70JN57CE588NPYPYTWH1DWG","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fusing-git-worktrees\u002FSKILL.md",[],[177,178,179,180,181,182,47,113,183,184,185,186,187,188,189,127,110,190,191],"using git worktrees","Using git","git","worktrees","git worktrees","implementation","git worktree","worktree","native","Tools","isolation","fallback","feature","via","workspace"]