skills/go-database/SKILL.md
Go Database Migration 與 ORM 規範:Migration 工具選擇(golang-migrate/goose)、 命名慣例、版本控制、CI/CD 整合、最佳實務(pt-online-schema-change, gh-ost)。 **適用場景**:設計資料庫遷移策略、實作 Migration、管理 Schema 版本、處理大型表變更、 配置 CI/CD Pipeline、避免 AutoMigrate、GORM 使用規範。
npx skillsauth add vincent119/ai-rules-kit go-databaseInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
相關 Skills:本規範建議搭配
go-ddd(Repository Pattern)
原則:
gorm.AutoMigrate() 於生產環境(僅限本地開發)# golang-migrate
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
# goose
go install github.com/pressly/goose/v3/cmd/goose@latest
migrations/
├── 20260108120000_create_users_table.up.sql
├── 20260108120000_create_users_table.down.sql
├── 20260108130000_add_email_index.up.sql
├── 20260108130000_add_email_index.down.sql
├── 20260109100000_alter_orders_add_status.up.sql
└── 20260109100000_alter_orders_add_status.down.sql
格式:YYYYMMDDHHMMSS_<description>.<up|down>.sql
規則:
.up.sql 都有對應的 .down.sql範例:
# 正確
20260108120000_create_users_table.up.sql
20260108120000_create_users_table.down.sql
# 錯誤
2026-01-08-CreateUsers.sql # 格式錯誤
create_users.up.sql # 缺少時間戳
20260108120000_AddUserEmail.up.sql # 應使用 snake_case
20260108120000_create_users_table.up.sql:
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users(email);
20260108120000_create_users_table.down.sql:
DROP INDEX IF EXISTS idx_users_email;
DROP TABLE IF EXISTS users;
20260109100000_alter_orders_add_status.up.sql:
-- 新增欄位(帶預設值避免 NULL 問題)
ALTER TABLE orders
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'pending';
-- 新增索引
CREATE INDEX idx_orders_status ON orders(status);
20260109100000_alter_orders_add_status.down.sql:
DROP INDEX IF EXISTS idx_orders_status;
ALTER TABLE orders
DROP COLUMN IF EXISTS status;
錯誤做法:
-- ❌ 修改已執行的 migration
-- 20260108120000_create_users_table.up.sql
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(255) NOT NULL,
-- 後來加上的欄位(不應修改已執行的 migration)
phone VARCHAR(20) NOT NULL
);
正確做法:
-- ✅ 新增一個新的 migration
-- 20260110150000_add_phone_to_users.up.sql
ALTER TABLE users
ADD COLUMN phone VARCHAR(20);
原則:
main() 中執行 migration(避免多副本競爭)# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
template:
spec:
initContainers:
- name: db-migration
image: myapp:latest
command:
- /bin/sh
- -c
- |
migrate -path /migrations \
-database "${DATABASE_URL}" \
up
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
containers:
- name: app
image: myapp:latest
# ...
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
migrate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run migrations
run: |
migrate -path ./migrations \
-database "${{ secrets.DATABASE_URL }}" \
up
- name: Deploy application
run: |
# ...部署應用
問題:ALTER TABLE 在大型表(百萬行級別)會鎖表,影響線上服務。
解決方案:使用 pt-online-schema-change 或 gh-ost
# 範例:新增欄位到大型表
pt-online-schema-change \
--alter "ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'pending'" \
--execute \
D=mydb,t=orders,h=localhost,u=root,p=password
特性:
# 範例
gh-ost \
--user="root" \
--password="password" \
--host="localhost" \
--database="mydb" \
--table="orders" \
--alter="ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'pending'" \
--execute
特性:
問題:直接新增 NOT NULL 欄位會失敗(舊資料無值)。
正確步驟:
Migration 範例:
Step 1:20260110100000_add_status_nullable.up.sql
ALTER TABLE orders
ADD COLUMN status VARCHAR(20) DEFAULT 'pending';
Step 2:20260110110000_backfill_status.up.sql
-- 回填舊資料
UPDATE orders
SET status = 'pending'
WHERE status IS NULL;
Step 3:20260110120000_make_status_not_null.up.sql
ALTER TABLE orders
ALTER COLUMN status SET NOT NULL;
本地測試流程:
# 1. 執行 up
migrate -path ./migrations -database "postgres://localhost/testdb" up
# 2. 驗證 Schema
psql testdb -c "\d orders"
# 3. 執行 down(測試回退)
migrate -path ./migrations -database "postgres://localhost/testdb" down 1
# 4. 再次執行 up(確保可重複執行)
migrate -path ./migrations -database "postgres://localhost/testdb" up
// ❌ 禁止:生產環境使用 AutoMigrate
func main() {
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})
db.AutoMigrate(&User{}, &Order{}) // 不可預測、缺少版本控制
}
// ✅ 正確:僅在本地開發使用
func setupTestDB(t *testing.T) *gorm.DB {
db, _ := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
db.AutoMigrate(&User{}, &Order{}) // 測試環境可用
return db
}
分離 Domain Entity 與 GORM Model:
// internal/order/domain/order.go (Domain Entity)
package domain
type Order struct {
id string
customerID string
amount float64
}
// internal/order/infra/order_model.go (GORM Model)
package infra
type OrderModel struct {
ID string `gorm:"type:uuid;primaryKey"`
CustomerID string `gorm:"type:uuid;not null"`
Amount float64 `gorm:"type:decimal(10,2);not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
func (OrderModel) TableName() string {
return "orders"
}
// 轉換函式
func toDomainOrder(m *OrderModel) *domain.Order {
return &domain.Order{
id: m.ID,
customerID: m.CustomerID,
amount: m.Amount,
}
}
func toGORMModel(o *domain.Order) *OrderModel {
return &OrderModel{
ID: o.ID(),
CustomerID: o.CustomerID(),
Amount: o.Amount(),
}
}
Migration 檔案
YYYYMMDDHHMMSS_description.up/down.sql.up.sql 都有對應的 .down.sql版本控制
CI/CD
main() 中執行 migration最佳實務
gorm.AutoMigrate()tools
基於 SLA/SLO 量化評估事故影響的計算模型與業務影響矩陣。適用於「SLA 影響」、「SLO 違反」、「影響評估」、「營收損失估算」、「Error Budget」、「可用性計算」、「事故成本評估」等量化事故業務影響的任務。強化 impact-assessor 的評估能力。注意:事故原因分析與改善規劃不在此技能範圍內。
research
根因分析(RCA)方法論詳細指南。提供 5 Whys、Fishbone 圖、Fault Tree Analysis、變更分析等結構化 RCA 技術,以及認知偏誤防範清單。適用於「根因分析」、「RCA」、「5 Whys」、「魚骨圖」、「Fault Tree」、「原因分析方法論」、「變更分析」等事故原因分析任務。強化 root-cause-investigator 的分析能力。注意:時間軸重建與改善規劃不在此技能範圍內。
testing
事故事後分析(Postmortem)完整流程。協調 7 個執行階段:資訊收集 → 時間軸重建 → 根因分析 → 影響評估 → 改善規劃 → 報告審查 → 整合報告,最終產出完整的 Postmortem 報告。適用於「寫事故報告」、「post-incident 分析」、「RCA 報告」、「事故時間軸整理」、「建立改善措施」等請求。注意:即時 Incident Response(on-call)、監控系統設定、告警配置不在此技能範圍內。
content-media
投影片版面模式庫。提供 20 種投影片類型的最佳版面配置、格線系統、色彩與字型設計 Token。適用於「投影片版面」、「Slide Layout」、「設計系統」、「格線」、「字型」、「色彩規範」等投影片視覺設計任務。強化 visual-designer 的設計能力。注意:PPT/Keynote 檔案直接輸出不在此技能範圍內。