fix(db): 改用 inspect 跳過現有 table,根治 CrashLoopBackOff
Some checks failed
CD Pipeline / build-and-deploy (push) Failing after 14m42s

checkfirst=True 只跳過 CREATE TABLE,SQLAlchemy 2.0 仍對
__table_args__ Index 物件發出獨立 CREATE INDEX → duplicate error。
改法:先 inspect 取得現有 tables,只對不存在的 table 呼叫
table.create(),index 永遠只隨新 table 建立,不再 duplicate。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
OG T
2026-04-15 15:18:19 +08:00
parent 8997ba70cb
commit 0f2ec7987c

View File

@@ -144,9 +144,19 @@ async def init_db() -> None:
"""
engine = get_engine()
async with engine.begin() as conn:
# checkfirst=True: 存在的 table/index 直接跳過,避免 rolling update 重啟時
# "relation already exists" CrashLoopBackOff2026-04-15 Claude Sonnet 4.6 Phase 3 修復)
await conn.run_sync(lambda c: Base.metadata.create_all(c, checkfirst=True))
# SQLAlchemy 2.0 問題create_all(checkfirst=True) 跳過 CREATE TABLE
# 但仍對 __table_args__ Index 物件發出獨立 CREATE INDEX → CrashLoopBackOff
# 修法:先 inspect 取得現有 tables只對不存在的 table 呼叫 table.create()
# 這樣 index 只隨新 table 一起建立,永遠不會 duplicate
# 2026-04-15 Claude Sonnet 4.6亞太Phase 3 修復
def _create_missing_tables(sync_conn):
from sqlalchemy import inspect as sa_inspect
existing = set(sa_inspect(sync_conn).get_table_names())
for table in Base.metadata.sorted_tables:
if table.name not in existing:
table.create(sync_conn)
await conn.run_sync(_create_missing_tables)
# 2026-04-02 Claude Code: 確保 risklevel enum 包含 'high' 值
# Phase 23 新增,避免舊 DB 缺少此值導致 InvalidTextRepresentation