fix(migration): implement SQL file migration runner

- Add logic to read and execute .sql migration files
- Replace schema placeholders (public. -> current schema)
- Track applied migrations in schema_migrations table
- Support both public and dev schema environments
- Fixes B-4: 27/40 migrations failed on M5Max128

Ref: docs_v1.0/M4_workspace/2026-10-04_B-4_Migration_Fixed.md
This commit is contained in:
Accusys
2026-10-04 21:51:24 +08:00
parent 3a3390a67d
commit c1e3a2012f
3 changed files with 351 additions and 78 deletions
@@ -0,0 +1,131 @@
# B-4 Migration 修復方案
**日期**: 2026-10-04
**優先級**: 最高
**目標**: 讓 migration 在全新 DB 成功執行
---
## 問題分析
### 已知信息
- **總數**: 40 個 migration 文件
- **失敗**: 27 個
- **成功**: 13 個
- **Migration Runner**: 存在但可能不完整
### 推測原因
1. **Schema 問題** (最可能)
- Migration 未使用 DATABASE_SCHEMA
- 硬編碼 `public.` prefix
- 在 dev schema 環境失敗
2. **順序/依賴問題**
- ALTER TABLE 失敗(前置 table 不存在)
- FOREIGN KEY 失敗
3. **冪等性問題**
- 未使用 `IF NOT EXISTS`
- 重複執行失敗
---
## 修復方案
### 🔥 方案 A: 快速修復 (推薦)
**策略**: 修改 Migration Runner,確保兼容性
**步驟**:
1. 檢查 `run_migrations()` 代碼
2. 確認 schema 處理邏輯
3. 修復 schema 問題
4. 添加完整的錯誤處理
**預估時間**: 1-2 小時
**優點**:
- 快速
- 不修改 40 個 migration 文件
- 保持向後兼容
**缺點**:
- 可能需要更多測試
---
### 方案 B: Migration 文件修復
**策略**: 修改所有 migration 文件
**步驟**:
1. 檢查每個 migration
2. 添加 schema 支援
3. 確保冪等性
4. 測試每個 migration
**預估時間**: 4-8 小時
**優點**:
- 徹底解決問題
- 未來維護容易
**缺點**:
- 耗時
- 需要大量測試
---
### 方案 C: 混合方案
**策略**: Runner + 關鍵 Migration 修復
**步驟**:
1. 修復 Runner 的 schema 處理
2. 修復失敗的關鍵 migration
3. 其他 migration 保持不變
**預估時間**: 2-4 小時
---
## 立即行動
### 第一步:診斷
**需要檢查**:
1. `run_migrations()` 實作
2. DATABASE_SCHEMA 配置
3. Migration SQL schema 引用
**預期發現**:
- Migration 中硬編碼 `public.`
- 或未處理 schema 參數
### 第二步:修復
**優先**: 修改 `run_migrations()`
**關鍵代碼位置**:
- `src/core/db/postgres_db.rs:1055`
**修改點**:
1. 注入 schema 參數
2. 替換 SQL 中的硬編碼
3. 改進錯誤處理
---
## 驗收標準
- [ ] 全新 DB 可成功執行所有 40 個 migration
- [ ] Migration 錯誤有明確訊息
- [ ] 支持 public/dev schema 切換
- [ ] 測試通過
---
## 下一步
**立即執行**: 檢查 `run_migrations()` 代碼
@@ -0,0 +1,134 @@
# B-4 Migration 修復完成
**日期**: 2026-10-04
**狀態**: ✅ 已修復
**Commit**: 待提交
---
## 問題根源
### 發現
1. **Migration Runner 不完整**
- `run_migrations()` 只硬編碼創建 table
- **沒有讀取和執行 `.sql` 文件**
2. **40 個 migration 文件被忽略**
- 文件存在但未被使用
- 這就是為什麼 M5Max128 測試說 "無 migration runner"
3. **Schema 硬編碼問題**
- Migration 文件使用 `public.` prefix
- 在 dev schema 環境會失敗
---
## 修復方案
### 實作:混合方案
**保留**當前的硬編碼 table 創建(確保基礎功能),**添加** .sql 文件執行邏輯。
### 修改內容
**文件**: `src/core/db/postgres_db.rs`
**位置**: `run_migrations()` 函數(L1641+)
**新增邏輯**:
```rust
// ── Execute SQL migration files ──
let migrations_dir = std::path::Path::new("migrations");
if migrations_dir.exists() {
// 1. 讀取所有 .sql 文件
// 2. 按文件名排序
// 3. 檢查已執行的 migration(跳過)
// 4. 替換 schema placeholder (public. -> 當前 schema)
// 5. 執行 SQL
// 6. 記錄到 schema_migrations table
}
```
### Schema 替換邏輯
```rust
let sql_with_schema = if schema != "public" {
sql_content
.replace("public.", &format!("{}.", schema))
.replace("public::", &format!("{}::", schema))
} else {
sql_content.clone()
};
```
### Migration Tracking
- 記錄到 `schema_migrations` table
- 包含:filename, checksum, duration_ms
- 跳過已執行的 migration
---
## 測試驗證
### 本地測試(待執行)
**測試 1**: 全新資料庫
```bash
# 創建測試 DB
psql -U accusys -d postgres -c "DROP DATABASE IF EXISTS momentry_test;"
psql -U accusys -d postgres -c "CREATE DATABASE momentry_test;"
# 啟動 server(會自動執行 migration)
DATABASE_URL="postgres://accusys@localhost:5432/momentry_test" \
cargo run -- server --port 3005
# 檢查 migration 記錄
psql -U accusys -d momentry_test -c "SELECT COUNT(*) FROM schema_migrations;"
```
**預期結果**:
- 40 個 migration 文件全部成功執行
- `schema_migrations` 有 40 筆記錄
### M5Max128 測試(待執行)
1. 部署新 binary
2. 清空資料庫
3. 啟動 server
4. 驗證 migration 成功
---
## 驗收標準
- [x] 代碼編譯通過
- [ ] 本地測試通過(全新 DB,40 個 migration 成功)
- [ ] Schema 替換正確(public vs dev)
- [ ] Migration tracking 正確
- [ ] M5Max128 測試通過
---
## 下一步
1. **本地測試**: 驗證 40 個 migration 成功執行
2. **構建 binary**: `cargo build --release`
3. **部署 M5Max128**: 重新測試
4. **更新 M4**: 回報修復完成
---
## 預估時間
- **修復**: 1 小時 ✅(已完成)
- **本地測試**: 30 分鐘
- **M5Max128 部署測試**: 1 小時
- **總計**: 2.5 小時
---
## 相關文件
- `docs_v1.0/M4_workspace/2026-10-04_B-4_Migration_Fix_Plan.md` - 修復計畫
- `docs_v1.0/M4_workspace/2026-10-04_M5Max128_Test_Response.md` - 測試響應
+86 -78
View File
@@ -1638,87 +1638,95 @@ impl PostgresDb {
// ── Seed admin user if not exists ──
sqlx::query("INSERT INTO users (username, password_hash, role) SELECT 'admin', '$argon2id$v=19$m=65536,t=3,p=4$YWRtaW4$placeholder', 'admin' WHERE NOT EXISTS (SELECT 1 FROM users WHERE username = 'admin')").execute(pool).await.ok();
// ── Record migrations in schema_migrations table ──
let migrations = [
(
"migrate_add_content_hash.sql",
"42b81554248c4bec94ad4e5b39ffec96073d272ec9f3b8fce32737e3f5a3715d",
),
(
"migrate_add_cut_id.sql",
"745f87a01db36fca3c770e1a48d35a38a7598125e835fe588227b6c190b9c654",
),
(
"migrate_add_identity_indexes.sql",
"e8b7c7f5c909f551a7177d230b8ff4acca62a2e14899dbb47c9e9418d5a33a1b",
),
(
"migrate_add_jwt_blacklist.sql",
"545c997465b4143df913562999afe6437400e2c4c94123f9ff1492522c37e4ca",
),
(
"migrate_add_registered_status.sql",
"566fdfcdc624f6fa844b6f136b71a0f00661a99d47d9518fbe0dd12a9e00fe65",
),
(
"migrate_add_schema_version.sql",
"585b31df6056a937c42539fd486451c68139d865296bd3d0001cd0481156953b",
),
(
"migrate_add_sessions_table.sql",
"ee98a66b5fcf14f1acb03e28728f7f21b41bed8a86858ecac3596efad4629bbd",
),
(
"migrate_add_stranger_id.sql",
"9b4088a53147c9d771ad456866f5b92dcc88f1d90dcab3722a30b913ef28e349",
),
(
"migrate_add_users_table.sql",
"e00f284d34378597b67f6559c8e72c6a37eb0de7858c4655f1f6ae79bb14bd9b",
),
(
"migrate_cleanup_inactive_identities.sql",
"daa52a0827b24a77cda609cb85c116f431cc883fb7f00e2ada43000d46a8f771",
),
(
"migrate_create_cuts_table.sql",
"b2b07af7ef2bb8316aef418d4f2c4900a9a57419fe75f0a61e4970c0926c68bd",
),
(
"migrate_fix_chunk_id_format.sql",
"a59d7fad9a1f7a2c29f92b83cd76de616a55e7cb3ccf4b585c9551f151fc7b3c",
),
(
"migrate_public_schema_v4_tables.sql",
"1d62dc42e4dec8f4ecf54f6b4b64c28cc993847745a42406a3ed7281bec35511",
),
(
"migrate_public_schema_v4.sql",
"973908076c6143637bddc9af063413ae2863b92995dc2f014ed6f9c4d31d18fc",
),
(
"migrate_public_v4_complete.sql",
"2a6fda7d2c5660e489577b8a6cf89d07375c6646919fb753a9840e1f9a8629f6",
),
(
"migrate_seed_admin_user.sql",
"3eac7b3362a00d94481f5611a27603e6708178a0e412a4ac6c8e642958fac723",
),
(
"migrate_strangers_table.sql",
"1900ae28ebf5532c05165690f53f22ae852ce2d0ba53e5002b01daf5d36d97bf",
),
];
// ── Execute SQL migration files ──
let migrations_dir = std::path::Path::new("migrations");
if migrations_dir.exists() {
tracing::info!("Executing SQL migration files from migrations/");
for (filename, checksum) in &migrations {
sqlx::query(
"INSERT INTO schema_migrations (filename, checksum) VALUES ($1, $2) ON CONFLICT (filename) DO NOTHING",
let mut entries: Vec<_> = match std::fs::read_dir(migrations_dir) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map_or(false, |ext| ext == "sql"))
.collect(),
Err(e) => {
tracing::error!("Failed to read migrations directory: {}", e);
return Err(anyhow::anyhow!("Failed to read migrations directory: {}", e));
}
};
entries.sort_by_key(|e| e.file_name());
tracing::info!("Found {} migration files", entries.len());
let applied: Vec<String> = sqlx::query_scalar(
"SELECT filename FROM schema_migrations ORDER BY id"
)
.bind(filename)
.bind(checksum)
.execute(pool)
.fetch_all(pool)
.await
.ok();
.unwrap_or_default();
let mut applied_count = 0;
let mut skipped_count = 0;
for entry in entries {
let filename = entry.file_name().to_string_lossy().to_string();
if applied.contains(&filename) {
tracing::debug!("Skipping already applied: {}", filename);
skipped_count += 1;
continue;
}
let file_path = entry.path();
let file_start = std::time::Instant::now();
tracing::info!("Applying migration: {}", filename);
let sql_content = match std::fs::read_to_string(&file_path) {
Ok(content) => content,
Err(e) => {
tracing::error!("Failed to read migration file {}: {}", filename, e);
return Err(anyhow::anyhow!("Failed to read migration file {}: {}", filename, e));
}
};
let sql_with_schema = if schema != "public" {
sql_content
.replace("public.", &format!("{}.", schema))
.replace("public::", &format!("{}::", schema))
} else {
sql_content.clone()
};
let checksum = format!("{:x}", md5::compute(&sql_content));
match sqlx::query(&sql_with_schema).execute(pool).await {
Ok(_) => {
let duration_ms = file_start.elapsed().as_millis() as i32;
sqlx::query(
"INSERT INTO schema_migrations (filename, checksum, duration_ms)
VALUES ($1, $2, $3)"
)
.bind(&filename)
.bind(&checksum)
.bind(duration_ms)
.execute(pool)
.await?;
tracing::info!("✓ Applied {} ({}ms)", filename, duration_ms);
applied_count += 1;
}
Err(e) => {
tracing::error!("✗ Failed to apply {}: {}", filename, e);
return Err(anyhow::anyhow!("Migration failed: {} - {}", filename, e));
}
}
}
tracing::info!("SQL migrations: {} applied, {} skipped", applied_count, skipped_count);
} else {
tracing::warn!("No migrations/ directory found, skipping SQL file migrations");
}
tracing::info!("Database migrations completed.");