fix(db): 補全 metadata model import 與 realtime sales ORM

ADR-017 Phase 3f-0
This commit is contained in:
OoO
2026-04-29 21:00:46 +08:00
parent 8be332728e
commit f4149d4c05
12 changed files with 314 additions and 27 deletions

View File

@@ -0,0 +1,29 @@
# DB Metadata Import 鐵律
## 問題
`Base.metadata.create_all()` 只會建立已載入 metadata 的 model。若 model 檔沒有被 `database/manager.py` 或其他啟動必經路徑 import新環境就會漏表但既有環境可能因舊資料庫已存在而掩蓋問題。
## 鐵律
1. 新增 SQLAlchemy model 時,必須在 `database/manager.py` 顯式 import。
2. 禁止依賴 re-export shim 或副作用 import 讓 table 偷偷進 metadata。
3. 若 init SQL 已有表,仍要補 ORM 或在 ADR 中明確說明為外部管理表。
4. `app.py` 啟動 self-check 的 expected table 清單要同步更新。
5. 新環境驗收要跑:
```bash
python3 - <<'PY'
from database.manager import Base
print(len(Base.metadata.tables))
print(sorted(Base.metadata.tables))
PY
```
## Phase 3f-0 決策
- `database/manager.py` 顯式載入 permission、AI history、autoheal、import、notification、PPT、vendor、realtime sales models。
- `database/ai_models.py` 移除 autoheal re-export shim需要 autoheal model 的程式必須直接 import `database.autoheal_models`
- `database/realtime_sales_models.py``realtime_sales_monthly` ORM讓 metrics、匯入與啟動自檢有同一份 metadata 來源。
- PostgreSQL `create_all()` 必須經 process-local guard 與 advisory lock避免多 worker 或多次 `DatabaseManager()` 在一般流程重複做 DDL 檢查。
- ORM 若對齊 init SQL 管理的表,必須同步 `docker/postgres/init/01-init.sql`,因 `create_all()` 不會 alter 已存在的窄表。