unis-oa/backend/scripts/check_schema_snapshot.py

114 lines
5.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Fail when sql/schema.sql no longer matches app/models.py.
为什么要卡这一关:生产库交给 DBA 时 ``[database] auto_create_schema=false``,表结构
全靠 ``sql/schema.sql`` 手工建,后端启动不再补列。快照落后模型一列,新建的库第一次
登录就撞 ``(1054, "Unknown column 'last_used_at' in 'field list'")`` —— 2026-10 那次
``oa_refresh_token.last_used_at`` 就是这么炸的:``models.py`` 加了列、测试库被启动时的
``ensure_columns()`` 悄悄补好了,于是本机一切正常,快照却没人管。
规矩写在 docs/architecture.md:改完 ``models.py`` 跑一次
``python3 scripts/dump_schema.py`` 重新导出。这个脚本就是防人忘的,比它对一遍比谁记性都稳。
不连数据库:解析快照文本 + 读 SQLAlchemy 元数据,离线就能跑。索引只按"列的组合"对,
不比索引名——MySQL 会给 ``unique=True`` 的列自己起名(``token_hash``、``name``……),
比名字全是假警报。
跑在 backend 目录下::
python3 scripts/check_schema_snapshot.py
"""
from __future__ import annotations
import pathlib
import re
import sys
BASE_DIR = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BASE_DIR))
SCHEMA_SQL = BASE_DIR.parent / "sql" / "schema.sql"
#: CREATE TABLE 块:表名 + 括号里的正文(正文里没有单独一行的右括号,见 SHOW CREATE TABLE 输出)
TABLE_BLOCK = re.compile(r"CREATE TABLE `(?P<name>[^`]+)` \((?P<body>.*?)\n\) ENGINE", re.S)
#: 正文里以反引号开头的行一定是列(索引、约束都以 PRIMARY/KEY/UNIQUE/CONSTRAINT/INDEX 开头)
COLUMN_LINE = re.compile(r"^\s+`(?P<name>[^`]+)`\s+\S", re.M)
#: KEY `名字` (`a`,`b`) / UNIQUE KEY `名字` (`a`,`b`)
KEY_LINE = re.compile(r"^\s+(?:UNIQUE\s+)?KEY\s+`[^`]+`\s*\((?P<cols>[^)]*)\)", re.M)
def snapshot_tables(text: str) -> dict[str, tuple[set[str], set[tuple[str, ...]]]]:
"""快照里的 表 -> (列名集合, 索引覆盖的列组合)。"""
tables: dict[str, tuple[set[str], set[tuple[str, ...]]]] = {}
for match in TABLE_BLOCK.finditer(text):
body = match.group("body")
columns = set(COLUMN_LINE.findall(body))
indexes: set[tuple[str, ...]] = set()
for raw in KEY_LINE.findall(body):
cols = tuple(re.findall(r"`([^`]+)`", raw))
if cols:
indexes.add(cols)
tables[match.group("name")] = (columns, indexes)
return tables
def model_tables() -> dict[str, tuple[set[str], set[tuple[str, ...]]]]:
"""模型里的 表 -> (列名集合, 索引/唯一约束覆盖的列组合)。"""
from app import models # noqa: F401 (注册 mapper,元数据才全)
from app.db import Base
tables: dict[str, tuple[set[str], set[tuple[str, ...]]]] = {}
for table in Base.metadata.sorted_tables:
indexes = {tuple(c.name for c in index.columns) for index in table.indexes}
from sqlalchemy import UniqueConstraint
for constraint in table.constraints:
if isinstance(constraint, UniqueConstraint):
cols = tuple(c.name for c in constraint.columns)
if cols:
indexes.add(cols)
tables[table.name] = ({c.name for c in table.columns}, indexes)
return tables
def compare(snapshot: dict, model: dict) -> list[str]:
"""返回"要改什么"的人话清单,空列表代表快照可信。"""
problems: list[str] = []
for name in sorted(set(model) - set(snapshot)):
problems.append(f"快照里缺表 {name}(模型有,实库大概是没建过)")
for name in sorted(set(snapshot) - set(model)):
problems.append(f"快照里多表 {name}(模型已删除,快照没重新导出)")
for name in sorted(set(snapshot) & set(model)):
snap_cols, snap_idx = snapshot[name]
model_cols, model_idx = model[name]
if missing := sorted(model_cols - snap_cols):
problems.append(f"{name} 快照缺列:{', '.join(missing)}")
if extra := sorted(snap_cols - model_cols):
problems.append(f"{name} 快照多列(模型已删除):{', '.join(extra)}")
if missing_idx := sorted(model_idx - snap_idx):
problems.append(
f"{name} 快照缺索引:{';'.join('`' + '`+`'.join(cols) + '`' for cols in missing_idx)}"
)
return problems
def main(argv: list[str]) -> int:
target = pathlib.Path(argv[0]) if argv else SCHEMA_SQL
if not target.exists():
print(f"[FAIL] 找不到结构快照:{target}")
return 1
snapshot = snapshot_tables(target.read_text(encoding="utf-8"))
model = model_tables()
problems = compare(snapshot, model)
for item in problems:
print(f"[FAIL] {item}")
if problems:
print(f"共 {len(problems)} 处结构快照与模型不一致,请跑 python3 scripts/dump_schema.py 重新导出 {target}")
return 1
print(f"通过:{target.name} 与 models.py 一致({len(model)} 张表)")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))