Logo Db Migrations

Db Migrations

Cộng đồng
ericrisco
db-migrations

Use when a schema change must ship without downtime — NOT NULL, rename, type change, or backfilling millions of live rows — for the expand-contract sequence and the lock/batching discipline that keeps each step from freezing prod. NOT lock internals or EXPLAIN (that is `postgresdb`), NOT drizzle-kit mechanics (that is `drizzle-orm`), NOT PITR (that is `backups`).

Tổng quan

Nhà phát hànhericrisco
Kho mãrsc-harness
Tên kỹ năngdb-migrations
Sao
239
Bản fork
24
Tệp đi kèm
5
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 5 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được ericrisco công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Db Migrations trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/ericrisco/rsc-harness/tree/main/skills/db-migrations
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ericrisco/rsc-harness.git /tmp/rsc-harness
mkdir -p .claude/skills
cp -r /tmp/rsc-harness/skills/db-migrations .claude/skills/db-migrations
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Db Migrations trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Db Migrations ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Db Migrations không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Database migrations without downtime

A production migration is a sequence, not a statement. The moment you treat ALTER TABLE ... NOT NULL as one atomic change, you have already lost: the lock blocks every writer, the deploy that depends on the new column races the deploy that still reads the old one, and a rollback means a second outage. Your job is to decompose one risky change into a chain of small steps where every intermediate state is independently deployable — the old app keeps working, the new app keeps working, and you can stop at any point without an outage.

This skill is engine-neutral. It owns the choreography — what order to run things in and how to keep each DDL from freezing the table — across Postgres, MySQL, and serverless variants, whatever runner you use (Flyway, Alembic, golang-migrate, drizzle-kit, raw SQL).

Route elsewhere

  • Postgres lock internals, EXPLAIN/ANALYZE, indexing strategy, RLS, PgBouncer → ../postgresdb/SKILL.md.
  • Writing schema and running drizzle-kit specifically → ../drizzle-orm/SKILL.md.
  • PlanetScale deploy-request / branch cutover (Vitess online DDL) → ../planetscale/SKILL.md.
  • Creating/verifying backups, restore drills, PITR → ../backups/SKILL.md (a migration requires a backup; making it lives there).
  • Pure query logic — joins, windows, CTEs → ../sql/SKILL.md (backfill batching is here; query correctness is there).

Step 1 — Is this change online-safe in one step?

Most outages come from running a multi-step change as a single statement. Decide first:

ChangeOne step?Why
Add nullable column, no volatile defaultYesMetadata-only on PG 11+/modern MySQL; no rewrite, no long lock.
Add column with a constant defaultYes (PG 11+)Stored as a catalog default, no table rewrite.
Add column with a volatile/expression defaultNoRewrites every row under lock → expand-contract.
Add NOT NULL to existing/new columnNoFull-table validation scan under lock → add-nullable → backfill → validate.
Rename column / tableNoApp reads the old name; needs dual-name window → expand-contract.
Change column type (non-trivial)NoRewrites rows, may invalidate the running app → new column + backfill.
Split / merge columnsNoTwo-sided data move → expand-contract.
Drop column / tableNoRunning app may still reference it → contract only after a cooling period.
Add foreign keyNoADD CONSTRAINT validates all rows under lock → add NOT VALID then VALIDATE.
Create indexNo, but cheapPlain CREATE INDEX locks writes → use CONCURRENTLY.

If the row says No, you are doing expand-contract. Go to Step 2.

Step 2 — The expand-contract loop

Three phases, each tied to a distinct deploy. Worked example: rename users.email → users.email_address.

Expand — add the new structure, start dual-writing, leave the old one fully working.

sql
-- migration 1 (deploy A): additive only, old app untouched
SET lock_timeout = '1s';
ALTER TABLE users ADD COLUMN email_address text;  -- nullable, no default → metadata-only
text
App deploy A: write BOTH columns on every insert/update; keep READING email.

Backfill — copy historical data in small background batches (Step 4), then verify counts/checksums.

Switch reads — once backfilled and verified, deploy the app that reads email_address.

text
App deploy B: read email_address; still dual-write both.  ← cooling period starts here

Contract — only after a cooling period (hours to days) where the new app has run clean and you can still roll back the app without touching schema, stop writing the old column and drop it.

sql
-- migration 2 (deploy C): runs days later, after cooling period
SET lock_timeout = '1s';
ALTER TABLE users DROP COLUMN email;

The cooling period is the point. It is what lets you roll back app deploy B to app deploy A with zero schema change — because the old column still exists and is still being written. Contracting early throws that safety away.

Step 3 — The N/N-1 rule

At every moment, two app versions can be live: the one running and the one rolling out. The schema must be compatible with both, and each app must tolerate the other's schema. That is the entire reason dual-write exists — it makes the schema a superset that satisfies app N and app N+1 simultaneously.

text
schema:  +email_address ......................... -email
apps:    [N reads email] [N+1 reads email_address] [N+2 ignores email]
              ^ both alive during rollout ^         ^ safe to drop now ^

If you ever have a single instant where one deployed app version cannot run against the current schema, your migration is not zero-downtime — it is a timed outage.

Step 4 — Make each DDL statement safe

Always set a short lock_timeout first. A DDL waiting on a lock builds a queue — every query behind it stalls too, and one slow ALTER freezes the whole table. A short timeout makes the migration fail fast so traffic keeps flowing; you retry instead of taking the site down.

sql
-- Bad: unbounded wait; if a lock is held, this queues every reader/writer behind it
ALTER TABLE orders ADD COLUMN region text;

-- Good: fail fast, retry
SET lock_timeout = '1s';
ALTER TABLE orders ADD COLUMN region text;

Create indexes CONCURRENTLY, outside a transaction. Plain CREATE INDEX takes a SHARE lock and blocks all writes for its whole duration — that is the "our deploy deadlocks when we add an index" symptom. CONCURRENTLY takes SHARE UPDATE EXCLUSIVE and does not block writes, but cannot run inside a transaction block. Runners (Flyway, Alembic, Django, Rails) wrap each migration in a transaction by default, so you must opt that step out — see references/tools-and-runners.md.

sql
-- Bad: locks out every writer for the full build
CREATE INDEX idx_orders_region ON orders (region);

-- Good: non-blocking; this statement must NOT be inside BEGIN/COMMIT
CREATE INDEX CONCURRENTLY idx_orders_region ON orders (region);

A failed CONCURRENTLY build leaves an INVALID index behind. Drop it (DROP INDEX CONCURRENTLY) before retrying. For PG-specific lock-level detail, see ../postgresdb/SKILL.md.

Add NOT NULL in four steps, never in one. A single ALTER ... SET NOT NULL (or ADD COLUMN ... NOT NULL DEFAULT <volatile>) scans/rewrites the whole table under lock.

sql
-- Bad: full-table validation/rewrite under an exclusive lock
ALTER TABLE users ADD COLUMN status text NOT NULL DEFAULT 'active';  -- on a 40M-row table = outage

-- Good: add nullable, backfill in batches (Step 5), then add a constraint without a blocking scan
SET lock_timeout = '1s';
ALTER TABLE users ADD COLUMN status text;                              -- 1. nullable
-- 2. backfill in batches (Step 5), app dual-writes the new column
ALTER TABLE users ADD CONSTRAINT users_status_nn
  CHECK (status IS NOT NULL) NOT VALID;                                -- 3. instant, no scan
ALTER TABLE users VALIDATE CONSTRAINT users_status_nn;                 -- 4. scans WITHOUT blocking writes
-- PG 12+: a validated CHECK (col IS NOT NULL) lets SET NOT NULL skip its own scan
ALTER TABLE users ALTER COLUMN status SET NOT NULL;

Same NOT VALID → VALIDATE pattern for adding a foreign key. The full per-change checklists live in references/expand-contract-playbook.md.

Step 5 — Backfill at scale

Never one giant UPDATE. A single statement over millions of rows holds locks, bloats WAL/undo, and pins replicas behind a wall of lag. Loop bounded chunks, commit each, throttle on lag, then verify.

sql
-- Bad: one statement locks rows, balloons WAL, spikes replica lag for minutes
UPDATE users SET email_address = email WHERE email_address IS NULL;
sql
-- Good: bounded PK-range batches, committed individually, throttled between batches
-- pseudo-loop (driven by your runner/script): a few thousand rows per batch
UPDATE users
SET email_address = email
WHERE id BETWEEN :lo AND :hi
  AND email_address IS NULL;
-- commit; check replica lag; sleep if lag/error-rate is high; advance :lo/:hi; repeat

Watch replication lag and the app error rate between batches; back off when either climbs. Verify before contracting — row counts and a checksum of old-vs-new must match. For very large sets, snapshot + CDC instead of an online loop. Postgres and MySQL backfill scripts, the lag-throttle, and checksum queries are in references/backfill-and-batching.md.

Step 6 — Rollback reality

Forward-only is the prevailing 2025-2026 production stance. Reliable down() migrations are rarely worth the effort — whether a rollback is even safe depends on the migration type and how much time has passed (data has changed under you). Treat applied migrations as immutable and fix forward.

Your real safety net is not a down() script — it is the expand-contract structure itself: because the old column/table still exists during the cooling period, "rolling back" is just redeploying the previous app. A reversible down-migration is only worth writing when the change is additive-only and pre-traffic (e.g. a brand-new table no app version reads yet). For anything that touched live data, a down-migration is a trap that looks like a seatbelt.

Step 7 — Pick a runner / OSC tool

Versioned runners replay ordered scripts; declarative tools diff your target schema. Pick by stack:

Stack / needTool (2026)Note
JVM, SQL-first, 50+ DBsFlyway 12.6.xVersion-based; Redgate dropped the Teams tier in 2025.
Max format flexibilityLiquibaseSQL/XML/YAML/JSON changelogs; most verbose.
Python / SQLAlchemyAlembic 1.18.xRequires Python ≥3.10; plugin system since 1.18.0.
Gogolang-migrateThe Go standard.
TypeScript / Drizzledrizzle-kitMechanics in ../drizzle-orm/SKILL.md; safety sequence here.
Schema-as-code, planned diffsAtlasDeclarative — you give the target, it plans the diff.
Big MySQL ALTER, native online DDL can't keep it onlinegh-ost or pt-oscSee below.

gh-ost vs pt-osc for a large MySQL ALTER: gh-ost is triggerless — it copies in chunks and replays the binlog, throttles on replica lag, and gives easier pause/cutover control; prefer it on a very busy master. pt-osc is trigger-based — strictly consistent, but the triggers add write overhead and can fail to acquire the metadata lock under highly concurrent or long-transaction load. Decision detail and per-runner transaction opt-out in references/tools-and-runners.md.

Step 8 — Gate migrations in CI

Add a static linter for migration SQL before merge, so a bare CREATE INDEX or a one-shot NOT NULL never reaches review. Squawk is the standard for Postgres migration SQL — it flags adding NOT NULL columns, non-concurrent index creation, blocking constraint adds, and column drops.

yaml
# CI step: fail the PR on dangerous migration DDL
- name: Lint migrations
  run: npx squawk@latest migrations/*.sql

Config snippet and rule notes in references/tools-and-runners.md. scripts/verify.sh in this skill runs the same static checks against the example migrations shipped in references/.

Anti-patterns

Anti-patternWhy it hurtsDo instead
ALTER TABLE ... ADD COLUMN ... NOT NULL DEFAULT <expr> on a big tableFull-table rewrite under lock = outageadd nullable → backfill → NOT VALID → VALIDATE (Step 4)
Plain CREATE INDEX in prodSHARE lock blocks all writes for the build → deploy "deadlock"CREATE INDEX CONCURRENTLY, outside a transaction
DDL with no lock_timeoutBuilds a lock queue; one slow ALTER freezes the tableSET lock_timeout='1s' first, fail fast, retry
One giant backfill UPDATELocks rows, bloats WAL, spikes replica lagbounded batches, commit each, throttle on lag (Step 5)
Renaming a column the running app still readsInstant errors for app version Ndual-name window: add new, dual-write, switch reads, then drop
Contracting before the cooling periodKills your no-schema-change rollback pathwait until the new app has run clean; then drop
Relying on down() in prodData already changed; rollback is unsafe or wrongforward-only; expand-contract IS the rollback (Step 6)
Coupling app + schema in one deployBreaks N/N-1; an instant where some app can't runseparate deploys; schema is a superset of both (Step 3)

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Db Migrations làm được gì?

Use when a schema change must ship without downtime — NOT NULL, rename, type change, or backfilling millions of live rows — for the expand-contract sequence and the lock/batching discipline that keeps each step from freezing prod. NOT lock internals or EXPLAIN (that is `postgresdb`), NOT drizzle-kit mechanics (that is `drizzle-orm`), NOT PITR (that is `backups`).

Vì sao nên dùng Db Migrations trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Db Migrations là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Db Migrations trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/ericrisco/rsc-harness/tree/main/skills/db-migrations. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Db Migrations?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Db Migrations với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Db Migrations với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Db Migrations có miễn phí không?

Có. Kỹ năng này được ericrisco phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇