← 返回 Skills 市场
wpank

database-migrations

作者 wpank · GitHub ↗ · v1.0.0
cross-platform ✓ 安全检测通过
995
总下载
0
收藏
6
当前安装
1
版本数
在 OpenClaw 中安装
/install database-migrations
功能描述
Safe, zero-downtime database migration strategies — schema evolution, rollback planning, data migration, tooling, and anti-pattern avoidance for production systems. Use when planning schema changes, writing migrations, or reviewing migration safety.
使用说明 (SKILL.md)

Database Migration Patterns

Schema Evolution Strategies

Strategy Risk Downtime Best For
Additive-Only Very Low None APIs with backward-compatibility guarantees
Expand-Contract Low None Renaming, restructuring, type changes
Parallel Change Low None High-risk changes on critical tables
Lazy Migration Medium None Large tables where bulk migration is too slow
Big Bang High Yes Dev/staging or small datasets only

Default to Additive-Only. Escalate to Expand-Contract only when you must modify or remove existing structures.


Zero-Downtime Patterns

Every production migration must avoid locking tables or breaking running application code.

Operation Pattern Key Constraint
Add column Nullable first Never add NOT NULL without default on large tables
Rename column Expand-contract Add new → dual-write → backfill → switch reads → drop old
Drop column Deprecate first Stop reading → stop writing → deploy → drop
Change type Parallel column Add new type → dual-write + cast → switch → drop old
Add index Concurrent CREATE INDEX CONCURRENTLY — don't wrap in transaction
Split table Extract + FK Create new → backfill → add FK → update queries → drop old columns
Change constraint Two-phase Add NOT VALIDVALIDATE CONSTRAINT separately
Add enum value Append only Never remove or rename existing values

Migration Tools

Tool Ecosystem Style Key Strength
Prisma Migrate TypeScript/Node Declarative (schema diff) ORM integration, shadow DB
Knex JavaScript/Node Imperative (up/down) Lightweight, flexible
Drizzle Kit TypeScript/Node Declarative (schema diff) Type-safe, SQL-like
Alembic Python Imperative (upgrade/downgrade) Granular control, autogenerate
Django Migrations Python/Django Declarative (model diff) Auto-detection
Flyway JVM / CLI SQL file versioning Simple, wide DB support
golang-migrate Go / CLI SQL (up/down files) Minimal, embeddable
Atlas Go / CLI Declarative (HCL/SQL diff) Schema-as-code, linting, CI

Match the tool to your ORM and deployment pipeline. Prefer declarative for simple schemas, imperative for fine-grained data manipulation.


Rollback Strategies

Approach When to Use
Reversible (up + down) Schema-only changes, early-stage products
Forward-only (corrective migration) Data-destructive changes, production at scale
Hybrid Reversible for schema, forward-only for data

Data Preservation

  1. Soft-delete columns — rename with _deprecated suffix instead of dropping
  2. Snapshot tablesCREATE TABLE _backup_\x3Ctable>_\x3Cdate> AS SELECT * FROM \x3Ctable>
  3. Point-in-time recovery — ensure WAL archiving covers migration windows
  4. Logical backupspg_dump of affected tables before migration

Blue-Green Database

1. Replicate primary → secondary (green)
2. Apply migration to green
3. Run validation suite against green
4. Switch traffic to green
5. Keep blue as rollback target (N hours)
6. Decommission blue after confidence window

Data Migration Patterns

Backfill Strategies

Strategy Best For
Inline backfill Small tables (\x3C 100K rows)
Batched backfill Medium tables (100K–10M rows)
Background job Large tables (10M+ rows)
Lazy backfill When immediate consistency not required

Batch Processing

DO $$
DECLARE
  batch_size INT := 1000;
  rows_updated INT;
BEGIN
  LOOP
    UPDATE my_table
    SET new_col = compute_value(old_col)
    WHERE id IN (
      SELECT id FROM my_table
      WHERE new_col IS NULL
      LIMIT batch_size
      FOR UPDATE SKIP LOCKED
    );
    GET DIAGNOSTICS rows_updated = ROW_COUNT;
    EXIT WHEN rows_updated = 0;
    PERFORM pg_sleep(0.1);  -- throttle to reduce lock pressure
    COMMIT;
  END LOOP;
END $$;

Dual-Write Period

For expand-contract and parallel change:

  1. Dual-write — application writes to both old and new columns/tables
  2. Backfill — fill new structure with historical data
  3. Verify — assert consistency (row counts, checksums)
  4. Cut over — switch reads to new, stop writing to old
  5. Cleanup — drop old structure after cool-down period

Testing Migrations

Test Against Production-Like Data

  • Never test against empty or synthetic data only
  • Use anonymized production snapshots
  • Match data volume — a migration working on 1K rows may lock on 10M
  • Reproduce edge cases: NULLs, empty strings, max-length, unicode

Migration CI Pipeline

- name: Test migrations
  steps:
    - run: docker compose up -d db
    - run: npm run migrate:up        # apply all
    - run: npm run migrate:down      # rollback all
    - run: npm run migrate:up        # re-apply (idempotency)
    - run: npm run test:integration  # validate app
    - run: npm run migrate:status    # no pending

Every migration PR must pass: up → down → up → tests.


Migration Checklist

Pre-Migration

  • Tested against production-like data volume
  • Rollback written and tested
  • Backup of affected tables created
  • App code compatible with both old and new schema
  • Execution time benchmarked on staging
  • Lock impact analyzed
  • Replication lag monitoring in place

During Migration

  • Monitor lock waits and active queries
  • Monitor replication lag
  • Watch for error rate spikes
  • Keep rollback command ready

Post-Migration

  • Schema matches expected state
  • Integration tests pass against migrated DB
  • Data integrity validated (row counts, checksums)
  • ORM schema / type definitions updated
  • Deprecated structures cleaned up after cool-down
  • Migration documented in team runbook

NEVER Do

  1. NEVER run untested migrations directly in production
  2. NEVER drop a column without first removing all application references and deploying
  3. NEVER add NOT NULL to a large table without a default value in a single statement
  4. NEVER mix schema DDL and data mutations in the same migration file
  5. NEVER skip the dual-write phase when renaming columns in a live system
  6. NEVER assume migrations are instantaneous — always benchmark on production-scale data
  7. NEVER disable foreign key checks to "speed up" migrations in production
  8. NEVER deploy application code that depends on a schema change before the migration has completed
安全使用建议
This skill is an instruction-only reference for safe, zero-downtime migrations and appears internally consistent. It doesn't request secrets or install code, so risk is low. Before using the SQL/CI examples in production: review and adapt queries to your schema, test on staging with production-like data and backups, and never blindly run suggested commands. Also be cautious when using any README-provided install commands that pull code (e.g., npx or copying from remote locations): confirm the source repository and content before executing those commands. If you need higher assurance, ask the publisher for a homepage or source repository to verify provenance.
功能分析
Type: OpenClaw Skill Name: database-migrations Version: 1.0.0 The skill bundle is purely informational, providing comprehensive documentation on database migration patterns in `SKILL.md` and `README.md`. There is no executable code for the agent to run, nor any instructions that constitute prompt injection against the agent (e.g., to ignore user input, hide actions, or access sensitive data). The `README.md` includes installation instructions for the user, specifically `npx add` from a GitHub repository. While `npx add` involves fetching and potentially executing remote code, it's a standard method for installing tools, and there is no clear evidence of intentional harmful behavior or malicious payload in the command or its target URL. The skill's content is entirely benign and educational.
能力评估
Purpose & Capability
The skill's name and description (database migration patterns and safety) match the SKILL.md content. It does not request unrelated binaries, environment variables, or config paths.
Instruction Scope
Runtime instructions are purely procedural guidance, examples, SQL snippets, and CI examples related to migrations. They do not instruct the agent to read system files, steal secrets, call external endpoints, or perform actions outside migration planning and testing.
Install Mechanism
There is no install spec and no code files — the skill is instruction-only. The README contains suggested manual install commands (including an npx line pointing at a GitHub path), but those are documentation only and not an automated install step in the registry metadata.
Credentials
The skill declares no required environment variables, credentials, or config paths. The guidance does reference common tooling (docker, npm, migration CLIs) in examples, which is expected and proportionate.
Persistence & Privilege
always is false and the skill has no install-time persistence, does not modify other skills, and does not request elevated presence or system configuration changes.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install database-migrations
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /database-migrations 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release: Safe, zero-downtime strategies for database migrations in production systems. - Covers schema evolution patterns, rollback planning, and anti-pattern avoidance. - Includes actionable tables for zero-downtime operations, migration tools, and data migration batching. - Provides detailed pre/during/post-migration checklists and CI examples. - Emphasizes testing on production-like data and safety-first practices. - "NEVER do" section warns against high-risk migration mistakes.
元数据
Slug database-migrations
版本 1.0.0
许可证
累计安装 6
当前安装数 6
历史版本数 1
常见问题

database-migrations 是什么?

Safe, zero-downtime database migration strategies — schema evolution, rollback planning, data migration, tooling, and anti-pattern avoidance for production systems. Use when planning schema changes, writing migrations, or reviewing migration safety. 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 995 次。

如何安装 database-migrations?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install database-migrations」即可一键安装,无需额外配置。

database-migrations 是免费的吗?

是的,database-migrations 完全免费(开源免费),可自由下载、安装和使用。

database-migrations 支持哪些平台?

database-migrations 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 database-migrations?

由 wpank(@wpank)开发并维护,当前版本 v1.0.0。

💬 留言讨论