← 課程地圖

SUPABASE CORE · 118

Schema / Migration / Dev→Production:Database 也需要版本控制

Dashboard 手動點幾下很適合試驗,但正式專案必須能回答:這個 column/policy/index 何時加入?怎麼在新環境重現?App code 和 schema 的部署順序是什麼?

Learning outcomes

1. Schema 不只 table/column

tables
columns
types
constraints
indexes
functions
triggers
RLS policies

這些都會影響 app behavior,應能被 review/reproduce。

2. Migration

001_create_courses.sql
002_add_owner_id.sql
003_enable_rls.sql
004_add_score_check.sql

Migration 把 schema evolution 放進 source control。

3. 危險變更

都可能影響 correctness、lock time、availability。

4. Expand → Migrate → Contract

1. Add compatible new column
2. Deploy code supporting both
3. Backfill
4. Switch reads/writes
5. Add stricter constraint
6. Remove old field later

核心是先相容,再收緊。

5. Environment drift

Dev Dashboard 加了 policy 但 migration 沒 commit,production 不會自動知道;production 手動 hotfix 也可能讓 repo 不再代表真實 schema。

Project checkpoint:Course Workspace v6 release plan

Git:
  app code
  migration
  RLS policies
  tests
    ↓
dev migration
    ↓
integration/RLS tests
    ↓
production migration
    ↓
compatible app deploy
    ↓
smoke query

先 DB 或先 app 取決於 compatibility design,不是固定口訣。

Debug evidence:column does not exist

  1. app commit 哪版?
  2. production migration 到哪版?
  3. migration 是否成功?
  4. app 是否提早依賴新 schema?

6. Migration 也要包含 Data API / RLS contract

現在 migration 不只要建立 table、column、index。對會被 client Data API 使用的 table,你還要明確思考 role privilege 與 RLS。新 table 不應假設建立後自然就能被 Browser client 查詢。

CREATE TABLE
  ↓
GRANT required privileges
  ↓
ENABLE RLS
  ↓
CREATE POLICY
  ↓
Integration / RLS tests
  ↓
Application release

Local development 建新 migration 時,先建立正式 migration artifact,再把 SQL change 放進去;若遠端已有 schema change,應把它 reconcile 回 migration history,而不是長期靠 Dashboard 手動狀態。

Migration review checklist

  1. Schema change 是否 backward compatible?
  2. Data API role 需要哪些 GRANT?
  3. RLS 是否 enable 且 policy 符合真實 access model?
  4. Update policy 是否需要 SELECT / WITH CHECK 配套?
  5. Production smoke 要驗哪個 user identity / query?

Knowledge check

  1. Migration 為何是 release artifact?
  2. 加 NOT NULL 為何可能危險?
  3. 什麼是 expand/contract?
  4. 設計 owner_id + RLS migration sequence。