"""老库列级对齐:create_all 只会建新表,不会给已存在的表加字段,也不会删字段。 - 模型新增可空字段后(如定制项目的验收时间 / 开票 / 回款),启动时自动 `ALTER TABLE ... ADD COLUMN` 补齐:`ensure_columns(engine, Base.metadata)`。 - 模型删掉的死字段(历史上如 currency / sort_order / periods 起止日期)用 `drop_stale_columns(engine)` 定点清除——只删下方白名单里明确列出的列, 不做「模型没有就删」的全量对账,避免误伤老库里来历不明的列。 不清理的后果:NOT NULL 列没了默认值来源,INSERT 会直接约束失败。 需要 SQLite ≥ 3.35(DROP COLUMN),低版本跳过并在启动日志提示。 """ from __future__ import annotations from sqlalchemy import inspect, text from sqlalchemy.engine import Engine from sqlalchemy.sql.schema import MetaData # 已在模型中删除、但老库里可能残留的死列(表名, 列名)。删掉模型字段时同步登记到这里。 STALE_COLUMNS: tuple[tuple[str, str], ...] = ( ("custom_projects", "currency"), # 外币折算从未落地,Python 端 default 一删,老库 INSERT 会撞 NOT NULL ("tasks", "sort_order"), # 子任务实际按 id 排序,此列只写不读 ("periods", "start_date"), # 周期起止由 year/month/week 推导,两列从未被读取 ("periods", "end_date"), ("projects", "priority"), # 优先级无界面读写,导出恒为 P2(NOT NULL 列,必须清) ("projects", "description"), ) def drop_stale_columns(engine: Engine) -> list[str]: """删除 STALE_COLUMNS 里登记的残留列,返回实际删掉的(表.列)。幂等。 这个函数在 main.py 导入期执行,任何一列失败都不能掀翻整个服务: 索引 / UNIQUE / 视图引用会让 DROP COLUMN 报错(老库常态),逐列 try 后跳过即可—— 死列留着不碍业务,服务起不来才碍。 """ if engine.dialect.name != "sqlite": # MySQL 等目标库不做 SQLite 式清列 return [] from sqlite3 import sqlite_version_info # 先看驱动能力,低版本直接跳过 if sqlite_version_info < (3, 35): print("[warn] SQLite < 3.35 不支持 DROP COLUMN,死列保留(不影响功能,只是占位)") return [] insp = inspect(engine) dropped: list[str] = [] for table, col in STALE_COLUMNS: if not insp.has_table(table): continue if col not in {c["name"] for c in insp.get_columns(table)}: continue try: with engine.begin() as conn: conn.execute(text(f"ALTER TABLE {table} DROP COLUMN {col}")) dropped.append(f"{table}.{col}") except Exception as e: # 索引/UNIQUE/视图引用等:留着死列继续启动,日志说清人话 print(f"[warn] 跳过死列 {table}.{col}:删不掉({e}),不影响使用") return dropped def ensure_columns(engine: Engine, metadata: MetaData) -> list[str]: """给已存在的表补上模型里新增的可空字段,返回补过的列名(表.列)。""" insp = inspect(engine) added: list[str] = [] for table in metadata.tables.values(): if not insp.has_table(table.name): continue # 表还不存在 → create_all 会按最新模型建,这里不用管 existing = {c["name"] for c in insp.get_columns(table.name)} for col in table.columns: if col.name in existing: continue if not col.nullable: print(f"[warn] 跳过高字段 {table.name}.{col.name}:新增列需允许为空") continue ddl = col.type.compile(engine.dialect) with engine.begin() as conn: conn.execute(text(f"ALTER TABLE {table.name} ADD COLUMN {col.name} {ddl} NULL")) added.append(f"{table.name}.{col.name}") return added