Agent skill

Database Migrations

by affaan-m in affaan-m/ECC

数据库迁移最佳实践,涵盖模式变更、数据迁移、回滚以及零停机部署,适用于PostgreSQL、MySQL及常用ORM(Prisma、Drizzle、Django、TypeORM、golang-migrate)。

MITAuto-check passedDatabases

Install Database Migrations

skills CLI
$ npx skills add affaan-m/ECC --skill database-migrations -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install affaan-m/ECC database-migrations --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/affaan-m/ECC.git skills-src && mkdir -p .claude/skills && cp -r skills-src/docs/zh-CN/skills/database-migrations .claude/skills/database-migrations && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
database-migrations
GitHub stars
276k
Used in
3 other repos
Token cost
~1.9k tokens
SKILL.md length
113 words
Files
1
Skills in repo
673
Repo updated
First seen
Licence
MIT

At a glance

数据库迁移最佳实践,涵盖模式变更、数据迁移、回滚以及零停机部署,适用于PostgreSQL、MySQL及常用ORM(Prisma、Drizzle、Django、TypeORM、golang-migrate)。

  • Works in 5 steps: 每个变更都是一次迁移 — 切勿手动更改生产数据库 → 迁移在生产环境中是只进不退的 — 回滚使用新的前向迁移 → 模式迁移和数据迁移是分开的 — 切勿在一个迁移中混合 DDL 和 DML → …
  • Tasks that involve ORMs and data access
  • SKILL.md covers 何时激活, 核心原则, 迁移安全检查清单 and PostgreSQL 模式, plus 6 more sections
  • Calls npx and python

What it does

Database Migrations is an agent skill from affaan-m/ECC. 数据库迁移最佳实践,涵盖模式变更、数据迁移、回滚以及零停机部署,适用于PostgreSQL、MySQL及常用ORM(Prisma、Drizzle、Django、TypeORM、golang-migrate)。

Its SKILL.md is about 1.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Databases, covering ORMs and data access, Backend development and Database migrations. It works with Django, Prisma, PostgreSQL and Go. The repository describes itself as: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. The licence is MIT.

When your agent uses it

  • Tasks that involve ORMs and data access
  • Tasks that involve Backend development
  • Tasks that involve Database migrations

Example prompts

  • “/database-migrations”

Requirements

  • Python 3
  • Node.js

Workflow steps

5 steps, taken from the first numbered list in SKILL.md.

  1. 每个变更都是一次迁移 — 切勿手动更改生产数据库
  2. 迁移在生产环境中是只进不退的 — 回滚使用新的前向迁移
  3. 模式迁移和数据迁移是分开的 — 切勿在一个迁移中混合 DDL 和 DML
  4. 针对生产规模的数据测试迁移 — 适用于 100 行的迁移可能在 1000 万行时锁定
  5. 迁移一旦部署就是不可变的 — 切勿编辑已在生产中运行的迁移

What it can do on your machine

Read from SKILL.md and the folder at commit ef648e0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • npx
    • python

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use npx, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Database Migrations loads about 1.9k tokens when it runs. Until then it costs about 31 tokens; SKILL.md has 113 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~31
When it runs · the whole SKILL.md, loaded when a task matches
~1.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from affaan-m/ECC at commit ef648e0, republished under its MIT licence (© affaan-m). 113 words, ~1,889 tokens.

Download SKILL.mdSave it as .claude/skills/database-migrations/SKILL.md (or your agent's skills folder).
name
database-migrations
description
数据库迁移最佳实践,涵盖模式变更、数据迁移、回滚以及零停机部署,适用于PostgreSQL、MySQL及常用ORM(Prisma、Drizzle、Django、TypeORM、golang-migrate)。
origin
ECC

数据库迁移模式

为生产系统提供安全、可逆的数据库模式变更。

何时激活

  • 创建或修改数据库表
  • 添加/删除列或索引
  • 运行数据迁移(回填、转换)
  • 计划零停机模式变更
  • 为新项目设置迁移工具

核心原则

  1. 每个变更都是一次迁移 — 切勿手动更改生产数据库
  2. 迁移在生产环境中是只进不退的 — 回滚使用新的前向迁移
  3. 模式迁移和数据迁移是分开的 — 切勿在一个迁移中混合 DDL 和 DML
  4. 针对生产规模的数据测试迁移 — 适用于 100 行的迁移可能在 1000 万行时锁定
  5. 迁移一旦部署就是不可变的 — 切勿编辑已在生产中运行的迁移

迁移安全检查清单

应用任何迁移之前:

  • [ ] 迁移同时包含 UP 和 DOWN(或明确标记为不可逆)
  • [ ] 对大表没有全表锁(使用并发操作)
  • [ ] 新列有默认值或可为空(切勿添加没有默认值的 NOT NULL)
  • [ ] 索引是并发创建的(对于现有表,不与 CREATE TABLE 内联创建)
  • [ ] 数据回填是与模式变更分开的迁移
  • [ ] 已针对生产数据副本进行测试
  • [ ] 回滚计划已记录

PostgreSQL 模式

安全地添加列
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
重命名列(零停机)

切勿在生产中直接重命名。使用扩展-收缩模式:

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

Prisma (TypeScript/Node.js)

工作流
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
模式示例
prisma
model 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])
}
自定义 SQL 迁移

对于 Prisma 无法表达的操作(并发索引、数据回填):

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

Drizzle (TypeScript/Node.js)

工作流
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
模式示例
typescript
import { 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(),
});

Django (Python)

工作流
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
数据迁移
python
from 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),
    ]
SeparateDatabaseAndState

从 Django 模型中删除列,而不立即从数据库中删除:

python
class Migration(migrations.Migration):
    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.RemoveField(model_name="user", name="legacy_field"),
            ],
            database_operations=[],  # Don't touch the DB yet
        ),
    ]

golang-migrate (Go)

工作流
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;

零停机迁移策略

对于关键的生产变更,遵循扩展-收缩模式:

Phase 1: EXPAND
  - 添加新列/表(可为空或带有默认值)
  - 部署:应用同时写入旧数据和新数据
  - 回填现有数据

Phase 2: MIGRATE
  - 部署:应用读取新数据,同时写入新旧数据
  - 验证数据一致性

Phase 3: CONTRACT
  - 部署:应用仅使用新数据
  - 在单独迁移中删除旧列/表
时间线示例
Day 1:迁移添加新的 `new_status` 列(可空)
Day 1:部署应用 v2 —— 同时写入 `status` 和 `new_status`
Day 2:运行针对现有行的回填迁移
Day 3:部署应用 v3 —— 仅从 `new_status` 读取
Day 7:迁移删除旧的 `status` 列

反模式

反模式为何会失败更好的方法
在生产中手动执行 SQL没有审计追踪,不可重复始终使用迁移文件
编辑已部署的迁移导致环境间出现差异改为创建新迁移
没有默认值的 NOT NULL锁定表,重写所有行添加可为空列,回填数据,然后添加约束
在大表上内联创建索引在构建期间阻塞写入使用 CREATE INDEX CONCURRENTLY
在一个迁移中混合模式和数据的变更难以回滚,事务时间长分开的迁移
在移除代码之前删除列应用程序在缺失列时出错先移除代码,下一次部署再删除列

© affaan-m, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in docs/zh-CN/skills/database-migrations of affaan-m/ECC.

Open the folder on GitHubat commit ef648e0

Used in 3 other repositories

We found 3 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 3 other GitHub owners. This page covers the copy in affaan-m/ECC, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Database Migrations next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Database Migrations compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Database Migrations this skillaffaan-m/ECC276k3 repos~1.9kAutomated safety check: PassMIT
Database Migrationsxu-xiang/everything-claude-code-zh2k—~1.7kAutomated safety check: PassMIT
Database Expertcin12211/orca-q224—~2.8kAutomated safety check: PassMIT
DB Review312362115/claude107—~1.8kAutomated safety check: PassMIT
SQL Database Assistantalirezarezvani/claude-skills28k—~4kAutomated safety check: PassMIT
Dsqlawslabs/agent-plugins915—~6.9kAutomated safety check: PassApache-2.0

Similar skills

  • Database Migrations

    xu-xiang/everything-claude-code-zh

    跨 PostgreSQL、MySQL 及常用 ORM(Prisma、Drizzle、Django、TypeORM、golang-migrate)的模式变更(schema changes)、数据迁移、回滚及零停机部署(zero-downtime deployments)的数据库迁移最佳实践。

    2k GitHub stars~1.7k tokensUpdated 7 mo ago
    DatabasesAuto-check passed
  • Database Expert

    cin12211/orca-q

    Database performance optimization, schema design, query analysis, and connection management across PostgreSQL, MySQL, MongoDB, and SQLite with ORM integration.

    224 GitHub stars~2.8k tokensUpdated 18 days ago
    DatabasesAuto-check passed
  • DB Review

    312362115/claude

    数据库代码审查 + Migration 安全检查. An agent skill from 312362115/claude.

    107 GitHub stars~1.8k tokensUpdated 4 mo ago
    DatabasesAuto-check passed
  • SQL Database Assistant

    alirezarezvani/claude-skills

    A skill your agent uses when the user asks to write SQL queries, optimize database performance, generate migrations, explore database schemas, or work with ORMs like Prisma, Drizzle, TypeORM, or…

    28k GitHub stars~4k tokensUpdated 1 mo ago
    DatabasesAuto-check passed
  • Dsql

    awslabs/agent-plugins

    Official

    Build with Aurora DSQL — manage schemas, execute queries, handle migrations, diagnose query plans, diagnose cluster performance, load data, and develop applications with a serverless, distributed…

    915 GitHub stars~6.9k tokensUpdated yesterday
    DatabasesAuto-check passed
  • DB Migrator

    laolaoshiren/claude-code-skills-zh

    数据库迁移助手 - Schema 对比、迁移脚本生成

    879 GitHub stars~677 tokensUpdated 4 days ago
    DatabasesAuto-check passed

More from affaan-m/ECC

All 673 skills in this repo
  • Skill Stocktake

    affaan-m/ECC

    Audits your installed Claude skills and commands for quality, with a quick mode for recently changed skills and a full mode that evaluates all of them through subagents.

    276k GitHub starsUsed in 5 repos~1.9k tokens
    Auto-check passed
  • Ingests, indexes, searches, edits and monitors video, audio and live streams through the VideoDB Python SDK, returning stream links, clips and timestamps.

    276k GitHub starsUsed in 3 repos~3.5k tokens
    Auto-check: notes
  • Rules Distillation

    affaan-m/ECC

    Scans installed skills for principles that recur across them and proposes rule-file changes: append, revise, add a section, create a file or leave as covered.

    276k GitHub starsUsed in 2 repos~2.3k tokens
    Auto-check passed
  • Builds DRAFT counterparty agreements from one markdown template and a small JSON spec per party, with clauses picked by the party's role.

    276k GitHub stars~2.9k tokensUpdated 5 days ago
    Auto-check passed
  • Measures whether agents actually follow a skill, rule or agent definition by generating scenarios at three strictness levels and scoring tool-call traces.

    276k GitHub starsUsed in 1 repo~623 tokens
    Auto-check passed
  • Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    276k GitHub stars~3.5k tokensUpdated 5 days ago
    Auto-check passed

Categories

Questions about Database Migrations

What does Database Migrations do?

数据库迁移最佳实践,涵盖模式变更、数据迁移、回滚以及零停机部署,适用于PostgreSQL、MySQL及常用ORM(Prisma、Drizzle、Django、TypeORM、golang-migrate)。. Database Migrations is an agent skill from affaan-m/ECC.

When should I use Database Migrations?

Database Migrations fits situations like: tasks that involve ORMs and data access; tasks that involve Backend development; tasks that involve Database migrations.

How do I install Database Migrations in Claude Code?

Run `npx skills add affaan-m/ECC --skill database-migrations -a claude-code`. Or copy the skill folder (docs/zh-CN/skills/database-migrations in affaan-m/ECC) into .claude/skills/database-migrations in your project. Claude Code loads it when a task matches its description.

How do I install Database Migrations in Codex?

Run `npx skills add affaan-m/ECC --skill database-migrations -a codex`. Or copy the skill folder (docs/zh-CN/skills/database-migrations in affaan-m/ECC) into .agents/skills/database-migrations in your project. Codex loads it when a task matches its description.

Can I use Database Migrations in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add affaan-m/ECC --skill database-migrations -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/database-migrations, .gemini/skills/database-migrations, .github/skills/database-migrations and .opencode/skills/database-migrations in your project.

What does Database Migrations need to run?

Going by SKILL.md and its folder, Database Migrations needs the command-line tools its instructions call (npx and python). Our summary lists: Python 3; Node.js.

Does Database Migrations access the network?

SKILL.md contains no URLs. Its commands use npx, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Database Migrations safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Database Migrations use?

Database Migrations is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Database Migrations use?

About 1.9k tokens (SKILL.md is roughly 7.6k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Database Migrations?

Skills that share tags, products or a category with Database Migrations: Database Migrations (xu-xiang/everything-claude-code-zh, 2k stars), Database Expert (cin12211/orca-q, 224 stars), DB Review (312362115/claude, 107 stars) and SQL Database Assistant (alirezarezvani/claude-skills, 28k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Database Migrations?

affaan-m (a GitHub user) maintains it in affaan-m/ECC, which has 275,546 GitHub stars. The repository holds 673 skills in this directory. The repository was last updated on October 5, 2026.

Source: affaan-m/ECC on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.