from __future__ import annotations from sqlalchemy import Engine, text from app.db.models import Base def _has_column(conn, table: str, col: str) -> bool: rows = conn.execute(text(f"PRAGMA table_info({table})")).fetchall() return any(r[1] == col for r in rows) # PRAGMA columns: (cid, name, type, notnull, dflt_value, pk) def ensure_schema(engine: Engine) -> None: """ SQLite 轻量自升级: - create_all 不会更新既有表结构,因此用 PRAGMA + ALTER TABLE 补列 - 必须保证任何失败都不影响主流程(上层可选择忽略异常) """ Base.metadata.create_all(bind=engine) with engine.begin() as conn: # job_logs.run_log if not _has_column(conn, "job_logs", "run_log"): conn.execute(text("ALTER TABLE job_logs ADD COLUMN run_log TEXT NOT NULL DEFAULT ''"))