home / skills / htooayelwinict / claude-config / database-change-management

database-change-management skill

/skills/database-change-management

This skill guides safe database schema changes with migrations, backfills, and zero-downtime patterns to protect data integrity.

npx playbooks add skill htooayelwinict/claude-config --skill database-change-management

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
3.1 KB
---
name: database-change-management
description: |
  Plan and implement safe database schema changes including migrations, indexes, and backfills. Use when creating
  tables, adding columns, optimizing queries, or managing Eloquent/SQLAlchemy relationships. EXCLUSIVE to database-admin agent.
allowed-tools: Read, Edit, Bash, Grep, Glob, Write, mcp_context7
---
# Database Change Management

**Exclusive to:** `database-admin` agent

## 📚 Context7 (Memory) — Up-to-Date Docs

Lookup latest ORM patterns before implementing:
```
mcp_context7_resolve-library-id(libraryName="laravel", query="eloquent relationships")
mcp_context7_query-docs(libraryId="/laravel/docs", query="migrations foreign keys")
```

## Validation Loop (MANDATORY)

Every migration MUST pass this verification sequence:
```bash
php artisan migrate        # Run migration
php artisan migrate:rollback   # Verify rollback works
php artisan migrate        # Re-run migration
composer test             # All tests still pass
```

**Do NOT complete until all steps succeed.**

## Instructions

1. Audit existing migrations and models for current schema
2. Design migration with reversible `down()` method
3. Run `migrate` and `rollback` to validate locally
4. Update Eloquent model ($fillable, $casts, relationships)
5. Document any required backfills or deployment order

## Safe Migration Patterns

### Adding Columns
```php
// ✅ Safe: nullable or with default
$table->string('field')->nullable();
$table->boolean('active')->default(true);

// ❌ Unsafe: NOT NULL without default
$table->string('field');
```

### Adding Indexes
```php
// Index for WHERE/ORDER BY columns
$table->index('user_id');
$table->index(['status', 'created_at']);
```

### Zero-Downtime Strategy
1. **Add** — Add nullable column
2. **Backfill** — Populate data in chunks
3. **Enforce** — Make column required

## Backfill Pattern
```php
Model::query()
    ->whereNull('new_field')
    ->chunkById(1000, function ($items) {
        foreach ($items as $item) {
            $item->update(['new_field' => $value]);
        }
    });
```

## Eloquent Relationships

### One-to-Many
```php
// User has many Posts
public function posts(): HasMany
{
    return $this->hasMany(Post::class);
}
```

### Many-to-Many
```php
public function tags(): BelongsToMany
{
    return $this->belongsToMany(Tag::class)
        ->withTimestamps();
}
```

## Query Optimization

### Eager Loading
```php
// ❌ N+1 Problem
foreach (Post::all() as $post) {
    echo $post->user->name;
}

// ✅ Eager Load
Post::with('user')->get();
```

### Index Strategy
| Query Pattern | Index |
|---------------|-------|
| `WHERE user_id = ?` | `index('user_id')` |
| `WHERE status = ? AND date > ?` | `index(['status', 'date'])` |

## Common Pitfalls
- ❌ NOT NULL without default on existing table
- ❌ Dropping columns without backup
- ❌ Missing indexes on foreign keys
- ❌ Missing `down()` method

## Verification
```bash
php artisan migrate
php artisan migrate:rollback
php artisan migrate
```

## Examples
- "Add an index to speed up dashboard query"
- "Add a nullable column then backfill safely"

Overview

This skill helps plan and implement safe database schema changes, migrations, indexes, and backfills. It enforces reversible migrations, local verification, and patterns that avoid downtime and data loss. It is exclusive to the database-admin agent and focuses on concrete, repeatable steps for schema work.

How this skill works

The skill audits existing migrations and models, designs reversible migration scripts with clear up/down methods, and prescribes a local validation loop including migrate and rollback checks. It provides safe patterns for adding columns, creating indexes, performing backfills in chunks, and updating ORM relationships. It also recommends deployment order and documentation needed for production rollouts.

When to use it

  • Creating new tables or adding columns to existing tables
  • Introducing or modifying indexes to optimize queries
  • Designing and running backfills for newly added fields
  • Changing Eloquent/ORM relationships or model casts
  • Preparing schema changes that must be zero-downtime

Best practices

  • Always write reversible migrations with a clear down() implementation
  • Run the mandatory validation loop: migrate, rollback, migrate, then run tests locally
  • Add nullable columns or defaults first, backfill in chunks, then make columns required
  • Use chunked updates for backfills to limit memory and lock contention
  • Add indexes that match WHERE/ORDER BY patterns and include multi-column indexes where needed

Example use cases

  • Add a nullable 'last_seen' column, backfill values in 1k chunks, then alter to NOT NULL
  • Create an index on (status, created_at) to speed up dashboard queries with frequent filters
  • Migrate a one-to-many relationship by adding foreign key column and updating Eloquent relation methods
  • Backfill a boolean 'active' flag, using default true to avoid failing existing writes during rollout
  • Introduce a pivot table for many-to-many relations and update model belongsToMany definitions

FAQ

What verification steps are mandatory before completing a migration?

Run migrate, migrate:rollback, migrate again, and then run the test suite locally; do not complete until all succeed.

How should I backfill large tables safely?

Use chunked queries (e.g., chunkById(1000)), update rows in small batches, and monitor locks and throughput.