[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D8CYCTCD1BXK9Z35BD3AMM":3,"skill-same:01M7D8CYCTCD1BXK9Z35BD3AMM":83},{"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":61,"commitSha":62,"skillDirectory":63,"forksCount":14,"repositoryHtmlUrl":64,"repositoryHomepageUrl":6,"ownerHtmlUrl":65,"ownerBlogUrl":66,"ownerDescription":67,"updatedAt":68,"install":69,"resources":82},"01M7D8CYCTCD1BXK9Z35BD3AMM","Database Migration Test Generator",null,"Generate tests for database migration safety covering schema changes, data integrity preservation, rollback verification, and zero-downtime migration validation","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fdatabase-migration-test-generator\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: Database Migration Test Generator\ndescription: Generate tests for database migration safety covering schema changes, data integrity preservation, rollback verification, and zero-downtime migration validation\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [database-migration, schema-testing, data-integrity, rollback-testing, zero-downtime, migration-safety, database-versioning]\ntestingTypes: [database, integration]\nframeworks: [jest, vitest, pytest]\nlanguages: [typescript, javascript, python, java]\ndomains: [api]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# Database Migration Test Generator Skill\n\nYou are an expert QA engineer specializing in database migration testing and data integrity verification. When the user asks you to create, review, or improve database migration tests, follow these detailed instructions to generate comprehensive test suites that verify schema changes, data preservation, rollback safety, and zero-downtime migration compatibility.\n\n## Core Principles\n\n1. **Migrations are code, test them as code** -- Every migration file is a deployable artifact that modifies production state. It deserves the same testing rigor as application code. Untested migrations are production time bombs.\n2. **Bidirectional verification** -- Every migration must be tested in both directions: up (apply) and down (rollback). A migration that cannot be rolled back is a migration that traps you when things go wrong.\n3. **Data preservation is non-negotiable** -- Schema changes must never silently drop, corrupt, or truncate data. Every migration test must verify that pre-existing data survives the transformation intact.\n4. **Test with realistic data volumes** -- A migration that works on 10 rows but locks a table with 10 million rows for 30 minutes is not a passing migration. Volume testing is mandatory for production-bound migrations.\n5. **Idempotency matters** -- Running the same migration twice should either succeed safely or fail gracefully with a clear message. Never assume migrations run exactly once.\n6. **Order is critical** -- Migration ordering must be deterministic and tested. Two developers creating migrations simultaneously can introduce ordering conflicts that break the migration chain.\n7. **Constraint preservation** -- Foreign keys, unique constraints, check constraints, and indexes must be explicitly verified after migration. Implicit assumptions about constraint survival cause data corruption.\n8. **Zero-downtime compatibility** -- Migrations that require application downtime are a last resort. Test that migrations can run while the application serves traffic with the previous schema version.\n9. **Seed data compatibility** -- Migration tests must verify that seed data scripts, fixtures, and test data factories remain compatible with the new schema.\n10. **Atomic migration units** -- Each migration should do one logical thing. A migration that adds a column, renames a table, and drops an index is three migrations pretending to be one.\n\n## Project Structure\n\n```\ntests\u002F\n  migrations\u002F\n    helpers\u002F\n      migration-runner.ts\n      test-database.ts\n      data-seeder.ts\n      snapshot-comparator.ts\n    schema\u002F\n      schema-change.test.ts\n      column-addition.test.ts\n      column-removal.test.ts\n      table-rename.test.ts\n      type-change.test.ts\n    integrity\u002F\n      data-preservation.test.ts\n      constraint-verification.test.ts\n      index-verification.test.ts\n      foreign-key.test.ts\n    rollback\u002F\n      rollback-safety.test.ts\n      rollback-data-preservation.test.ts\n      partial-rollback.test.ts\n    zero-downtime\u002F\n      backward-compatible.test.ts\n      dual-write.test.ts\n      online-migration.test.ts\n    ordering\u002F\n      migration-sequence.test.ts\n      concurrent-migration.test.ts\n    performance\u002F\n      large-table-migration.test.ts\n      index-creation.test.ts\n    config\u002F\n      migration-test.config.ts\n  fixtures\u002F\n    seed-data\u002F\n      pre-migration.sql\n      post-migration-expected.sql\n```\n\n## Test Database Setup\n\nBefore testing migrations, you need an isolated database environment that can be created and destroyed rapidly.\n\n### TypeScript with Drizzle ORM\n\n```typescript\n\u002F\u002F test-database.ts\nimport { drizzle } from 'drizzle-orm\u002Fnode-postgres';\nimport { migrate } from 'drizzle-orm\u002Fnode-postgres\u002Fmigrator';\nimport { Pool } from 'pg';\nimport { execSync } from 'child_process';\n\ninterface TestDatabase {\n  pool: Pool;\n  db: ReturnType\u003Ctypeof drizzle>;\n  name: string;\n  connectionString: string;\n  teardown: () => Promise\u003Cvoid>;\n}\n\nasync function createTestDatabase(prefix: string = 'migration_test'): Promise\u003CTestDatabase> {\n  const dbName = `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n  const adminPool = new Pool({\n    connectionString: process.env.TEST_DATABASE_ADMIN_URL,\n  });\n\n  await adminPool.query(`CREATE DATABASE \"${dbName}\"`);\n  await adminPool.end();\n\n  const connectionString = `${process.env.TEST_DATABASE_BASE_URL}\u002F${dbName}`;\n  const pool = new Pool({ connectionString });\n  const db = drizzle(pool);\n\n  return {\n    pool,\n    db,\n    name: dbName,\n    connectionString,\n    teardown: async () => {\n      await pool.end();\n      const cleanup = new Pool({\n        connectionString: process.env.TEST_DATABASE_ADMIN_URL,\n      });\n      await cleanup.query(`DROP DATABASE IF EXISTS \"${dbName}\" WITH (FORCE)`);\n      await cleanup.end();\n    },\n  };\n}\n\nasync function applyMigrationsUpTo(\n  db: ReturnType\u003Ctypeof drizzle>,\n  migrationsFolder: string,\n  upToVersion?: string\n): Promise\u003Cvoid> {\n  if (upToVersion) {\n    \u002F\u002F Apply migrations sequentially up to the specified version\n    const fs = await import('fs');\n    const path = await import('path');\n    const files = fs.readdirSync(migrationsFolder)\n      .filter(f => f.endsWith('.sql'))\n      .sort()\n      .filter(f => f \u003C= upToVersion);\n\n    for (const file of files) {\n      const sql = fs.readFileSync(path.join(migrationsFolder, file), 'utf-8');\n      await db.execute(sql);\n    }\n  } else {\n    await migrate(db, { migrationsFolder });\n  }\n}\n```\n\n### Migration Runner\n\n```typescript\n\u002F\u002F migration-runner.ts\nimport { readFileSync, readdirSync } from 'fs';\nimport { join } from 'path';\n\ninterface MigrationFile {\n  version: string;\n  name: string;\n  upSql: string;\n  downSql: string;\n  filePath: string;\n}\n\ninterface MigrationResult {\n  version: string;\n  direction: 'up' | 'down';\n  success: boolean;\n  duration: number;\n  error?: string;\n  rowsAffected?: number;\n}\n\nclass MigrationRunner {\n  private migrationsDir: string;\n  private migrations: MigrationFile[] = [];\n\n  constructor(migrationsDir: string) {\n    this.migrationsDir = migrationsDir;\n    this.loadMigrations();\n  }\n\n  private loadMigrations(): void {\n    const files = readdirSync(this.migrationsDir)\n      .filter(f => f.endsWith('.sql'))\n      .sort();\n\n    this.migrations = files.map(file => {\n      const content = readFileSync(join(this.migrationsDir, file), 'utf-8');\n      const [upSql, downSql] = this.splitMigration(content);\n      return {\n        version: file.replace('.sql', ''),\n        name: file,\n        upSql,\n        downSql,\n        filePath: join(this.migrationsDir, file),\n      };\n    });\n  }\n\n  private splitMigration(content: string): [string, string] {\n    const downMarker = '-- migrate:down';\n    const parts = content.split(downMarker);\n    return [\n      parts[0].replace('-- migrate:up', '').trim(),\n      parts.length > 1 ? parts[1].trim() : '',\n    ];\n  }\n\n  async runUp(pool: Pool, version: string): Promise\u003CMigrationResult> {\n    const migration = this.getMigration(version);\n    const start = Date.now();\n    try {\n      const result = await pool.query(migration.upSql);\n      return {\n        version, direction: 'up', success: true,\n        duration: Date.now() - start,\n        rowsAffected: result.rowCount ?? 0,\n      };\n    } catch (error) {\n      return {\n        version, direction: 'up', success: false,\n        duration: Date.now() - start,\n        error: (error as Error).message,\n      };\n    }\n  }\n\n  async runDown(pool: Pool, version: string): Promise\u003CMigrationResult> {\n    const migration = this.getMigration(version);\n    if (!migration.downSql) {\n      return {\n        version, direction: 'down', success: false,\n        duration: 0, error: 'No down migration defined',\n      };\n    }\n    const start = Date.now();\n    try {\n      const result = await pool.query(migration.downSql);\n      return {\n        version, direction: 'down', success: true,\n        duration: Date.now() - start,\n        rowsAffected: result.rowCount ?? 0,\n      };\n    } catch (error) {\n      return {\n        version, direction: 'down', success: false,\n        duration: Date.now() - start,\n        error: (error as Error).message,\n      };\n    }\n  }\n\n  getMigration(version: string): MigrationFile {\n    const migration = this.migrations.find(m => m.version === version);\n    if (!migration) throw new Error(`Migration ${version} not found`);\n    return migration;\n  }\n\n  getAllVersions(): string[] {\n    return this.migrations.map(m => m.version);\n  }\n}\n```\n\n## Schema Change Testing\n\n### Column Addition and Removal\n\n```typescript\n\u002F\u002F schema-change.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\n\ndescribe('Schema Change Migrations', () => {\n  let testDb: TestDatabase;\n  let runner: MigrationRunner;\n\n  beforeAll(async () => {\n    testDb = await createTestDatabase('schema_test');\n    runner = new MigrationRunner('.\u002Fdrizzle\u002Fmigrations');\n  });\n\n  afterAll(async () => {\n    await testDb.teardown();\n  });\n\n  describe('Column Addition: add email_verified to users', () => {\n    it('should add the column with correct type and default', async () => {\n      \u002F\u002F Apply migrations up to the one before our target\n      await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0004_previous');\n\n      \u002F\u002F Seed test data before migration\n      await testDb.pool.query(`\n        INSERT INTO users (id, email, name) VALUES\n        ('u1', 'alice@example.com', 'Alice'),\n        ('u2', 'bob@example.com', 'Bob')\n      `);\n\n      \u002F\u002F Run the migration under test\n      const result = await runner.runUp(testDb.pool, '0005_add_email_verified');\n      expect(result.success).toBe(true);\n\n      \u002F\u002F Verify column exists with correct type\n      const columnInfo = await testDb.pool.query(`\n        SELECT column_name, data_type, column_default, is_nullable\n        FROM information_schema.columns\n        WHERE table_name = 'users' AND column_name = 'email_verified'\n      `);\n      expect(columnInfo.rows).toHaveLength(1);\n      expect(columnInfo.rows[0].data_type).toBe('boolean');\n      expect(columnInfo.rows[0].column_default).toBe('false');\n      expect(columnInfo.rows[0].is_nullable).toBe('NO');\n    });\n\n    it('should preserve existing data after column addition', async () => {\n      const users = await testDb.pool.query(\n        'SELECT id, email, name, email_verified FROM users ORDER BY id'\n      );\n      expect(users.rows).toHaveLength(2);\n      expect(users.rows[0]).toMatchObject({ id: 'u1', email: 'alice@example.com', email_verified: false });\n      expect(users.rows[1]).toMatchObject({ id: 'u2', email: 'bob@example.com', email_verified: false });\n    });\n\n    it('should allow rollback without data loss', async () => {\n      const result = await runner.runDown(testDb.pool, '0005_add_email_verified');\n      expect(result.success).toBe(true);\n\n      \u002F\u002F Verify column is gone\n      const columnInfo = await testDb.pool.query(`\n        SELECT column_name FROM information_schema.columns\n        WHERE table_name = 'users' AND column_name = 'email_verified'\n      `);\n      expect(columnInfo.rows).toHaveLength(0);\n\n      \u002F\u002F Verify original data still intact\n      const users = await testDb.pool.query('SELECT id, email, name FROM users ORDER BY id');\n      expect(users.rows).toHaveLength(2);\n      expect(users.rows[0].email).toBe('alice@example.com');\n    });\n  });\n\n  describe('Column Type Change: string to enum', () => {\n    it('should convert existing values to enum without data loss', async () => {\n      await testDb.pool.query(`\n        INSERT INTO orders (id, status) VALUES\n        ('o1', 'pending'), ('o2', 'shipped'), ('o3', 'delivered')\n      `);\n\n      const result = await runner.runUp(testDb.pool, '0006_status_to_enum');\n      expect(result.success).toBe(true);\n\n      const orders = await testDb.pool.query('SELECT id, status FROM orders ORDER BY id');\n      expect(orders.rows[0].status).toBe('pending');\n      expect(orders.rows[1].status).toBe('shipped');\n      expect(orders.rows[2].status).toBe('delivered');\n    });\n\n    it('should reject invalid enum values after migration', async () => {\n      await expect(\n        testDb.pool.query(`INSERT INTO orders (id, status) VALUES ('o4', 'invalid_status')`)\n      ).rejects.toThrow();\n    });\n  });\n});\n```\n\n## Data Integrity Verification\n\n```typescript\n\u002F\u002F data-preservation.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\nimport { createHash } from 'crypto';\n\ndescribe('Data Integrity During Migration', () => {\n  let testDb: TestDatabase;\n\n  beforeAll(async () => {\n    testDb = await createTestDatabase('integrity_test');\n  });\n\n  afterAll(async () => {\n    await testDb.teardown();\n  });\n\n  it('should preserve row count across migration', async () => {\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0004_previous');\n\n    \u002F\u002F Seed substantial data\n    const insertValues = Array.from({ length: 1000 }, (_, i) =>\n      `('user_${i}', 'user${i}@example.com', 'User ${i}')`\n    ).join(',\\n');\n    await testDb.pool.query(`INSERT INTO users (id, email, name) VALUES ${insertValues}`);\n\n    const beforeCount = await testDb.pool.query('SELECT COUNT(*) as count FROM users');\n    expect(Number(beforeCount.rows[0].count)).toBe(1000);\n\n    \u002F\u002F Run migration\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0005_add_email_verified');\n\n    const afterCount = await testDb.pool.query('SELECT COUNT(*) as count FROM users');\n    expect(Number(afterCount.rows[0].count)).toBe(1000);\n  });\n\n  it('should preserve data checksums across migration', async () => {\n    \u002F\u002F Capture checksums before migration\n    const beforeData = await testDb.pool.query(\n      'SELECT id, email, name FROM users ORDER BY id'\n    );\n    const beforeChecksum = createHash('sha256')\n      .update(JSON.stringify(beforeData.rows))\n      .digest('hex');\n\n    \u002F\u002F Run migration that adds a column\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0006_add_profile_url');\n\n    \u002F\u002F Capture same columns after migration (excluding new column)\n    const afterData = await testDb.pool.query(\n      'SELECT id, email, name FROM users ORDER BY id'\n    );\n    const afterChecksum = createHash('sha256')\n      .update(JSON.stringify(afterData.rows))\n      .digest('hex');\n\n    expect(afterChecksum).toBe(beforeChecksum);\n  });\n\n  it('should preserve unicode data during encoding-sensitive migrations', async () => {\n    await testDb.pool.query(`\n      INSERT INTO products (id, name, description) VALUES\n      ('p1', 'Cafe Latte', 'Smooth espresso with steamed milk'),\n      ('p2', 'Matcha', 'Japanese green tea powder'),\n      ('p3', 'Acai Bowl', 'Brazilian superfood bowl')\n    `);\n\n    await runner.runUp(testDb.pool, '0007_change_text_encoding');\n\n    const products = await testDb.pool.query('SELECT name, description FROM products ORDER BY id');\n    expect(products.rows[0].name).toBe('Cafe Latte');\n    expect(products.rows[1].name).toBe('Matcha');\n    expect(products.rows[2].name).toBe('Acai Bowl');\n  });\n});\n```\n\n## Foreign Key and Constraint Preservation\n\n```typescript\n\u002F\u002F constraint-verification.test.ts\ndescribe('Constraint Preservation', () => {\n  it('should preserve foreign key constraints after migration', async () => {\n    const constraints = await testDb.pool.query(`\n      SELECT\n        tc.constraint_name,\n        tc.constraint_type,\n        kcu.column_name,\n        ccu.table_name AS foreign_table_name,\n        ccu.column_name AS foreign_column_name\n      FROM information_schema.table_constraints tc\n      JOIN information_schema.key_column_usage kcu\n        ON tc.constraint_name = kcu.constraint_name\n      LEFT JOIN information_schema.constraint_column_usage ccu\n        ON tc.constraint_name = ccu.constraint_name\n      WHERE tc.table_name = 'orders'\n        AND tc.constraint_type = 'FOREIGN KEY'\n    `);\n\n    const userFk = constraints.rows.find(r => r.foreign_table_name === 'users');\n    expect(userFk).toBeDefined();\n    expect(userFk.column_name).toBe('user_id');\n    expect(userFk.foreign_column_name).toBe('id');\n  });\n\n  it('should preserve unique constraints after migration', async () => {\n    const uniqueConstraints = await testDb.pool.query(`\n      SELECT tc.constraint_name, kcu.column_name\n      FROM information_schema.table_constraints tc\n      JOIN information_schema.key_column_usage kcu\n        ON tc.constraint_name = kcu.constraint_name\n      WHERE tc.table_name = 'users'\n        AND tc.constraint_type = 'UNIQUE'\n    `);\n\n    const emailUnique = uniqueConstraints.rows.find(r => r.column_name === 'email');\n    expect(emailUnique).toBeDefined();\n  });\n\n  it('should preserve check constraints after migration', async () => {\n    \u002F\u002F After migration, check constraints should still enforce\n    await expect(\n      testDb.pool.query(`INSERT INTO orders (id, user_id, total) VALUES ('o1', 'u1', -100)`)\n    ).rejects.toThrow(); \u002F\u002F Negative total should violate check constraint\n  });\n\n  it('should maintain index coverage after migration', async () => {\n    const indexes = await testDb.pool.query(`\n      SELECT indexname, indexdef\n      FROM pg_indexes\n      WHERE tablename = 'orders'\n    `);\n\n    const indexNames = indexes.rows.map(r => r.indexname);\n    expect(indexNames).toContain('orders_user_id_idx');\n    expect(indexNames).toContain('orders_created_at_idx');\n    expect(indexNames).toContain('orders_status_idx');\n  });\n});\n```\n\n## Rollback Safety Testing\n\n```typescript\n\u002F\u002F rollback-safety.test.ts\ndescribe('Rollback Safety', () => {\n  it('should rollback cleanly to previous schema state', async () => {\n    \u002F\u002F Capture schema snapshot before migration\n    const beforeSchema = await captureSchemaSnapshot(testDb.pool, 'users');\n\n    \u002F\u002F Apply migration\n    await runner.runUp(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Rollback\n    await runner.runDown(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Capture schema snapshot after rollback\n    const afterSchema = await captureSchemaSnapshot(testDb.pool, 'users');\n\n    expect(afterSchema).toEqual(beforeSchema);\n  });\n\n  it('should preserve data through up-then-down cycle', async () => {\n    await testDb.pool.query(`\n      INSERT INTO users (id, email, name) VALUES ('u1', 'test@test.com', 'Test')\n    `);\n\n    \u002F\u002F Up\n    await runner.runUp(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Modify new column\n    await testDb.pool.query(`UPDATE users SET email_verified = true WHERE id = 'u1'`);\n\n    \u002F\u002F Down\n    await runner.runDown(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Original data should survive\n    const result = await testDb.pool.query('SELECT * FROM users WHERE id = $1', ['u1']);\n    expect(result.rows[0].email).toBe('test@test.com');\n    expect(result.rows[0].name).toBe('Test');\n  });\n\n  it('should handle rollback of data-transforming migration', async () => {\n    \u002F\u002F This tests migrations that transform data (not just schema)\n    await testDb.pool.query(`\n      INSERT INTO users (id, email, name) VALUES\n      ('u1', 'ALICE@EXAMPLE.COM', 'Alice'),\n      ('u2', 'Bob@Example.COM', 'Bob')\n    `);\n\n    \u002F\u002F Migration that lowercases all emails\n    await runner.runUp(testDb.pool, '0008_lowercase_emails');\n\n    const afterUp = await testDb.pool.query('SELECT email FROM users ORDER BY id');\n    expect(afterUp.rows[0].email).toBe('alice@example.com');\n\n    \u002F\u002F Rollback -- note: data transformation may not be reversible\n    const rollbackResult = await runner.runDown(testDb.pool, '0008_lowercase_emails');\n    \u002F\u002F The test verifies rollback behavior is documented and intentional\n    expect(rollbackResult.success).toBe(true);\n  });\n});\n\nasync function captureSchemaSnapshot(pool: Pool, tableName: string) {\n  const columns = await pool.query(`\n    SELECT column_name, data_type, column_default, is_nullable,\n           character_maximum_length, numeric_precision\n    FROM information_schema.columns\n    WHERE table_name = $1\n    ORDER BY ordinal_position\n  `, [tableName]);\n\n  const constraints = await pool.query(`\n    SELECT tc.constraint_name, tc.constraint_type, kcu.column_name\n    FROM information_schema.table_constraints tc\n    JOIN information_schema.key_column_usage kcu\n      ON tc.constraint_name = kcu.constraint_name\n    WHERE tc.table_name = $1\n    ORDER BY tc.constraint_name\n  `, [tableName]);\n\n  const indexes = await pool.query(`\n    SELECT indexname, indexdef FROM pg_indexes\n    WHERE tablename = $1 ORDER BY indexname\n  `, [tableName]);\n\n  return { columns: columns.rows, constraints: constraints.rows, indexes: indexes.rows };\n}\n```\n\n## Zero-Downtime Migration Testing\n\nZero-downtime migrations must be compatible with both the old and new application code running simultaneously during deployment.\n\n```typescript\n\u002F\u002F backward-compatible.test.ts\ndescribe('Zero-Downtime Migration Compatibility', () => {\n  it('should allow old code to function during column addition', async () => {\n    \u002F\u002F Simulate old code running while migration adds a new column\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0004_previous');\n\n    \u002F\u002F Old code inserts (does not know about new column)\n    const oldCodeInsert = `INSERT INTO users (id, email, name) VALUES ('u1', 'a@b.com', 'A')`;\n    await testDb.pool.query(oldCodeInsert);\n\n    \u002F\u002F Run migration (adds email_verified column with default)\n    await runner.runUp(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Old code insert should still work (new column has a default)\n    await expect(\n      testDb.pool.query(`INSERT INTO users (id, email, name) VALUES ('u2', 'b@c.com', 'B')`)\n    ).resolves.not.toThrow();\n\n    \u002F\u002F Old code select should still work (extra column is ignored)\n    const result = await testDb.pool.query('SELECT id, email, name FROM users');\n    expect(result.rows).toHaveLength(2);\n  });\n\n  it('should support expand-contract pattern for column rename', async () => {\n    \u002F\u002F Phase 1: Expand -- add new column, dual-write\n    await runner.runUp(testDb.pool, '0009_expand_add_full_name');\n\n    \u002F\u002F Verify both old and new columns exist\n    const cols = await testDb.pool.query(`\n      SELECT column_name FROM information_schema.columns\n      WHERE table_name = 'users' AND column_name IN ('name', 'full_name')\n    `);\n    expect(cols.rows).toHaveLength(2);\n\n    \u002F\u002F Old code writes to 'name', trigger copies to 'full_name'\n    await testDb.pool.query(`UPDATE users SET name = 'Alice Updated' WHERE id = 'u1'`);\n    const user = await testDb.pool.query(`SELECT name, full_name FROM users WHERE id = 'u1'`);\n    expect(user.rows[0].full_name).toBe('Alice Updated');\n\n    \u002F\u002F Phase 2: Contract -- remove old column (separate deployment)\n    await runner.runUp(testDb.pool, '0010_contract_remove_name');\n\n    const colsAfter = await testDb.pool.query(`\n      SELECT column_name FROM information_schema.columns\n      WHERE table_name = 'users' AND column_name IN ('name', 'full_name')\n    `);\n    expect(colsAfter.rows).toHaveLength(1);\n    expect(colsAfter.rows[0].column_name).toBe('full_name');\n  });\n\n  it('should handle NOT NULL addition with backfill', async () => {\n    \u002F\u002F Step 1: Add nullable column\n    await runner.runUp(testDb.pool, '0011_add_nullable_status');\n\n    \u002F\u002F Step 2: Backfill existing rows\n    await testDb.pool.query(`UPDATE users SET status = 'active' WHERE status IS NULL`);\n\n    \u002F\u002F Step 3: Add NOT NULL constraint\n    await runner.runUp(testDb.pool, '0012_make_status_not_null');\n\n    \u002F\u002F Verify constraint is enforced\n    await expect(\n      testDb.pool.query(`INSERT INTO users (id, email, full_name) VALUES ('u3', 'c@d.com', 'C')`)\n    ).rejects.toThrow(); \u002F\u002F status is NOT NULL now\n  });\n});\n```\n\n## Python with Alembic\n\n```python\n# test_migrations.py\nimport pytest\nimport hashlib\nimport json\nfrom alembic import command\nfrom alembic.config import Config\nfrom sqlalchemy import create_engine, text, inspect\nfrom sqlalchemy.orm import sessionmaker\n\n@pytest.fixture(scope=\"module\")\ndef alembic_config():\n    config = Config(\"alembic.ini\")\n    config.set_main_option(\"sqlalchemy.url\", \"postgresql:\u002F\u002Flocalhost:5432\u002Fmigration_test\")\n    return config\n\n@pytest.fixture(scope=\"function\")\ndef test_engine():\n    admin_engine = create_engine(\"postgresql:\u002F\u002Flocalhost:5432\u002Fpostgres\")\n    db_name = f\"migration_test_{id(object())}\"\n    with admin_engine.connect() as conn:\n        conn.execution_options(isolation_level=\"AUTOCOMMIT\")\n        conn.execute(text(f'CREATE DATABASE \"{db_name}\"'))\n\n    engine = create_engine(f\"postgresql:\u002F\u002Flocalhost:5432\u002F{db_name}\")\n    yield engine\n\n    engine.dispose()\n    with admin_engine.connect() as conn:\n        conn.execution_options(isolation_level=\"AUTOCOMMIT\")\n        conn.execute(text(f'DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)'))\n    admin_engine.dispose()\n\nclass TestMigrationUpDown:\n    def test_upgrade_creates_table(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc123\")  # target revision\n\n        inspector = inspect(test_engine)\n        tables = inspector.get_table_names()\n        assert \"users\" in tables\n\n        columns = {col[\"name\"] for col in inspector.get_columns(\"users\")}\n        assert \"id\" in columns\n        assert \"email\" in columns\n        assert \"created_at\" in columns\n\n    def test_downgrade_removes_table(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc123\")\n        command.downgrade(alembic_config, \"abc122\")  # previous revision\n\n        inspector = inspect(test_engine)\n        tables = inspector.get_table_names()\n        assert \"users\" not in tables\n\n    def test_data_preserved_through_column_addition(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc123\")\n\n        with test_engine.connect() as conn:\n            conn.execute(text(\n                \"INSERT INTO users (id, email) VALUES ('u1', 'test@test.com')\"\n            ))\n            conn.commit()\n\n            before = conn.execute(text(\"SELECT id, email FROM users\")).fetchall()\n            before_hash = hashlib.sha256(\n                json.dumps([(r[0], r[1]) for r in before]).encode()\n            ).hexdigest()\n\n        command.upgrade(alembic_config, \"abc124\")  # adds 'phone' column\n\n        with test_engine.connect() as conn:\n            after = conn.execute(text(\"SELECT id, email FROM users\")).fetchall()\n            after_hash = hashlib.sha256(\n                json.dumps([(r[0], r[1]) for r in after]).encode()\n            ).hexdigest()\n\n        assert before_hash == after_hash\n\n    def test_foreign_key_constraints_preserved(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc125\")\n\n        inspector = inspect(test_engine)\n        fks = inspector.get_foreign_keys(\"orders\")\n        user_fk = next((fk for fk in fks if fk[\"referred_table\"] == \"users\"), None)\n\n        assert user_fk is not None\n        assert user_fk[\"constrained_columns\"] == [\"user_id\"]\n        assert user_fk[\"referred_columns\"] == [\"id\"]\n```\n\n## Large Table Migration Strategies\n\n```typescript\n\u002F\u002F large-table-migration.test.ts\ndescribe('Large Table Migration Performance', () => {\n  it('should complete migration within acceptable time for large tables', async () => {\n    \u002F\u002F Seed a large dataset\n    const batchSize = 10000;\n    const totalRows = 100000;\n\n    for (let i = 0; i \u003C totalRows; i += batchSize) {\n      const values = Array.from({ length: batchSize }, (_, j) => {\n        const idx = i + j;\n        return `('user_${idx}', 'user${idx}@example.com', 'User ${idx}')`;\n      }).join(',');\n      await testDb.pool.query(`INSERT INTO users (id, email, name) VALUES ${values}`);\n    }\n\n    const countBefore = await testDb.pool.query('SELECT COUNT(*) FROM users');\n    expect(Number(countBefore.rows[0].count)).toBe(totalRows);\n\n    \u002F\u002F Run migration and measure time\n    const start = Date.now();\n    const result = await runner.runUp(testDb.pool, '0005_add_email_verified');\n    const duration = Date.now() - start;\n\n    expect(result.success).toBe(true);\n    \u002F\u002F Assert migration completes within 30 seconds for 100K rows\n    expect(duration).toBeLessThan(30000);\n\n    \u002F\u002F Verify no data loss\n    const countAfter = await testDb.pool.query('SELECT COUNT(*) FROM users');\n    expect(Number(countAfter.rows[0].count)).toBe(totalRows);\n  }, 60000); \u002F\u002F 60 second timeout\n\n  it('should use batched updates for data migration on large tables', async () => {\n    \u002F\u002F Verify the migration uses batched processing, not a single UPDATE\n    const migrationSql = runner.getMigration('0013_backfill_normalized_email').upSql;\n\n    \u002F\u002F The migration should process in batches to avoid table locks\n    expect(migrationSql).toContain('LIMIT');\n    \u002F\u002F Or verify it uses a loop\u002Fbatch pattern\n    expect(migrationSql).toMatch(\u002FDO \\$\\$|LOOP|WHILE\u002Fi);\n  });\n});\n```\n\n## Migration Ordering Verification\n\n```typescript\n\u002F\u002F migration-sequence.test.ts\ndescribe('Migration Ordering', () => {\n  it('should have strictly sequential version numbers', () => {\n    const versions = runner.getAllVersions();\n    for (let i = 1; i \u003C versions.length; i++) {\n      expect(versions[i] > versions[i - 1]).toBe(true);\n    }\n  });\n\n  it('should not have duplicate version timestamps', () => {\n    const versions = runner.getAllVersions();\n    const unique = new Set(versions);\n    expect(unique.size).toBe(versions.length);\n  });\n\n  it('should apply all migrations in sequence without error', async () => {\n    const versions = runner.getAllVersions();\n    for (const version of versions) {\n      const result = await runner.runUp(testDb.pool, version);\n      expect(result.success).toBe(true);\n    }\n  });\n\n  it('should rollback all migrations in reverse without error', async () => {\n    const versions = runner.getAllVersions().reverse();\n    for (const version of versions) {\n      const result = await runner.runDown(testDb.pool, version);\n      expect(result.success).toBe(true);\n    }\n  });\n\n  it('should detect dependency ordering issues', async () => {\n    \u002F\u002F Try applying a migration that depends on a table created by a later migration\n    \u002F\u002F This should fail, proving the ordering is enforced\n    const laterMigration = runner.getAllVersions()[5];\n    const freshDb = await createTestDatabase('ordering_test');\n    try {\n      \u002F\u002F Apply only migrations 0-2, then try to apply migration 5\n      for (const v of runner.getAllVersions().slice(0, 3)) {\n        await runner.runUp(freshDb.pool, v);\n      }\n      const result = await runner.runUp(freshDb.pool, laterMigration);\n      \u002F\u002F If it references tables from migrations 3-4, it should fail\n      if (!result.success) {\n        expect(result.error).toMatch(\u002Frelation .* does not exist|table .* doesn't exist\u002Fi);\n      }\n    } finally {\n      await freshDb.teardown();\n    }\n  });\n});\n```\n\n## Configuration\n\n```typescript\n\u002F\u002F migration-test.config.ts\ninterface MigrationTestConfig {\n  database: {\n    adminUrl: string;\n    baseUrl: string;\n    testDbPrefix: string;\n    maxTestDatabases: number;\n    cleanupOrphanedDbs: boolean;\n  };\n  migrations: {\n    directory: string;\n    schemaFile: string;\n    seedFile: string;\n  };\n  performance: {\n    maxMigrationDurationMs: number;\n    largeTableRowCount: number;\n    batchSize: number;\n  };\n  reporting: {\n    generateSchemaSnapshots: boolean;\n    snapshotDirectory: string;\n    reportFormat: 'json' | 'markdown';\n  };\n}\n\nconst defaultConfig: MigrationTestConfig = {\n  database: {\n    adminUrl: process.env.TEST_DATABASE_ADMIN_URL || 'postgresql:\u002F\u002Flocalhost:5432\u002Fpostgres',\n    baseUrl: process.env.TEST_DATABASE_BASE_URL || 'postgresql:\u002F\u002Flocalhost:5432',\n    testDbPrefix: 'migration_test',\n    maxTestDatabases: 10,\n    cleanupOrphanedDbs: true,\n  },\n  migrations: {\n    directory: '.\u002Fdrizzle\u002Fmigrations',\n    schemaFile: '.\u002Fsrc\u002Fdb\u002Fschema.ts',\n    seedFile: '.\u002Fsrc\u002Fdb\u002Fseed.ts',\n  },\n  performance: {\n    maxMigrationDurationMs: 30000,\n    largeTableRowCount: 100000,\n    batchSize: 10000,\n  },\n  reporting: {\n    generateSchemaSnapshots: true,\n    snapshotDirectory: '.\u002Ftest-artifacts\u002Fschema-snapshots',\n    reportFormat: 'json',\n  },\n};\n```\n\n## Best Practices\n\n1. **Create one test database per test suite, not per test** -- Database creation is expensive. Use transactions for isolation within a suite and rollback between tests when possible.\n\n2. **Always test both directions** -- Every migration must have an up test and a down test. Discovering that rollback is broken during an incident is the worst possible time to find out.\n\n3. **Seed realistic data before testing migrations** -- Empty-table migrations always pass. Seed data that includes nulls, unicode, large text fields, maximum-length strings, and edge-case values.\n\n4. **Capture schema snapshots before and after** -- Store a snapshot of columns, constraints, indexes, and triggers. Compare snapshots to detect unintended schema drift.\n\n5. **Test migration idempotency** -- Run the same migration twice. It should either succeed (if designed to be idempotent) or fail with a clear error (not corrupt data).\n\n6. **Verify index performance after migration** -- An index that exists is not the same as an index that performs. Run EXPLAIN ANALYZE on critical queries after migration to verify index usage.\n\n7. **Use the expand-contract pattern for breaking changes** -- Never rename or remove a column in a single step. Expand (add new), migrate data, update application, contract (remove old) across multiple deployments.\n\n8. **Test with production-like constraints enabled** -- Do not disable foreign keys, unique constraints, or check constraints during testing. Migrations must work with all constraints active.\n\n9. **Include concurrent access tests** -- Run SELECT and INSERT queries during migration execution to verify the migration does not cause blocking or deadlocks in a zero-downtime deployment.\n\n10. **Automate migration testing in CI** -- Every pull request that includes a migration file should automatically run the migration test suite against a clean database.\n\n11. **Document irreversible migrations explicitly** -- If a migration cannot be rolled back (dropping a column with data), document this in the migration file and in the test with a clear reason.\n\n12. **Test seed data compatibility** -- After every migration, run the seed script to verify it still works. Broken seed scripts block new developer onboarding and CI environment setup.\n\n## Anti-Patterns to Avoid\n\n1. **Testing migrations on empty databases only** -- An empty database has no data to corrupt, no constraints to violate, and no performance issues. Always seed data before testing migrations.\n\n2. **Sharing test databases between test runs** -- Leftover state from a previous run causes flaky tests. Create a fresh database for every test suite execution and destroy it afterward.\n\n3. **Skipping rollback tests because you will never rollback** -- Production incidents happen. Deployments fail. Rollback capability is insurance, and untested insurance pays nothing.\n\n4. **Using IF EXISTS \u002F IF NOT EXISTS to mask ordering bugs** -- Wrapping every DDL in conditional checks hides dependency ordering problems. Fix the ordering instead of working around it.\n\n5. **Testing only the latest migration in isolation** -- Migrations form a chain. Test the complete chain from empty to current, not just the latest link. A migration that works alone may conflict with a previous one.\n\n6. **Ignoring migration performance** -- A migration that takes 45 minutes on a production-sized table causes 45 minutes of degraded service. Always benchmark with realistic data volumes.\n\n7. **Writing irreversible migrations without documentation** -- If a migration drops data or transforms it one-way, this must be explicitly documented and the down migration should raise a clear error, not silently do nothing.\n\n8. **Hardcoding test data IDs that conflict with production sequences** -- Use UUIDs or explicitly non-overlapping ranges for test data to prevent conflicts if tests accidentally run against production.\n\n## Debugging Tips\n\n1. **Migration fails with \"relation does not exist\"** -- Check migration ordering. The referenced table may be created by a later migration. Verify that your migration runner processes files in the correct order (lexicographic sort of filenames is the standard).\n\n2. **Rollback fails with \"column does not exist\"** -- The down migration references a column that was already removed by a later migration. Test rollbacks in reverse order, starting from the most recent migration.\n\n3. **Data type mismatch after migration** -- Use explicit CAST in data-transforming migrations. Implicit type coercion varies across database versions and may silently truncate data.\n\n4. **Migration succeeds locally but fails in CI** -- Check database versions. A feature available in PostgreSQL 15 may not exist in PostgreSQL 13. Pin your CI database version to match production.\n\n5. **Test database not cleaning up** -- Implement a cleanup script that drops all databases matching your test prefix. Run it as a CI step or a pre-test hook. Orphaned test databases consume disk space and connections.\n\n6. **Constraint violation during migration** -- The migration is trying to add a NOT NULL constraint to a column with existing NULL values, or a UNIQUE constraint on non-unique data. Always backfill data before adding constraints.\n\n7. **Migration takes too long in tests** -- Reduce the seed data volume for routine tests but keep a separate performance test suite with production-scale data. Use the performance suite on a schedule, not on every commit.\n\n8. **Foreign key prevents table drop during rollback** -- Drop foreign key constraints before dropping the referenced table. The rollback migration must remove dependencies in the correct order.\n\n9. **Index creation blocks queries in zero-downtime tests** -- Use CREATE INDEX CONCURRENTLY in PostgreSQL to avoid table locks. Note that this cannot run inside a transaction, so the migration must not be wrapped in BEGIN\u002FCOMMIT.\n\n10. **Seed data breaks after migration** -- Update seed scripts in the same pull request as the migration. Never merge a migration without verifying seed compatibility.","# Database Migration Test Generator Skill\n\nYou are an expert QA engineer specializing in database migration testing and data integrity verification. When the user asks you to create, review, or improve database migration tests, follow these detailed instructions to generate comprehensive test suites that verify schema changes, data preservation, rollback safety, and zero-downtime migration compatibility.\n\n## Core Principles\n\n1. **Migrations are code, test them as code** -- Every migration file is a deployable artifact that modifies production state. It deserves the same testing rigor as application code. Untested migrations are production time bombs.\n2. **Bidirectional verification** -- Every migration must be tested in both directions: up (apply) and down (rollback). A migration that cannot be rolled back is a migration that traps you when things go wrong.\n3. **Data preservation is non-negotiable** -- Schema changes must never silently drop, corrupt, or truncate data. Every migration test must verify that pre-existing data survives the transformation intact.\n4. **Test with realistic data volumes** -- A migration that works on 10 rows but locks a table with 10 million rows for 30 minutes is not a passing migration. Volume testing is mandatory for production-bound migrations.\n5. **Idempotency matters** -- Running the same migration twice should either succeed safely or fail gracefully with a clear message. Never assume migrations run exactly once.\n6. **Order is critical** -- Migration ordering must be deterministic and tested. Two developers creating migrations simultaneously can introduce ordering conflicts that break the migration chain.\n7. **Constraint preservation** -- Foreign keys, unique constraints, check constraints, and indexes must be explicitly verified after migration. Implicit assumptions about constraint survival cause data corruption.\n8. **Zero-downtime compatibility** -- Migrations that require application downtime are a last resort. Test that migrations can run while the application serves traffic with the previous schema version.\n9. **Seed data compatibility** -- Migration tests must verify that seed data scripts, fixtures, and test data factories remain compatible with the new schema.\n10. **Atomic migration units** -- Each migration should do one logical thing. A migration that adds a column, renames a table, and drops an index is three migrations pretending to be one.\n\n## Project Structure\n\n```\ntests\u002F\n  migrations\u002F\n    helpers\u002F\n      migration-runner.ts\n      test-database.ts\n      data-seeder.ts\n      snapshot-comparator.ts\n    schema\u002F\n      schema-change.test.ts\n      column-addition.test.ts\n      column-removal.test.ts\n      table-rename.test.ts\n      type-change.test.ts\n    integrity\u002F\n      data-preservation.test.ts\n      constraint-verification.test.ts\n      index-verification.test.ts\n      foreign-key.test.ts\n    rollback\u002F\n      rollback-safety.test.ts\n      rollback-data-preservation.test.ts\n      partial-rollback.test.ts\n    zero-downtime\u002F\n      backward-compatible.test.ts\n      dual-write.test.ts\n      online-migration.test.ts\n    ordering\u002F\n      migration-sequence.test.ts\n      concurrent-migration.test.ts\n    performance\u002F\n      large-table-migration.test.ts\n      index-creation.test.ts\n    config\u002F\n      migration-test.config.ts\n  fixtures\u002F\n    seed-data\u002F\n      pre-migration.sql\n      post-migration-expected.sql\n```\n\n## Test Database Setup\n\nBefore testing migrations, you need an isolated database environment that can be created and destroyed rapidly.\n\n### TypeScript with Drizzle ORM\n\n```typescript\n\u002F\u002F test-database.ts\nimport { drizzle } from 'drizzle-orm\u002Fnode-postgres';\nimport { migrate } from 'drizzle-orm\u002Fnode-postgres\u002Fmigrator';\nimport { Pool } from 'pg';\nimport { execSync } from 'child_process';\n\ninterface TestDatabase {\n  pool: Pool;\n  db: ReturnType\u003Ctypeof drizzle>;\n  name: string;\n  connectionString: string;\n  teardown: () => Promise\u003Cvoid>;\n}\n\nasync function createTestDatabase(prefix: string = 'migration_test'): Promise\u003CTestDatabase> {\n  const dbName = `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n  const adminPool = new Pool({\n    connectionString: process.env.TEST_DATABASE_ADMIN_URL,\n  });\n\n  await adminPool.query(`CREATE DATABASE \"${dbName}\"`);\n  await adminPool.end();\n\n  const connectionString = `${process.env.TEST_DATABASE_BASE_URL}\u002F${dbName}`;\n  const pool = new Pool({ connectionString });\n  const db = drizzle(pool);\n\n  return {\n    pool,\n    db,\n    name: dbName,\n    connectionString,\n    teardown: async () => {\n      await pool.end();\n      const cleanup = new Pool({\n        connectionString: process.env.TEST_DATABASE_ADMIN_URL,\n      });\n      await cleanup.query(`DROP DATABASE IF EXISTS \"${dbName}\" WITH (FORCE)`);\n      await cleanup.end();\n    },\n  };\n}\n\nasync function applyMigrationsUpTo(\n  db: ReturnType\u003Ctypeof drizzle>,\n  migrationsFolder: string,\n  upToVersion?: string\n): Promise\u003Cvoid> {\n  if (upToVersion) {\n    \u002F\u002F Apply migrations sequentially up to the specified version\n    const fs = await import('fs');\n    const path = await import('path');\n    const files = fs.readdirSync(migrationsFolder)\n      .filter(f => f.endsWith('.sql'))\n      .sort()\n      .filter(f => f \u003C= upToVersion);\n\n    for (const file of files) {\n      const sql = fs.readFileSync(path.join(migrationsFolder, file), 'utf-8');\n      await db.execute(sql);\n    }\n  } else {\n    await migrate(db, { migrationsFolder });\n  }\n}\n```\n\n### Migration Runner\n\n```typescript\n\u002F\u002F migration-runner.ts\nimport { readFileSync, readdirSync } from 'fs';\nimport { join } from 'path';\n\ninterface MigrationFile {\n  version: string;\n  name: string;\n  upSql: string;\n  downSql: string;\n  filePath: string;\n}\n\ninterface MigrationResult {\n  version: string;\n  direction: 'up' | 'down';\n  success: boolean;\n  duration: number;\n  error?: string;\n  rowsAffected?: number;\n}\n\nclass MigrationRunner {\n  private migrationsDir: string;\n  private migrations: MigrationFile[] = [];\n\n  constructor(migrationsDir: string) {\n    this.migrationsDir = migrationsDir;\n    this.loadMigrations();\n  }\n\n  private loadMigrations(): void {\n    const files = readdirSync(this.migrationsDir)\n      .filter(f => f.endsWith('.sql'))\n      .sort();\n\n    this.migrations = files.map(file => {\n      const content = readFileSync(join(this.migrationsDir, file), 'utf-8');\n      const [upSql, downSql] = this.splitMigration(content);\n      return {\n        version: file.replace('.sql', ''),\n        name: file,\n        upSql,\n        downSql,\n        filePath: join(this.migrationsDir, file),\n      };\n    });\n  }\n\n  private splitMigration(content: string): [string, string] {\n    const downMarker = '-- migrate:down';\n    const parts = content.split(downMarker);\n    return [\n      parts[0].replace('-- migrate:up', '').trim(),\n      parts.length > 1 ? parts[1].trim() : '',\n    ];\n  }\n\n  async runUp(pool: Pool, version: string): Promise\u003CMigrationResult> {\n    const migration = this.getMigration(version);\n    const start = Date.now();\n    try {\n      const result = await pool.query(migration.upSql);\n      return {\n        version, direction: 'up', success: true,\n        duration: Date.now() - start,\n        rowsAffected: result.rowCount ?? 0,\n      };\n    } catch (error) {\n      return {\n        version, direction: 'up', success: false,\n        duration: Date.now() - start,\n        error: (error as Error).message,\n      };\n    }\n  }\n\n  async runDown(pool: Pool, version: string): Promise\u003CMigrationResult> {\n    const migration = this.getMigration(version);\n    if (!migration.downSql) {\n      return {\n        version, direction: 'down', success: false,\n        duration: 0, error: 'No down migration defined',\n      };\n    }\n    const start = Date.now();\n    try {\n      const result = await pool.query(migration.downSql);\n      return {\n        version, direction: 'down', success: true,\n        duration: Date.now() - start,\n        rowsAffected: result.rowCount ?? 0,\n      };\n    } catch (error) {\n      return {\n        version, direction: 'down', success: false,\n        duration: Date.now() - start,\n        error: (error as Error).message,\n      };\n    }\n  }\n\n  getMigration(version: string): MigrationFile {\n    const migration = this.migrations.find(m => m.version === version);\n    if (!migration) throw new Error(`Migration ${version} not found`);\n    return migration;\n  }\n\n  getAllVersions(): string[] {\n    return this.migrations.map(m => m.version);\n  }\n}\n```\n\n## Schema Change Testing\n\n### Column Addition and Removal\n\n```typescript\n\u002F\u002F schema-change.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\n\ndescribe('Schema Change Migrations', () => {\n  let testDb: TestDatabase;\n  let runner: MigrationRunner;\n\n  beforeAll(async () => {\n    testDb = await createTestDatabase('schema_test');\n    runner = new MigrationRunner('.\u002Fdrizzle\u002Fmigrations');\n  });\n\n  afterAll(async () => {\n    await testDb.teardown();\n  });\n\n  describe('Column Addition: add email_verified to users', () => {\n    it('should add the column with correct type and default', async () => {\n      \u002F\u002F Apply migrations up to the one before our target\n      await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0004_previous');\n\n      \u002F\u002F Seed test data before migration\n      await testDb.pool.query(`\n        INSERT INTO users (id, email, name) VALUES\n        ('u1', 'alice@example.com', 'Alice'),\n        ('u2', 'bob@example.com', 'Bob')\n      `);\n\n      \u002F\u002F Run the migration under test\n      const result = await runner.runUp(testDb.pool, '0005_add_email_verified');\n      expect(result.success).toBe(true);\n\n      \u002F\u002F Verify column exists with correct type\n      const columnInfo = await testDb.pool.query(`\n        SELECT column_name, data_type, column_default, is_nullable\n        FROM information_schema.columns\n        WHERE table_name = 'users' AND column_name = 'email_verified'\n      `);\n      expect(columnInfo.rows).toHaveLength(1);\n      expect(columnInfo.rows[0].data_type).toBe('boolean');\n      expect(columnInfo.rows[0].column_default).toBe('false');\n      expect(columnInfo.rows[0].is_nullable).toBe('NO');\n    });\n\n    it('should preserve existing data after column addition', async () => {\n      const users = await testDb.pool.query(\n        'SELECT id, email, name, email_verified FROM users ORDER BY id'\n      );\n      expect(users.rows).toHaveLength(2);\n      expect(users.rows[0]).toMatchObject({ id: 'u1', email: 'alice@example.com', email_verified: false });\n      expect(users.rows[1]).toMatchObject({ id: 'u2', email: 'bob@example.com', email_verified: false });\n    });\n\n    it('should allow rollback without data loss', async () => {\n      const result = await runner.runDown(testDb.pool, '0005_add_email_verified');\n      expect(result.success).toBe(true);\n\n      \u002F\u002F Verify column is gone\n      const columnInfo = await testDb.pool.query(`\n        SELECT column_name FROM information_schema.columns\n        WHERE table_name = 'users' AND column_name = 'email_verified'\n      `);\n      expect(columnInfo.rows).toHaveLength(0);\n\n      \u002F\u002F Verify original data still intact\n      const users = await testDb.pool.query('SELECT id, email, name FROM users ORDER BY id');\n      expect(users.rows).toHaveLength(2);\n      expect(users.rows[0].email).toBe('alice@example.com');\n    });\n  });\n\n  describe('Column Type Change: string to enum', () => {\n    it('should convert existing values to enum without data loss', async () => {\n      await testDb.pool.query(`\n        INSERT INTO orders (id, status) VALUES\n        ('o1', 'pending'), ('o2', 'shipped'), ('o3', 'delivered')\n      `);\n\n      const result = await runner.runUp(testDb.pool, '0006_status_to_enum');\n      expect(result.success).toBe(true);\n\n      const orders = await testDb.pool.query('SELECT id, status FROM orders ORDER BY id');\n      expect(orders.rows[0].status).toBe('pending');\n      expect(orders.rows[1].status).toBe('shipped');\n      expect(orders.rows[2].status).toBe('delivered');\n    });\n\n    it('should reject invalid enum values after migration', async () => {\n      await expect(\n        testDb.pool.query(`INSERT INTO orders (id, status) VALUES ('o4', 'invalid_status')`)\n      ).rejects.toThrow();\n    });\n  });\n});\n```\n\n## Data Integrity Verification\n\n```typescript\n\u002F\u002F data-preservation.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\nimport { createHash } from 'crypto';\n\ndescribe('Data Integrity During Migration', () => {\n  let testDb: TestDatabase;\n\n  beforeAll(async () => {\n    testDb = await createTestDatabase('integrity_test');\n  });\n\n  afterAll(async () => {\n    await testDb.teardown();\n  });\n\n  it('should preserve row count across migration', async () => {\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0004_previous');\n\n    \u002F\u002F Seed substantial data\n    const insertValues = Array.from({ length: 1000 }, (_, i) =>\n      `('user_${i}', 'user${i}@example.com', 'User ${i}')`\n    ).join(',\\n');\n    await testDb.pool.query(`INSERT INTO users (id, email, name) VALUES ${insertValues}`);\n\n    const beforeCount = await testDb.pool.query('SELECT COUNT(*) as count FROM users');\n    expect(Number(beforeCount.rows[0].count)).toBe(1000);\n\n    \u002F\u002F Run migration\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0005_add_email_verified');\n\n    const afterCount = await testDb.pool.query('SELECT COUNT(*) as count FROM users');\n    expect(Number(afterCount.rows[0].count)).toBe(1000);\n  });\n\n  it('should preserve data checksums across migration', async () => {\n    \u002F\u002F Capture checksums before migration\n    const beforeData = await testDb.pool.query(\n      'SELECT id, email, name FROM users ORDER BY id'\n    );\n    const beforeChecksum = createHash('sha256')\n      .update(JSON.stringify(beforeData.rows))\n      .digest('hex');\n\n    \u002F\u002F Run migration that adds a column\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0006_add_profile_url');\n\n    \u002F\u002F Capture same columns after migration (excluding new column)\n    const afterData = await testDb.pool.query(\n      'SELECT id, email, name FROM users ORDER BY id'\n    );\n    const afterChecksum = createHash('sha256')\n      .update(JSON.stringify(afterData.rows))\n      .digest('hex');\n\n    expect(afterChecksum).toBe(beforeChecksum);\n  });\n\n  it('should preserve unicode data during encoding-sensitive migrations', async () => {\n    await testDb.pool.query(`\n      INSERT INTO products (id, name, description) VALUES\n      ('p1', 'Cafe Latte', 'Smooth espresso with steamed milk'),\n      ('p2', 'Matcha', 'Japanese green tea powder'),\n      ('p3', 'Acai Bowl', 'Brazilian superfood bowl')\n    `);\n\n    await runner.runUp(testDb.pool, '0007_change_text_encoding');\n\n    const products = await testDb.pool.query('SELECT name, description FROM products ORDER BY id');\n    expect(products.rows[0].name).toBe('Cafe Latte');\n    expect(products.rows[1].name).toBe('Matcha');\n    expect(products.rows[2].name).toBe('Acai Bowl');\n  });\n});\n```\n\n## Foreign Key and Constraint Preservation\n\n```typescript\n\u002F\u002F constraint-verification.test.ts\ndescribe('Constraint Preservation', () => {\n  it('should preserve foreign key constraints after migration', async () => {\n    const constraints = await testDb.pool.query(`\n      SELECT\n        tc.constraint_name,\n        tc.constraint_type,\n        kcu.column_name,\n        ccu.table_name AS foreign_table_name,\n        ccu.column_name AS foreign_column_name\n      FROM information_schema.table_constraints tc\n      JOIN information_schema.key_column_usage kcu\n        ON tc.constraint_name = kcu.constraint_name\n      LEFT JOIN information_schema.constraint_column_usage ccu\n        ON tc.constraint_name = ccu.constraint_name\n      WHERE tc.table_name = 'orders'\n        AND tc.constraint_type = 'FOREIGN KEY'\n    `);\n\n    const userFk = constraints.rows.find(r => r.foreign_table_name === 'users');\n    expect(userFk).toBeDefined();\n    expect(userFk.column_name).toBe('user_id');\n    expect(userFk.foreign_column_name).toBe('id');\n  });\n\n  it('should preserve unique constraints after migration', async () => {\n    const uniqueConstraints = await testDb.pool.query(`\n      SELECT tc.constraint_name, kcu.column_name\n      FROM information_schema.table_constraints tc\n      JOIN information_schema.key_column_usage kcu\n        ON tc.constraint_name = kcu.constraint_name\n      WHERE tc.table_name = 'users'\n        AND tc.constraint_type = 'UNIQUE'\n    `);\n\n    const emailUnique = uniqueConstraints.rows.find(r => r.column_name === 'email');\n    expect(emailUnique).toBeDefined();\n  });\n\n  it('should preserve check constraints after migration', async () => {\n    \u002F\u002F After migration, check constraints should still enforce\n    await expect(\n      testDb.pool.query(`INSERT INTO orders (id, user_id, total) VALUES ('o1', 'u1', -100)`)\n    ).rejects.toThrow(); \u002F\u002F Negative total should violate check constraint\n  });\n\n  it('should maintain index coverage after migration', async () => {\n    const indexes = await testDb.pool.query(`\n      SELECT indexname, indexdef\n      FROM pg_indexes\n      WHERE tablename = 'orders'\n    `);\n\n    const indexNames = indexes.rows.map(r => r.indexname);\n    expect(indexNames).toContain('orders_user_id_idx');\n    expect(indexNames).toContain('orders_created_at_idx');\n    expect(indexNames).toContain('orders_status_idx');\n  });\n});\n```\n\n## Rollback Safety Testing\n\n```typescript\n\u002F\u002F rollback-safety.test.ts\ndescribe('Rollback Safety', () => {\n  it('should rollback cleanly to previous schema state', async () => {\n    \u002F\u002F Capture schema snapshot before migration\n    const beforeSchema = await captureSchemaSnapshot(testDb.pool, 'users');\n\n    \u002F\u002F Apply migration\n    await runner.runUp(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Rollback\n    await runner.runDown(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Capture schema snapshot after rollback\n    const afterSchema = await captureSchemaSnapshot(testDb.pool, 'users');\n\n    expect(afterSchema).toEqual(beforeSchema);\n  });\n\n  it('should preserve data through up-then-down cycle', async () => {\n    await testDb.pool.query(`\n      INSERT INTO users (id, email, name) VALUES ('u1', 'test@test.com', 'Test')\n    `);\n\n    \u002F\u002F Up\n    await runner.runUp(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Modify new column\n    await testDb.pool.query(`UPDATE users SET email_verified = true WHERE id = 'u1'`);\n\n    \u002F\u002F Down\n    await runner.runDown(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Original data should survive\n    const result = await testDb.pool.query('SELECT * FROM users WHERE id = $1', ['u1']);\n    expect(result.rows[0].email).toBe('test@test.com');\n    expect(result.rows[0].name).toBe('Test');\n  });\n\n  it('should handle rollback of data-transforming migration', async () => {\n    \u002F\u002F This tests migrations that transform data (not just schema)\n    await testDb.pool.query(`\n      INSERT INTO users (id, email, name) VALUES\n      ('u1', 'ALICE@EXAMPLE.COM', 'Alice'),\n      ('u2', 'Bob@Example.COM', 'Bob')\n    `);\n\n    \u002F\u002F Migration that lowercases all emails\n    await runner.runUp(testDb.pool, '0008_lowercase_emails');\n\n    const afterUp = await testDb.pool.query('SELECT email FROM users ORDER BY id');\n    expect(afterUp.rows[0].email).toBe('alice@example.com');\n\n    \u002F\u002F Rollback -- note: data transformation may not be reversible\n    const rollbackResult = await runner.runDown(testDb.pool, '0008_lowercase_emails');\n    \u002F\u002F The test verifies rollback behavior is documented and intentional\n    expect(rollbackResult.success).toBe(true);\n  });\n});\n\nasync function captureSchemaSnapshot(pool: Pool, tableName: string) {\n  const columns = await pool.query(`\n    SELECT column_name, data_type, column_default, is_nullable,\n           character_maximum_length, numeric_precision\n    FROM information_schema.columns\n    WHERE table_name = $1\n    ORDER BY ordinal_position\n  `, [tableName]);\n\n  const constraints = await pool.query(`\n    SELECT tc.constraint_name, tc.constraint_type, kcu.column_name\n    FROM information_schema.table_constraints tc\n    JOIN information_schema.key_column_usage kcu\n      ON tc.constraint_name = kcu.constraint_name\n    WHERE tc.table_name = $1\n    ORDER BY tc.constraint_name\n  `, [tableName]);\n\n  const indexes = await pool.query(`\n    SELECT indexname, indexdef FROM pg_indexes\n    WHERE tablename = $1 ORDER BY indexname\n  `, [tableName]);\n\n  return { columns: columns.rows, constraints: constraints.rows, indexes: indexes.rows };\n}\n```\n\n## Zero-Downtime Migration Testing\n\nZero-downtime migrations must be compatible with both the old and new application code running simultaneously during deployment.\n\n```typescript\n\u002F\u002F backward-compatible.test.ts\ndescribe('Zero-Downtime Migration Compatibility', () => {\n  it('should allow old code to function during column addition', async () => {\n    \u002F\u002F Simulate old code running while migration adds a new column\n    await applyMigrationsUpTo(testDb.db, '.\u002Fdrizzle\u002Fmigrations', '0004_previous');\n\n    \u002F\u002F Old code inserts (does not know about new column)\n    const oldCodeInsert = `INSERT INTO users (id, email, name) VALUES ('u1', 'a@b.com', 'A')`;\n    await testDb.pool.query(oldCodeInsert);\n\n    \u002F\u002F Run migration (adds email_verified column with default)\n    await runner.runUp(testDb.pool, '0005_add_email_verified');\n\n    \u002F\u002F Old code insert should still work (new column has a default)\n    await expect(\n      testDb.pool.query(`INSERT INTO users (id, email, name) VALUES ('u2', 'b@c.com', 'B')`)\n    ).resolves.not.toThrow();\n\n    \u002F\u002F Old code select should still work (extra column is ignored)\n    const result = await testDb.pool.query('SELECT id, email, name FROM users');\n    expect(result.rows).toHaveLength(2);\n  });\n\n  it('should support expand-contract pattern for column rename', async () => {\n    \u002F\u002F Phase 1: Expand -- add new column, dual-write\n    await runner.runUp(testDb.pool, '0009_expand_add_full_name');\n\n    \u002F\u002F Verify both old and new columns exist\n    const cols = await testDb.pool.query(`\n      SELECT column_name FROM information_schema.columns\n      WHERE table_name = 'users' AND column_name IN ('name', 'full_name')\n    `);\n    expect(cols.rows).toHaveLength(2);\n\n    \u002F\u002F Old code writes to 'name', trigger copies to 'full_name'\n    await testDb.pool.query(`UPDATE users SET name = 'Alice Updated' WHERE id = 'u1'`);\n    const user = await testDb.pool.query(`SELECT name, full_name FROM users WHERE id = 'u1'`);\n    expect(user.rows[0].full_name).toBe('Alice Updated');\n\n    \u002F\u002F Phase 2: Contract -- remove old column (separate deployment)\n    await runner.runUp(testDb.pool, '0010_contract_remove_name');\n\n    const colsAfter = await testDb.pool.query(`\n      SELECT column_name FROM information_schema.columns\n      WHERE table_name = 'users' AND column_name IN ('name', 'full_name')\n    `);\n    expect(colsAfter.rows).toHaveLength(1);\n    expect(colsAfter.rows[0].column_name).toBe('full_name');\n  });\n\n  it('should handle NOT NULL addition with backfill', async () => {\n    \u002F\u002F Step 1: Add nullable column\n    await runner.runUp(testDb.pool, '0011_add_nullable_status');\n\n    \u002F\u002F Step 2: Backfill existing rows\n    await testDb.pool.query(`UPDATE users SET status = 'active' WHERE status IS NULL`);\n\n    \u002F\u002F Step 3: Add NOT NULL constraint\n    await runner.runUp(testDb.pool, '0012_make_status_not_null');\n\n    \u002F\u002F Verify constraint is enforced\n    await expect(\n      testDb.pool.query(`INSERT INTO users (id, email, full_name) VALUES ('u3', 'c@d.com', 'C')`)\n    ).rejects.toThrow(); \u002F\u002F status is NOT NULL now\n  });\n});\n```\n\n## Python with Alembic\n\n```python\n# test_migrations.py\nimport pytest\nimport hashlib\nimport json\nfrom alembic import command\nfrom alembic.config import Config\nfrom sqlalchemy import create_engine, text, inspect\nfrom sqlalchemy.orm import sessionmaker\n\n@pytest.fixture(scope=\"module\")\ndef alembic_config():\n    config = Config(\"alembic.ini\")\n    config.set_main_option(\"sqlalchemy.url\", \"postgresql:\u002F\u002Flocalhost:5432\u002Fmigration_test\")\n    return config\n\n@pytest.fixture(scope=\"function\")\ndef test_engine():\n    admin_engine = create_engine(\"postgresql:\u002F\u002Flocalhost:5432\u002Fpostgres\")\n    db_name = f\"migration_test_{id(object())}\"\n    with admin_engine.connect() as conn:\n        conn.execution_options(isolation_level=\"AUTOCOMMIT\")\n        conn.execute(text(f'CREATE DATABASE \"{db_name}\"'))\n\n    engine = create_engine(f\"postgresql:\u002F\u002Flocalhost:5432\u002F{db_name}\")\n    yield engine\n\n    engine.dispose()\n    with admin_engine.connect() as conn:\n        conn.execution_options(isolation_level=\"AUTOCOMMIT\")\n        conn.execute(text(f'DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)'))\n    admin_engine.dispose()\n\nclass TestMigrationUpDown:\n    def test_upgrade_creates_table(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc123\")  # target revision\n\n        inspector = inspect(test_engine)\n        tables = inspector.get_table_names()\n        assert \"users\" in tables\n\n        columns = {col[\"name\"] for col in inspector.get_columns(\"users\")}\n        assert \"id\" in columns\n        assert \"email\" in columns\n        assert \"created_at\" in columns\n\n    def test_downgrade_removes_table(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc123\")\n        command.downgrade(alembic_config, \"abc122\")  # previous revision\n\n        inspector = inspect(test_engine)\n        tables = inspector.get_table_names()\n        assert \"users\" not in tables\n\n    def test_data_preserved_through_column_addition(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc123\")\n\n        with test_engine.connect() as conn:\n            conn.execute(text(\n                \"INSERT INTO users (id, email) VALUES ('u1', 'test@test.com')\"\n            ))\n            conn.commit()\n\n            before = conn.execute(text(\"SELECT id, email FROM users\")).fetchall()\n            before_hash = hashlib.sha256(\n                json.dumps([(r[0], r[1]) for r in before]).encode()\n            ).hexdigest()\n\n        command.upgrade(alembic_config, \"abc124\")  # adds 'phone' column\n\n        with test_engine.connect() as conn:\n            after = conn.execute(text(\"SELECT id, email FROM users\")).fetchall()\n            after_hash = hashlib.sha256(\n                json.dumps([(r[0], r[1]) for r in after]).encode()\n            ).hexdigest()\n\n        assert before_hash == after_hash\n\n    def test_foreign_key_constraints_preserved(self, test_engine, alembic_config):\n        alembic_config.set_main_option(\"sqlalchemy.url\", str(test_engine.url))\n        command.upgrade(alembic_config, \"abc125\")\n\n        inspector = inspect(test_engine)\n        fks = inspector.get_foreign_keys(\"orders\")\n        user_fk = next((fk for fk in fks if fk[\"referred_table\"] == \"users\"), None)\n\n        assert user_fk is not None\n        assert user_fk[\"constrained_columns\"] == [\"user_id\"]\n        assert user_fk[\"referred_columns\"] == [\"id\"]\n```\n\n## Large Table Migration Strategies\n\n```typescript\n\u002F\u002F large-table-migration.test.ts\ndescribe('Large Table Migration Performance', () => {\n  it('should complete migration within acceptable time for large tables', async () => {\n    \u002F\u002F Seed a large dataset\n    const batchSize = 10000;\n    const totalRows = 100000;\n\n    for (let i = 0; i \u003C totalRows; i += batchSize) {\n      const values = Array.from({ length: batchSize }, (_, j) => {\n        const idx = i + j;\n        return `('user_${idx}', 'user${idx}@example.com', 'User ${idx}')`;\n      }).join(',');\n      await testDb.pool.query(`INSERT INTO users (id, email, name) VALUES ${values}`);\n    }\n\n    const countBefore = await testDb.pool.query('SELECT COUNT(*) FROM users');\n    expect(Number(countBefore.rows[0].count)).toBe(totalRows);\n\n    \u002F\u002F Run migration and measure time\n    const start = Date.now();\n    const result = await runner.runUp(testDb.pool, '0005_add_email_verified');\n    const duration = Date.now() - start;\n\n    expect(result.success).toBe(true);\n    \u002F\u002F Assert migration completes within 30 seconds for 100K rows\n    expect(duration).toBeLessThan(30000);\n\n    \u002F\u002F Verify no data loss\n    const countAfter = await testDb.pool.query('SELECT COUNT(*) FROM users');\n    expect(Number(countAfter.rows[0].count)).toBe(totalRows);\n  }, 60000); \u002F\u002F 60 second timeout\n\n  it('should use batched updates for data migration on large tables', async () => {\n    \u002F\u002F Verify the migration uses batched processing, not a single UPDATE\n    const migrationSql = runner.getMigration('0013_backfill_normalized_email').upSql;\n\n    \u002F\u002F The migration should process in batches to avoid table locks\n    expect(migrationSql).toContain('LIMIT');\n    \u002F\u002F Or verify it uses a loop\u002Fbatch pattern\n    expect(migrationSql).toMatch(\u002FDO \\$\\$|LOOP|WHILE\u002Fi);\n  });\n});\n```\n\n## Migration Ordering Verification\n\n```typescript\n\u002F\u002F migration-sequence.test.ts\ndescribe('Migration Ordering', () => {\n  it('should have strictly sequential version numbers', () => {\n    const versions = runner.getAllVersions();\n    for (let i = 1; i \u003C versions.length; i++) {\n      expect(versions[i] > versions[i - 1]).toBe(true);\n    }\n  });\n\n  it('should not have duplicate version timestamps', () => {\n    const versions = runner.getAllVersions();\n    const unique = new Set(versions);\n    expect(unique.size).toBe(versions.length);\n  });\n\n  it('should apply all migrations in sequence without error', async () => {\n    const versions = runner.getAllVersions();\n    for (const version of versions) {\n      const result = await runner.runUp(testDb.pool, version);\n      expect(result.success).toBe(true);\n    }\n  });\n\n  it('should rollback all migrations in reverse without error', async () => {\n    const versions = runner.getAllVersions().reverse();\n    for (const version of versions) {\n      const result = await runner.runDown(testDb.pool, version);\n      expect(result.success).toBe(true);\n    }\n  });\n\n  it('should detect dependency ordering issues', async () => {\n    \u002F\u002F Try applying a migration that depends on a table created by a later migration\n    \u002F\u002F This should fail, proving the ordering is enforced\n    const laterMigration = runner.getAllVersions()[5];\n    const freshDb = await createTestDatabase('ordering_test');\n    try {\n      \u002F\u002F Apply only migrations 0-2, then try to apply migration 5\n      for (const v of runner.getAllVersions().slice(0, 3)) {\n        await runner.runUp(freshDb.pool, v);\n      }\n      const result = await runner.runUp(freshDb.pool, laterMigration);\n      \u002F\u002F If it references tables from migrations 3-4, it should fail\n      if (!result.success) {\n        expect(result.error).toMatch(\u002Frelation .* does not exist|table .* doesn't exist\u002Fi);\n      }\n    } finally {\n      await freshDb.teardown();\n    }\n  });\n});\n```\n\n## Configuration\n\n```typescript\n\u002F\u002F migration-test.config.ts\ninterface MigrationTestConfig {\n  database: {\n    adminUrl: string;\n    baseUrl: string;\n    testDbPrefix: string;\n    maxTestDatabases: number;\n    cleanupOrphanedDbs: boolean;\n  };\n  migrations: {\n    directory: string;\n    schemaFile: string;\n    seedFile: string;\n  };\n  performance: {\n    maxMigrationDurationMs: number;\n    largeTableRowCount: number;\n    batchSize: number;\n  };\n  reporting: {\n    generateSchemaSnapshots: boolean;\n    snapshotDirectory: string;\n    reportFormat: 'json' | 'markdown';\n  };\n}\n\nconst defaultConfig: MigrationTestConfig = {\n  database: {\n    adminUrl: process.env.TEST_DATABASE_ADMIN_URL || 'postgresql:\u002F\u002Flocalhost:5432\u002Fpostgres',\n    baseUrl: process.env.TEST_DATABASE_BASE_URL || 'postgresql:\u002F\u002Flocalhost:5432',\n    testDbPrefix: 'migration_test',\n    maxTestDatabases: 10,\n    cleanupOrphanedDbs: true,\n  },\n  migrations: {\n    directory: '.\u002Fdrizzle\u002Fmigrations',\n    schemaFile: '.\u002Fsrc\u002Fdb\u002Fschema.ts',\n    seedFile: '.\u002Fsrc\u002Fdb\u002Fseed.ts',\n  },\n  performance: {\n    maxMigrationDurationMs: 30000,\n    largeTableRowCount: 100000,\n    batchSize: 10000,\n  },\n  reporting: {\n    generateSchemaSnapshots: true,\n    snapshotDirectory: '.\u002Ftest-artifacts\u002Fschema-snapshots',\n    reportFormat: 'json',\n  },\n};\n```\n\n## Best Practices\n\n1. **Create one test database per test suite, not per test** -- Database creation is expensive. Use transactions for isolation within a suite and rollback between tests when possible.\n\n2. **Always test both directions** -- Every migration must have an up test and a down test. Discovering that rollback is broken during an incident is the worst possible time to find out.\n\n3. **Seed realistic data before testing migrations** -- Empty-table migrations always pass. Seed data that includes nulls, unicode, large text fields, maximum-length strings, and edge-case values.\n\n4. **Capture schema snapshots before and after** -- Store a snapshot of columns, constraints, indexes, and triggers. Compare snapshots to detect unintended schema drift.\n\n5. **Test migration idempotency** -- Run the same migration twice. It should either succeed (if designed to be idempotent) or fail with a clear error (not corrupt data).\n\n6. **Verify index performance after migration** -- An index that exists is not the same as an index that performs. Run EXPLAIN ANALYZE on critical queries after migration to verify index usage.\n\n7. **Use the expand-contract pattern for breaking changes** -- Never rename or remove a column in a single step. Expand (add new), migrate data, update application, contract (remove old) across multiple deployments.\n\n8. **Test with production-like constraints enabled** -- Do not disable foreign keys, unique constraints, or check constraints during testing. Migrations must work with all constraints active.\n\n9. **Include concurrent access tests** -- Run SELECT and INSERT queries during migration execution to verify the migration does not cause blocking or deadlocks in a zero-downtime deployment.\n\n10. **Automate migration testing in CI** -- Every pull request that includes a migration file should automatically run the migration test suite against a clean database.\n\n11. **Document irreversible migrations explicitly** -- If a migration cannot be rolled back (dropping a column with data), document this in the migration file and in the test with a clear reason.\n\n12. **Test seed data compatibility** -- After every migration, run the seed script to verify it still works. Broken seed scripts block new developer onboarding and CI environment setup.\n\n## Anti-Patterns to Avoid\n\n1. **Testing migrations on empty databases only** -- An empty database has no data to corrupt, no constraints to violate, and no performance issues. Always seed data before testing migrations.\n\n2. **Sharing test databases between test runs** -- Leftover state from a previous run causes flaky tests. Create a fresh database for every test suite execution and destroy it afterward.\n\n3. **Skipping rollback tests because you will never rollback** -- Production incidents happen. Deployments fail. Rollback capability is insurance, and untested insurance pays nothing.\n\n4. **Using IF EXISTS \u002F IF NOT EXISTS to mask ordering bugs** -- Wrapping every DDL in conditional checks hides dependency ordering problems. Fix the ordering instead of working around it.\n\n5. **Testing only the latest migration in isolation** -- Migrations form a chain. Test the complete chain from empty to current, not just the latest link. A migration that works alone may conflict with a previous one.\n\n6. **Ignoring migration performance** -- A migration that takes 45 minutes on a production-sized table causes 45 minutes of degraded service. Always benchmark with realistic data volumes.\n\n7. **Writing irreversible migrations without documentation** -- If a migration drops data or transforms it one-way, this must be explicitly documented and the down migration should raise a clear error, not silently do nothing.\n\n8. **Hardcoding test data IDs that conflict with production sequences** -- Use UUIDs or explicitly non-overlapping ranges for test data to prevent conflicts if tests accidentally run against production.\n\n## Debugging Tips\n\n1. **Migration fails with \"relation does not exist\"** -- Check migration ordering. The referenced table may be created by a later migration. Verify that your migration runner processes files in the correct order (lexicographic sort of filenames is the standard).\n\n2. **Rollback fails with \"column does not exist\"** -- The down migration references a column that was already removed by a later migration. Test rollbacks in reverse order, starting from the most recent migration.\n\n3. **Data type mismatch after migration** -- Use explicit CAST in data-transforming migrations. Implicit type coercion varies across database versions and may silently truncate data.\n\n4. **Migration succeeds locally but fails in CI** -- Check database versions. A feature available in PostgreSQL 15 may not exist in PostgreSQL 13. Pin your CI database version to match production.\n\n5. **Test database not cleaning up** -- Implement a cleanup script that drops all databases matching your test prefix. Run it as a CI step or a pre-test hook. Orphaned test databases consume disk space and connections.\n\n6. **Constraint violation during migration** -- The migration is trying to add a NOT NULL constraint to a column with existing NULL values, or a UNIQUE constraint on non-unique data. Always backfill data before adding constraints.\n\n7. **Migration takes too long in tests** -- Reduce the seed data volume for routine tests but keep a separate performance test suite with production-scale data. Use the performance suite on a schedule, not on every commit.\n\n8. **Foreign key prevents table drop during rollback** -- Drop foreign key constraints before dropping the referenced table. The rollback migration must remove dependencies in the correct order.\n\n9. **Index creation blocks queries in zero-downtime tests** -- Use CREATE INDEX CONCURRENTLY in PostgreSQL to avoid table locks. Note that this cannot run inside a transaction, so the migration must not be wrapped in BEGIN\u002FCOMMIT.\n\n10. **Seed data breaks after migration** -- Update seed scripts in the same pull request as the migration. Never merge a migration without verifying seed compatibility.",{"name":5,"tags":24,"agents":32,"author":45,"domains":46,"license":15,"version":48,"languages":49,"frameworks":54,"description":7,"testingTypes":58},[25,26,27,28,29,30,31],"database-migration","schema-testing","data-integrity","rollback-testing","zero-downtime","migration-safety","database-versioning",[33,34,35,36,37,38,39,40,41,42,43,44],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","Pramod",[47],"api","1.0.0",[50,51,52,53],"typescript","javascript","python","java",[55,56,57],"jest","vitest","pytest",[59,60],"database","integration","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fdatabase-migration-test-generator","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":70,"prompt":80,"zipAvailable":81},[71,74,77],{"tool":72,"command":73},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Database Migration Test Generator\"",{"tool":75,"command":76},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Database Migration Test Generator\"",{"tool":78,"command":79},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Database Migration Test Generator\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fdatabase-migration-test-generator\u002FSKILL.md",true,[],[84,92,99,106,113,120],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":88,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]