Communitygithub.com

lguidolin/零停機資料庫遷移

在變更資料庫結構且需保留資料時使用(新增/刪除/重新命名欄位、限制條件、索引或逆向填充)。

零停機資料庫遷移 是什麼?

此技能定義了一套嚴謹的資料庫結構變更規範,確保在滾動部署期間,舊版與新版 Pod 共用同一個資料庫時,不會造成服務中斷。其核心是「擴展/收縮(Expand/Contract)」或稱「並行變更(Parallel Change)」模式,將任何破壞性結構變更拆散為三個獨立釋出週期:先以向後相容的方式新增(Expansion),再分批進行資料逆向填充與雙重寫入(Migration),最後在舊版程式完全退役後才移除舊結構(Contract)。技能同時提供了 PostgreSQL 常見陷阱的對應安全做法(如使用 NOT VALID 搭配 VALIDATE、CREATE INDEX CONCURRENTLY 等),並強調開發環境的「最終形體 CREATE OR REPLACE」規則與生產環境的嚴格遷移紀律不可混淆。此規範適用於所有需要保留資料的專案(如附有數據的預備環境或正式環境),並支援 graphile-migrate 等遷移工具。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/lguidolin/agent-skills/tree/main/skills/zero-downtime-migrations

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

零停機資料庫遷移 是做什麼的?

概述

一種在滾動部署期間維持線上系統運作的資料庫結構變更規範。在發布過程中,舊版 Pod 與新版 Pod 共用同一個資料庫——因此資料庫結構必須同時相容於兩個應用程式版本。將破壞性遷移與需要它的部署綁在一起,是造成自我服務中斷的典型錯誤。

撰寫規則(所有專案)

  • 兩種遷移,明確區分: 冪等的 current/ 集合(開發迭代——每次循環重新執行,使用 CREATE OR REPLACE / IF NOT EXISTS,物件處於最終形體,不進行建立後的 ALTER)以及已提交的遷移(不可變、有序、實際發布的內容)。ALTER DEFAULT PRIVILEGES 是唯一允許的內聯 ALTER。
  • 擁有權透過遷移的執行方式決定,而非散落的 ALTER ... OWNER。
  • 單一啟動來源,由本機/Docker 初始化路徑與影子/測試資料庫共用——每個環境都以相同方式建置。

擴展/收縮(並行變更)

適用情況: 資料庫中存有部署後必須保留的資料(附有數據的預備環境、正式環境)。例外: 本機/可重設專案——但撰寫已提交遷移時應視為此規則適用,以便後續升級時不必重寫。

一個資料庫結構變更應拆分為三個釋出週期,絕不能合而為一:

  1. 擴展 —— 以累加方式、向後相容地新增新結構:可為空的欄位、新資料表、新函式。應用程式版本 N 繼續正常運作。
  2. 遷移 —— 以有限批次進行逆向填充(絕不使用單一會鎖定資料表的 UPDATE);必要時由應用程式 N+1 進行雙重寫入;將讀取切換到新結構。此時才新增 NOT NULL(先以 NOT VALID 新增限制條件,再獨立執行 VALIDATE)。
  3. 收縮 —— 只有在應用程式 N 完全退役後,才在後續的釋出週期中移除舊的欄位或限制條件。

PostgreSQL 常見陷阱

陷阱安全做法
含有易變/大量逆向填充預設值的 NOT NULL 欄位新增可為空欄位 → 分批逆向填充 → 以 NOT VALID 新增限制條件 → VALIDATE
新增限制條件先以 NOT VALID 新增,再 VALIDATE CONSTRAINT(較弱的鎖)
建立索引CREATE INDEX CONCURRENTLY — 無法在交易內執行;需與遷移工具的交易包裝隔離
被封鎖的遷移導致正式環境凍結設定 lock_timeout / statement_timeout 以快速失敗
重新命名欄位這是一個擴展/收縮流程:新增新欄位 → 逆向填充 → 切換讀取 → 移除舊欄位,跨越多個釋出週期

為什麼「最終形體 CREATE OR REPLACE」在正式環境中不夠用

該規則是開發者人體工學,在開發環境中正確。在正式環境中,面對真實使用者與滾動部署,兩個應用程式版本在發布期間共用同一個資料庫——因此擴展/收縮才是讓變更安全的方法。請勿混淆兩者。

完整理由:憲法第十七條,收錄於 engineering-constitution/references/engineering-constitution.md。部署管線:cloud-delivery-aks。

Individual skills in this repo

This repo contains 18 individual skills — each has its own dedicated page.

lguidolin/change-hygiene-and-code-craft

Use when writing or refactoring code, structuring a commit or PR, or deciding whether to abstract duplication. Symptoms — mixing reorg with logic changes, a PR doing several things at once, a file growing large, the second copy of similar code, or unsure whether to DRY something up.

lguidolin/cloud-delivery-aks

Use when deploying to Kubernetes or Azure Kubernetes Service (AKS), configuring cloud secrets, setting up progressive rollout/canary, per-PR ephemeral environments, or k8s health probes. Keywords — Kubernetes, AKS, Key Vault, Argo Rollouts, Flagger, canary, blue-green, liveness, readiness, PodDisruptionBudget, HPA, rollback, GHCR.

lguidolin/commit-history-rewrite

Use when an existing repository has messy commit history that needs to conform to conventional commits before adopting release-please, or when intermediate WIP/fixup/merge commits need to be cleaned up.

lguidolin/conventional-commits-and-releases

Use when committing, writing a commit message, opening a PR that will be squash-merged, or configuring automated versioning/changelogs. Keywords — conventional commits, release-please, semver, feat/fix/chore, breaking change, changelog.

lguidolin/defense-in-depth-security

Use when handling untrusted input, secrets, authentication/authorization, or dependencies — or threat-modeling a new surface. Keywords — STRIDE, threat model, least privilege, secrets management, supply chain, dependency scanning, input validation, audit log, defense in depth.

lguidolin/designing-before-building

Use when starting a feature, fixing a non-trivial bug, or about to write implementation code — before any code exists. Symptoms you need this: "this is simple, I'll just code it", reaching for the editor before a design is approved, or an idea that hasn't been turned into a spec and plan.

lguidolin/engineering-constitution

Use when starting work in a project that follows the engineering constitution, orienting to its rules, or deciding which engineering practice applies to a task — spec writing, commits, testing, security, deploys, database, or UI work.

lguidolin/graphql-contract-testing

Use when writing a GraphQL query/mutation that the UI and a test will share, or building route/schema contract or smoke tests. Symptoms — copying a query into a test, a test asserting on query text, schema change that didn't break the UI build, or RLS/permission drift. Keywords — graphql-codegen, typed document, contract test, route smoke test.

lguidolin/init-repo-CI

Use when setting up a new repository with conventional commits, release-please, and CI automation, or when retrofitting an existing repository that lacks automated versioning and PR validation workflows.

lguidolin/interface-craft-and-accessibility

Use when building or styling UI — components, layouts, forms, design tokens — or making accessibility decisions. Keywords — a11y, WCAG, keyboard navigation, focus state, contrast, design system, minimalist UI, component reuse, ARIA, semantic HTML.

lguidolin/merge-gates-and-automation

Use when setting up or changing CI, pre-push hooks, or a task runner, or deciding what must pass before merge. Symptoms — tempted to put authoritative checks only in a local hook, skip CI, bypass with --no-verify, or unsure what gates a merge vs. runs locally.

lguidolin/observability-and-slos

Use when adding logging, metrics, tracing, health checks, SLOs, or alerting — or when building a service surface that needs to be operable and debuggable. Keywords — structured logs, OpenTelemetry, correlation id, RED metrics, liveness, readiness, SLI, SLO, error budget, alerting.

lguidolin/performance-and-scale

Use when working on hot paths, list endpoints, pagination, data-access in loops, or public interfaces/schemas. Symptoms — unbounded queries, N+1 access, no latency budget, optimizing without measuring, or changing an interface many consumers depend on. Keywords — pagination, N+1, Hyrum's Law, performance budget, bundle size.

lguidolin/postgres-postgraphile-rls-and-sql

Use when writing PostgreSQL, PostGraphile config, Row-Level Security policies, SQL schema files, or working on the Browser→App→PostGraphile→Postgres data path. Keywords — RLS, SECURITY DEFINER, search_path, pgSettings, grants, roles, GraphQL depth limit, query cost, statement_timeout, SQL file organization.

lguidolin/recording-decisions

Use when a design or architecture decision has been made and needs to be captured — writing a decision record or ADR, updating a decision index, noting a deferred idea, or superseding a past decision. Keywords — ADR, decision record, rationale, rejected alternatives, dependency index.

lguidolin/resilience-and-deploy-safety

Use when planning a deploy, designing a rollback, or responding to an incident or writing a postmortem. Keywords — deploy safety, rollback, immutable artifact, progressive delivery, canary, blast radius, incident response, blameless postmortem, error budget.

lguidolin/ship-it

Use when the user wants to ship work — push, PR, archive decision records, merge, and clean up. Handles the full lifecycle from committing final changes through post-merge cleanup including converting specs/plans to compact decision records.

lguidolin/tests-as-a-control

Use when writing or modifying tests, when a test breaks during a refactor, or when testing permission/role rules. Symptoms — tempted to edit a test to make it pass, testing only the happy path, a deny-test that started passing, flaky tests, or unsure what to assert.

相關技能