Skip to main content
skill CX Codex

database-migration · bobmatnyc — Claude Code skill: what it does, how to install

Guides AI coding assistants through zero-downtime database schema updates. It provides safe multi-phase migration templates and rollback guides.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add bobmatnyc/claude-mpm-skills --skill database-migration -a claude-code
Open on GitHub

What database-migration does

The skill instructs the coding assistant on five core migration rules: backward compatibility, reversibility, staging verification, incremental rollouts, and zero downtime. Direct destructive edits like adding a NOT NULL column to a busy table lock database writes. To prevent service outages, the skill enforces an expand-contract pattern: add a nullable column, write to both fields, backfill existing records, enforce constraints, and drop deprecated columns only after deployment.

It includes production-ready SQL recipes for renaming columns, converting data types, and linking foreign keys. On PostgreSQL, it directs the agent to run CREATE INDEX CONCURRENTLY whenever large tables need indexing. It also provides reference CLI commands for Alembic, Knex, and Rails migrations.

Adding constraints directly on large tables without staged rollouts causes query timeouts and lock contention. In failure scenarios, the guidance outlines targeted recovery paths: fix-forward repair scripts, handling schema drift, and handling partial migration errors.

What it helps with

  • Rename a production column without locking table writes
  • Create database indexes on large datasets using CONCURRENTLY
  • Design multi-phase expand-contract migrations with rollback plans
  • Resolve failed migrations and schema drift across environments

Example prompts for the agent

  • Help me split the full_name column into two fields in PostgreSQL with zero downtime
  • Write an Alembic migration script to add a foreign key constraint to orders
  • What is the safe rollback strategy if our schema backfill fails halfway?

How to install database-migration

1Skills CLI (Vercel)

npx skills add bobmatnyc/claude-mpm-skills --skill database-migration -a claude-code

2Manually: put the files in place

~/.claude/skills/database-migration/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/database-migration/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about database-migration

How to install database-migration in Claude Code?

Run npx skills add bobmatnyc/claude-mpm-skills --skill database-migration -a claude-code. The skill file installs to ~/.claude/skills/database-migration/SKILL.md.

What does the database-migration skill do?

It equips the coding assistant with phased patterns, decision trees, and rollback strategies to modify production schemas without downtime.

How does the skill handle column type changes safely?

It splits the change into phases: add a new column with the target type, sync data from the old column, and drop the legacy column only after new application code is deployed.

Source text

SKILL.md · MIT
---
name: database-migration
description: Safe patterns for evolving database schemas in production with decision trees and troubleshooting guidance.
user-invocable: false
disable-model-invocation: true
updated_at: 2025-12-03T00:00:00Z
tags: [database, migration, schema, production, decision-trees, troubleshooting, zero-downtime]
progressive_disclosure:
  entry_point:
    summary: "Safe patterns for evolving database schemas in production with decision trees and troubleshooting guidance."
    when_to_use: "When working with data, databases, or data transformations."
    quick_start: "1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation."
  references:
    - decision-trees.md
    - troubleshooting.md
---
# Database Migration

Safe patterns for evolving database schemas in production.

## Migration Principles

1. **Backward compatible** - New code works with old schema
2. **Reversible** - Can rollback if needed
3. **Tested** - Verify on staging before production
4. **Incremental** - Small changes, not big-bang
5. **Zero downtime** - No service interruption

## Safe Migration Pattern

### Phase 1: Add New (Compatible)
```sql
-- Add new column (nullable initially)
ALTER TABLE users ADD COLUMN full_name VARCHAR(255) NULL;

-- Deploy new code that writes to both old and new
UPDATE users SET full_name = CONCAT(first_name, ' ', last_name);
```

### Phase 2: Migrate Data
```sql
-- Backfill existing data
UPDATE users
SET full_name = CONCAT(first_name, ' ', last_name)
WHERE full_name IS NULL;
```

### Phase 3: Make Required
```sql
-- Make column required
ALTER TABLE users ALTER COLUMN full_name SET NOT NULL;
```

### Phase 4: Remove Old (After New Code Deployed)
```sql
-- Remove old columns
ALTER TABLE users DROP COLUMN first_name;
ALTER TABLE users DROP COLUMN last_name;
```

## Common Migrations

### Adding Index
```sql
-- Create index concurrently (PostgreSQL)
CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
```

### Renaming Column
```sql
-- Phase 1: Add new column
ALTER TABLE users ADD COLUMN email_address VARCHAR(255);

-- Phase 2: Copy data
UPDATE users SET email_address = email;

-- Phase 3: Drop old column (after deploy)
ALTER TABLE users DROP COLUMN email;
```

### Changing Column Type
```sql
-- Phase 1: Add new column with new type
ALTER TABLE products ADD COLUMN price_cents INTEGER;

-- Phase 2: Migrate data
UPDATE products SET price_cents = CAST(price * 100 AS INTEGER);

-- Phase 3: Drop old column
ALTER TABLE products DROP COLUMN price;
ALTER TABLE products RENAME COLUMN price_cents TO price;
```

### Adding Foreign Key
```sql
-- Add column first
ALTER TABLE orders ADD COLUMN user_id INTEGER NULL;

-- Populate data
UPDATE orders SET user_id = (
    SELECT id FROM users WHERE users.email = orders.user_email
);

-- Add foreign key
ALTER TABLE orders
ADD CONSTRAINT fk_orders_users
FOREIGN KEY (user_id) REFERENCES users(id);
```

## Migration Tools

### Python (Alembic)
```python
# Generate migration
alembic revision --autogenerate -m "add user full_name"

# Apply migration
alembic upgrade head

# Rollback
alembic downgrade -1
```

### JavaScript (Knex)
```javascript
// Create migration
knex migrate:make add_full_name

// Apply migrations
knex migrate:latest

// Rollback
knex migrate:rollback
```

### Rails
```ruby
# Generate migration
rails generate migration AddFullNameToUsers full_name:string

# Run migrations
rails db:migrate

# Rollback
rails db:rollback
```

## Testing Migrations

```python
def test_migration_forward_backward():
    # Apply migration
    apply_migration("add_full_name")

    # Verify schema
    assert column_exists("users", "full_name")

    # Rollback
    rollback_migration()

    # Verify rollback
    assert not column_exists("users", "full_name")
```

## Dangerous Operations

### ❌ Avoid in Production
```sql
-- Locks table for long time
ALTER TABLE users ADD COLUMN email VARCHAR(255) NOT NULL;

-- Can't rollback
DROP TABLE old_users;

-- Breaks existing code immediately
ALTER TABLE users DROP COLUMN email;
```

### ✅ Safe Alternatives
```sql
-- Add as nullable first
ALTER TABLE users ADD COLUMN email VARCHAR(255) NULL;

-- Rename instead of drop
ALTER TABLE old_users RENAME TO archived_users;

-- Keep old column until new code deployed
-- (multi-phase approach)
```

## Rollback Strategy

```sql
-- Every migration needs DOWN
-- UP
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);

-- DOWN
ALTER TABLE users DROP COLUMN full_name;
```

## Decision Support

### Quick Decision Guide

**Making a schema change?**
- Breaking change (drops/modifies data) → Multi-phase migration (expand-contract)
- Additive change (new columns/tables) → Single-phase migration
- Large table (millions of rows) → Use CONCURRENTLY for indexes

**Need zero downtime?**
- Schema change → Expand-contract pattern (5 phases)
- Data migration (< 10k rows) → Synchronous in-migration
- Data migration (> 1M rows) → Background worker pattern

**Planning rollback?**
- Added new schema only → Simple DOWN migration
- Modified/removed schema → Multi-phase rollback or fix forward
- Cannot lose data → Point-in-time recovery (PITR)

**Choosing migration tool?**
- Python/Django → Django Migrations
- Python/SQLAlchemy → Alembic
- Node.js/TypeScript → Prisma Migrate or Knex.js
- Enterprise/multi-language → Flyway or Liquibase

**→ See [references/decision-trees.md](./references/decision-trees.md) for comprehensive decision frameworks**

## Troubleshooting

### Common Issues Quick Reference

**Migration failed halfway** → Check database state, fix forward with repair migration

**Schema drift detected** → Use autogenerate to create reconciliation migration

**Cannot rollback (no downgrade)** → Create reverse migration or fix forward

**Foreign key violation** → Clean data before adding constraint, or add as NOT VALID

**Migration locks table too long** → Use CONCURRENTLY, add columns in phases, batch updates

**Circular dependency** → Create merge migration or reorder dependencies

**→ See [references/troubleshooting.md](./references/troubleshooting.md) for detailed solutions with examples**

## Navigation

### Detailed References

- **[🌳 Decision Trees](./references/decision-trees.md)** - Schema migration strategies, zero-downtime patterns, rollback strategies, migration tool selection, and data migration approaches. Load when planning migrations or choosing strategies.

- **[🔧 Troubleshooting](./references/troubleshooting.md)** - Failed migration recovery, schema drift detection, migration conflicts, rollback failures, data integrity issues, and performance problems. Load when debugging migration issues.

## Remember
- Test migrations on copy of production data
- Have rollback plan ready
- Monitor during deployment
- Communicate with team about schema changes
- Keep migrations small and focused

© bobmatnyc · MIT · bobmatnyc/claude-mpm-skills

Similar skills

All skills for Data and databases →

database-migration by other authors comes first.

From the same set97

golang-cli-cobra-viper A skill for building Go command-line tools: command structure with Cobra and configuration from flags, environment variables and files with Viper. CX Codex +1 425installs dependency-audit A skill that walks through dependency cleanup: outdated packages, security vulnerabilities and libraries nothing imports anymore. CX Codex +1 422installs wordpress-plugin-fundamentals A skill for building WordPress plugins on PHP 8.3+ with OOP, hooks, database access and the Settings API. Useful when the agent has to scaffold a plugin instead of guessing at structure. CX Codex +1 421installs digitalocean-compute Tells your agent which DigitalOcean compute to use for a job: Droplets, App Platform, Functions, DOKS or GPUs. Handy when you are deciding where an app or container should run. CX Codex +1 416installs wordpress-testing-qa A skill for testing WordPress plugins and themes: PHPUnit integration, WP_Mock, PHPCS and CI/CD. Useful when your test setup needs structure. CX Codex +1 413installs hono-testing A skill that shows how to test Hono apps: build a Request, hand it to the app, check the Response. Covers the typed test client and Workers bindings too. CX Codex +1 411installs golang-observability-opentelemetry A skill for instrumenting Go services: OpenTelemetry for distributed tracing, Prometheus for metrics, slog for structured logging. CX Codex +1 409installs digitalocean-overview This skill maps DigitalOcean accounts, projects, services, and tooling so you can plan a setup through the Control Panel, doctl, REST API, or Terraform. CX Codex +1 408installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor