Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Database migration best practices for schema changes, data migrations, rollbacks, and zero-downtime deployments across PostgreSQL, MySQL, and common ORMs (Prisma, Drizzle, Kysely, Django, TypeORM, golang-migrate).
.claude/skills/loulanyue-database-migrations/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-05 | ✗→✓ | ▲ Improved | 111% | 0% |
| case-03 | ✓→✓ | = Same ✓ | 89% | 0% |
| case-01 | ✓→✓ | = Same ✓ | 149% | 0% |
| case-02 | ✓→✓ | = Same ✓ | 494% | 0% |
| case-04 | ✓→✓ | = Same ✓ | 37% | 0% |
Safe, reversible database schema changes for production systems.
Before applying any migration:
sql-- GOOD: Nullable column, no lock ALTER TABLE users ADD COLUMN avatar_url TEXT; -- GOOD: Column with default (Postgres 11+ is instant, no rewrite) ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true; -- BAD: NOT NULL without default on existing table (requires full rewrite) ALTER TABLE users ADD COLUMN role TEXT NOT NULL; -- This locks the table and rewrites every row
sql-- BAD: Blocks writes on large tables CREATE INDEX idx_users_email ON users (email); -- GOOD: Non-blocking, allows concurrent writes CREATE INDEX CONCURRENTLY idx_users_email ON users (email); -- Note: CONCURRENTLY cannot run inside a transaction block -- Most migration tools need special handling for this
Never rename directly in production. Use the expand-contract pattern:
sql-- Step 1: Add new column (migration 001) ALTER TABLE users ADD COLUMN display_name TEXT; -- Step 2: Backfill data (migration 002, data migration) UPDATE users SET display_name = username WHERE display_name IS NULL; -- Step 3: Update application code to read/write both columns -- Deploy application changes -- Step 4: Stop writing to old column, drop it (migration 003) ALTER TABLE users DROP COLUMN username;
sql-- Step 1: Remove all application references to the column -- Step 2: Deploy application without the column reference -- Step 3: Drop column in next migration ALTER TABLE orders DROP COLUMN legacy_status; -- For Django: use SeparateDatabaseAndState to remove from model -- without generating DROP COLUMN (then drop in next migration)
sql-- BAD: Updates all rows in one transaction (locks table) UPDATE users SET normalized_email = LOWER(email); -- GOOD: Batch update with progress DO $$ DECLARE batch_size INT := 10000; rows_updated INT; BEGIN LOOP UPDATE users SET normalized_email = LOWER(email) WHERE id IN ( SELECT id FROM users WHERE normalized_email IS NULL LIMIT batch_size FOR UPDATE SKIP LOCKED ); GET DIAGNOSTICS rows_updated = ROW_COUNT; RAISE NOTICE 'Updated % rows', rows_updated; EXIT WHEN rows_updated = 0; COMMIT; END LOOP; END $$;
bash# Create migration from schema changes npx prisma migrate dev --name add_user_avatar # Apply pending migrations in production npx prisma migrate deploy # Reset database (dev only) npx prisma migrate reset # Generate client after schema changes npx prisma generate
prismamodel User { id String @id @default(cuid()) email String @unique name String? avatarUrl String? @map("avatar_url") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") orders Order[] @@map("users") @@index([email]) }
For operations Prisma cannot express (concurrent indexes, data backfills):
bash# Create empty migration, then edit the SQL manually npx prisma migrate dev --create-only --name add_email_index
sql-- migrations/20240115_add_email_index/migration.sql -- Prisma cannot generate CONCURRENTLY, so we write it manually CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users (email);
bash# Generate migration from schema changes npx drizzle-kit generate # Apply migrations npx drizzle-kit migrate # Push schema directly (dev only, no migration file) npx drizzle-kit push
typescriptimport { pgTable, text, timestamp, uuid, boolean } from "drizzle-orm/pg-core"; export const users = pgTable("users", { id: uuid("id").primaryKey().defaultRandom(), email: text("email").notNull().unique(), name: text("name"), isActive: boolean("is_active").notNull().default(true), createdAt: timestamp("created_at").notNull().defaultNow(), updatedAt: timestamp("updated_at").notNull().defaultNow(), });
bash# Initialize config file (kysely.config.ts) kysely init # Create a new migration file kysely migrate make add_user_avatar # Apply all pending migrations kysely migrate latest # Rollback last migration kysely migrate down # Show migration status kysely migrate list
typescript// migrations/2024_01_15_001_create_user_profile.ts import { type Kysely, sql } from 'kysely' // IMPORTANT: Always use Kysely<any>, not your typed DB interface. // Migrations are frozen in time and must not depend on current schema types. export async function up(db: Kysely<any>): Promise<void> { await db.schema .createTable('user_profile') .addColumn('id', 'serial', (col) => col.primaryKey()) .addColumn('email', 'varchar(255)', (col) => col.notNull().unique()) .addColumn('avatar_url', 'text') .addColumn('created_at', 'timestamp', (col) => col.defaultTo(sql`now()`).notNull() ) .execute() await db.schema .createIndex('idx_user_profile_avatar') .on('user_profile') .column('avatar_url') .execute() } export async function down(db: Kysely<any>): Promise<void> { await db.schema.dropTable('user_profile').execute() }
typescriptimport { Migrator, FileMigrationProvider } from 'kysely' import { promises as fs } from 'fs' import * as path from 'path' // ESM only — CJS can use __dirname directly import { fileURLToPath } from 'url' const migrationFolder = path.join( path.dirname(fileURLToPath(import.meta.url)), './migrations', ) // `db` is your Kysely<any> database instance const migrator = new Migrator({ db, provider: new FileMigrationProvider({ fs, path, migrationFolder, }), // WARNING: Only enable in development. Disables timestamp-ordering // validation, which can cause schema drift between environments. // allowUnorderedMigrations: true, }) const { error, results } = await migrator.migrateToLatest() results?.forEach((it) => { if (it.status === 'Success') { console.log(`migration "${it.migrationName}" executed successfully`) } else if (it.status === 'Error') { console.error(`failed to execute migration "${it.migrationName}"`) } }) if (error) { console.error('migration failed', error) process.exit(1) }
bash# Generate migration from model changes python manage.py makemigrations # Apply migrations python manage.py migrate # Show migration status python manage.py showmigrations # Generate empty migration for custom SQL python manage.py makemigrations --empty app_name -n description
pythonfrom django.db import migrations def backfill_display_names(apps, schema_editor): User = apps.get_model("accounts", "User") batch_size = 5000 users = User.objects.filter(display_name="") while users.exists(): batch = list(users[:batch_size]) for user in batch: user.display_name = user.username User.objects.bulk_update(batch, ["display_name"], batch_size=batch_size) def reverse_backfill(apps, schema_editor): pass # Data migration, no reverse needed class Migration(migrations.Migration): dependencies = [("accounts", "0015_add_display_name")] operations = [ migrations.RunPython(backfill_display_names, reverse_backfill), ]
Remove a column from the Django model without dropping it from the database immediately:
pythonclass Migration(migrations.Migration): operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField(model_name="user", name="legacy_field"), ], database_operations=[], # Don't touch the DB yet ), ]
bash# Create migration pair migrate create -ext sql -dir migrations -seq add_user_avatar # Apply all pending migrations migrate -path migrations -database "$DATABASE_URL" up # Rollback last migration migrate -path migrations -database "$DATABASE_URL" down 1 # Force version (fix dirty state) migrate -path migrations -database "$DATABASE_URL" force VERSION
sql-- migrations/000003_add_user_avatar.up.sql ALTER TABLE users ADD COLUMN avatar_url TEXT; CREATE INDEX CONCURRENTLY idx_users_avatar ON users (avatar_url) WHERE avatar_url IS NOT NULL; -- migrations/000003_add_user_avatar.down.sql DROP INDEX IF EXISTS idx_users_avatar; ALTER TABLE users DROP COLUMN IF EXISTS avatar_url;
For critical production changes, follow the expand-contract pattern:
Phase 1: EXPAND
- Add new column/table (nullable or with default)
- Deploy: app writes to BOTH old and new
- Backfill existing data
Phase 2: MIGRATE
- Deploy: app reads from NEW, writes to BOTH
- Verify data consistency
Phase 3: CONTRACT
- Deploy: app only uses NEW
- Drop old column/table in separate migrationDay 1: Migration adds new_status column (nullable)
Day 1: Deploy app v2 — writes to both status and new_status
Day 2: Run backfill migration for existing rows
Day 3: Deploy app v3 — reads from new_status only
Day 7: Migration drops old status column| Anti-Pattern | Why It Fails | Better Approach | |-------------|-------------|-----------------| | Manual SQL in production | No audit trail, unrepeatable | Always use migration files | | Editing deployed migrations | Causes drift between environments | Create new migration instead | | NOT NULL without default | Locks table, rewrites all rows | Add nullable, backfill, then add constraint | | Inline index on large table | Blocks writes during build | CREATE INDEX CONCURRENTLY | | Schema + data in one migration | Hard to rollback, long transactions | Separate migrations | | Dropping column before removing code | Application errors on missing column | Remove code first, drop column next deploy |
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-03 | pass→pass | 14,716 | 10,168 | -31% | 1 | 1 | 0% | 2,687 | 5,087 | +89% | 0 | 0 | — |
case-01 | pass→pass | 13,929 | 13,164 | -5% | 1 | 1 | 0% | 2,217 | 5,517 | +149% | 0 | 0 | — |
case-02 | pass→pass | 3,804 | 4,611 | +21% | 1 | 1 | 0% | 606 | 3,601 | +494% | 0 | 0 | — |
case-04 | pass→pass | 20,101 | 11,635 | -42% | 1 | 1 | 0% | 3,752 | 5,148 | +37% | 0 | 0 | — |
case-05 | fail→pass | 14,334 | 10,969 | -23% | 1 | 1 | 0% | 2,383 | 5,029 | +111% | 0 | 0 | — |
case-06 | pass→pass | 13,485 | 8,015 | -41% | 1 | 1 | 0% | 2,291 | 4,323 | +89% | 0 | 0 | — |
case-07 | pass→pass | 9,403 | 10,638 | +13% | 1 | 1 | 0% | 1,815 | 5,016 | +176% | 0 | 0 | — |
case-08 | pass→pass | 6,605 | 4,341 | -34% | 1 | 1 | 0% | 1,227 | 3,931 | +220% | 0 | 0 | — |
case-13 | pass→pass | 12,256 | 6,361 | -48% | 1 | 1 | 0% | 2,138 | 4,295 | +101% | 0 | 0 | — |
case-09 | pass→pass | 9,121 | 8,593 | -6% | 1 | 1 | 0% | 1,758 | 4,704 | +168% | 0 | 0 | — |
case-10 | pass→pass | 5,286 | 4,288 | -19% | 1 | 1 | 0% | 1,001 | 3,866 | +286% | 0 | 0 | — |
case-11 | pass→pass | 6,247 | 4,328 | -31% | 1 | 1 | 0% | 1,187 | 3,940 | +232% | 0 | 0 | — |
case-12 | pass→pass | 7,278 | 4,804 | -34% | 1 | 1 | 0% | 1,208 | 3,917 | +224% | 0 | 0 | — |
case-14 | pass→pass | 7,334 | 4,737 | -35% | 1 | 1 | 0% | 1,310 | 3,881 | +196% | 0 | 0 | — |
case-15 | pass→pass | 10,014 | 8,185 | -18% | 1 | 1 | 0% | 1,648 | 4,401 | +167% | 0 | 0 | — |
case-16 | pass→pass | 5,145 | 2,166 | -58% | 1 | 1 | 0% | 850 | 3,346 | +294% | 0 | 0 | — |
case-17 | pass→pass | 14,847 | 10,502 | -29% | 1 | 1 | 0% | 2,549 | 4,801 | +88% | 0 | 0 | — |
case-18 | pass→pass | 11,528 | 6,044 | -48% | 1 | 1 | 0% | 1,863 | 4,024 | +116% | 0 | 0 | — |
case-19 | pass→pass | 8,928 | 5,725 | -36% | 1 | 1 | 0% | 1,528 | 3,955 | +159% | 0 | 0 | — |
case-20 | pass→pass | 10,872 | 10,346 | -5% | 1 | 1 | 0% | 2,160 | 5,067 | +135% | 0 | 0 | — |
case-21 | pass→pass | 15,885 | 9,940 | -37% | 1 | 1 | 0% | 3,019 | 4,991 | +65% | 0 | 0 | — |
case-22 | pass→pass | 13,567 | 10,818 | -20% | 1 | 1 | 0% | 2,726 | 5,263 | +93% | 0 | 0 | — |
case-23 | pass→pass | 7,971 | 6,360 | -20% | 1 | 1 | 0% | 1,686 | 4,297 | +155% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +4 percentage points is the difference between those two pass rates over the 23 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.