SUPABASE CORE · 118
Schema / Migration / Dev→Production:Database 也需要版本控制
Dashboard 手動點幾下很適合試驗,但正式專案必須能回答:這個 column/policy/index 何時加入?怎麼在新環境重現?App code 和 schema 的部署順序是什麼?
Learning outcomes
- 能把 schema change 視為 versioned artifact。
- 能辨識 additive / destructive migration risk。
- 能設計 backward-compatible deployment order。
- 能說明 dev/production drift 的危險。
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.sqlMigration 把 schema evolution 放進 source control。
3. 危險變更
- DROP column/table
- 改 data type
- 既有 null column 加 NOT NULL
- 大表建立昂貴 index
- 大量 backfill
都可能影響 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
- app commit 哪版?
- production migration 到哪版?
- migration 是否成功?
- 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
- Schema change 是否 backward compatible?
- Data API role 需要哪些 GRANT?
- RLS 是否 enable 且 policy 符合真實 access model?
- Update policy 是否需要 SELECT / WITH CHECK 配套?
- Production smoke 要驗哪個 user identity / query?
Knowledge check
- Migration 為何是 release artifact?
- 加 NOT NULL 為何可能危險?
- 什麼是 expand/contract?
- 設計 owner_id + RLS migration sequence。