← 返回列表
全部 Skill›数据库 Databases›database-migrations

database-migrations

作者 @affaan-m · 语言 en
Database migration best practices for schema changes, data migrations, rollbacks, and zero-downtime deployments across PostgreSQL, MySQL, and common ORMs (Prisma, Drizzle, Django, TypeORM, golang-migrate). Use when planning or implementing database schema changes.
数据库 DatabasesSQL 数据库通用执行命令访问网络待翻译
存储库
最近源活动
2026-11-20 09:13
检测 SKILL.md 语言
en
星标 ★
309,846
分支 Fork
45,351
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

Database Migration Patterns

Safe, reversible database schema changes for production systems.

When to Activate

  • Creating or altering database tables
  • Adding/removing columns or indexes
  • Running data migrations (backfill, transform)
  • Planning zero-downtime schema changes
  • Setting up migration tooling for a new project

Core Principles

  1. Every change is a migration — never alter production databases manually
  2. Migrations are forward-only in production — rollbacks use new forward migrations
  3. Schema and data migrations are separate — never mix DDL and DML in one migration
  4. Test migrations against production-sized data — a migration that works on 100 rows may lock on 10M
  5. Migrations are immutable once deployed — never edit a migration that has run in production

Migration Safety Checklist

Before applying any migration:

  • [ ] Migration has both UP and DOWN (or is explicitly marked irreversible)
  • [ ] No full table locks on large tables (use concurrent operations)
  • [ ] New columns have defaults or are nullable (never add NOT NULL without default)
  • [ ] Indexes created concurrently (not inline with CREATE TABLE for existing tables)
  • [ ] Data backfill is a separate migration from schema change
  • [ ] Tested against a copy of production data
  • [ ] Rollback plan documented

PostgreSQL Patterns

Adding a Column Safely

-- Nullable column: no table rewrite, but takes ACCESS EXCLUSIVE lock
ALTER TABLE users ADD COLUMN avatar_url TEXT;

-- PostgreSQL 11+: a non-volatile default avoids a table rewrite
-- Still takes ACCESS EXCLUSIVE lock and may wait for other transactions
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;

-- BAD on a populated table: existing rows would have NULL in the new column
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
-- Fails with not_null_violation (SQLSTATE 23502); does not backfill existing rows

Avoiding a table rewrite does not mean avoiding locks. These ADD COLUMN

operations take an ACCESS EXCLUSIVE lock, held until the transaction ends.

Keep the transaction short and use an appropriate lock_timeout to bound lock

acquisition waits. A volatile default such as clock_timestamp() requires a

table rewrite; the PostgreSQL 11+ fast path applies to non-volatile defaults.

Adding a NOT NULL column without a default can succeed on an empty table.

Run the self-checking reproduction SQL on

PostgreSQL 11+:

psql -X -v ON_ERROR_STOP=1 -f examples/postgres-add-column.sql

It uses a temporary table, rolls back the ALTERs, and drops the fixture, checking

lock acquisition, rewrites, and the expected constraint violation.

Reference: PostgreSQL ALTER TABLE.

Adding an Index Without Downtime

-- 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

Renaming a Column (Zero-Downtime)

For a pure rename (both columns represent the same value), use expand-contract.

Keep username authoritative until the read cutover:

-- Step 1: Expand (migration 001)
ALTER TABLE users ADD COLUMN display_name TEXT;

-- Step 2: Deploy app v2: read username, write BOTH columns atomically.
-- Cover every INSERT/UPDATE path, including jobs, imports, and admin tools.
-- Drain old-only writers and their in-flight transactions before backfilling.

-- Step 3: Backfill in bounded primary-key ranges (separate data migration).
-- Example range; advance bounds to cover every existing id.
BEGIN;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET LOCAL lock_timeout = '2s';
UPDATE users SET display_name = username
WHERE id > 0 AND id <= 10000
  AND display_name IS DISTINCT FROM username;
COMMIT;

-- Step 4: Validate AFTER all ranges complete, while dual writes continue.
-- Require zero mismatches before switching reads.
SELECT count(*) AS mismatched_rows FROM users
WHERE display_name IS DISTINCT FROM username;

-- Step 5: Deploy app v3: read display_name, still write BOTH columns.
-- Keep dual writes throughout the rollback window.

-- Step 6: After the rollback window, stop backfill/reconciliation workers.
-- Transfer required constraints/indexes/dependencies to the new column.
-- Make old-column constraints compatible with new-only INSERTs/UPDATEs.
-- Drain non-app readers of username and their in-flight transactions first.
-- Then deploy app v4 using ONLY display_name; drain remaining old-column users.

-- Step 7: Contract in a separate migration after checking dependencies.
ALTER TABLE users DROP COLUMN username;

Commit each range independently; checkpoint only after commit and retry failed

batch transactions. Choose bounds for the actual key space (including zero or

negative IDs if present). IS DISTINCT FROM repairs stale non-NULL values and

handles NULL pairs without repeatedly updating them. Do not fetch username

into application memory and later write that stale snapshot: copy the target

row's current value in the same UPDATE. At Read Committed, concurrent updates

serialize on the row and PostgreSQL rechecks the predicate after waiting.

Deploying dual writes does not repair earlier drift by itself. Finish draining

old-only writers before backfill, and validate parity before read cutover. Once

new-only writes start, the old column may be stale: do not restart this backfill

or roll b

评论
Aaffaan-m
affaan-m
affaan-m/ECC
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@affaan-m
所属大类数据库 Databases / SQL 数据库
国内可用性通用
最近源活动2026-11-20 09:13
风险提示执行命令、访问网络
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。