65 lines
3.2 KiB
Python
65 lines
3.2 KiB
Python
"""老库列级对齐: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"),
|
||
)
|
||
|
||
|
||
def drop_stale_columns(engine: Engine) -> list[str]:
|
||
"""删除 STALE_COLUMNS 里登记的残留列,返回实际删掉的(表.列)。幂等。"""
|
||
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
|
||
with engine.begin() as conn:
|
||
conn.execute(text(f"ALTER TABLE {table} DROP COLUMN {col}"))
|
||
dropped.append(f"{table}.{col}")
|
||
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
|