sqlscripts.py
1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""测试建库:按版本顺序执行仓库根目录 sql_script/ 下的全部脚本(和正式部署由 DBA 执行的是同一批文件)。
这样每次跑测试都在验证「脚本建出来的库 == app/models.py 的表定义」:两边不一致,启动检查(verify_schema)会直接报错。
"""
from __future__ import annotations
from pathlib import Path
SQL_ROOT = Path(__file__).resolve().parents[2] / "sql_script"
def _version_key(p: Path) -> tuple:
return tuple(int(x) if x.isdigit() else 0 for x in p.name.lstrip("vV").split("."))
def script_files() -> list[Path]:
dirs = sorted((d for d in SQL_ROOT.iterdir() if d.is_dir() and d.name[:1] in "vV"), key=_version_key)
return [f for d in dirs for f in sorted(d.glob("*.sql"))]
def split_sql(sql: str) -> list[str]:
"""按语句末尾的分号切分(引号里的分号、-- 注释行不算)。"""
out, buf, quote = [], [], ""
for line in sql.splitlines():
if not quote and line.lstrip().startswith("--"):
continue
for ch in line:
if quote:
if ch == quote:
quote = ""
elif ch in ("'", '"', "`"):
quote = ch
elif ch == ";":
stmt = "".join(buf).strip()
if stmt:
out.append(stmt)
buf = []
continue
buf.append(ch)
buf.append("\n")
tail = "".join(buf).strip()
if tail:
out.append(tail)
return out
def apply_all(engine) -> list[str]:
"""执行全部脚本,返回执行过的文件(相对 sql_script/)。"""
done = []
with engine.begin() as c:
for f in script_files():
for stmt in split_sql(f.read_text(encoding="utf-8")):
c.exec_driver_sql(stmt) # 不走 text():注释里的「restock:run:12」不能当成绑定参数
done.append(f.relative_to(SQL_ROOT).as_posix())
return done