146 lines
5.7 KiB
Python
146 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
||
"""由 SQLAlchemy 元数据生成 backend/sql/schema.sql(生产建库脚本)。
|
||
|
||
生产档把 auto_create_schema 关掉,建表交 DBA,跑的就是这份文件。既然不能手写,
|
||
就不能靠"谁记得手动重新生成"来保证它和模型一致——所以这里既当生成器,也当校验器:
|
||
|
||
python3 scripts/gen_schema.py # 重新生成 sql/schema.sql
|
||
python3 scripts/gen_schema.py --check # 只比对,不一致退出码 1(可挂 CI)
|
||
|
||
改完 app/models 记得重新生成,别手改 sql/schema.sql。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import re
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
from sqlalchemy.dialects import mysql # noqa: E402
|
||
from sqlalchemy.schema import CreateIndex, CreateTable # noqa: E402
|
||
|
||
import app.models # noqa: F401,E402 (触发模型注册)
|
||
from app.models.base import Base # noqa: E402
|
||
|
||
OUT_PATH = Path(__file__).resolve().parents[1] / "sql" / "schema.sql"
|
||
|
||
# SQLAlchemy 编译 CreateTable 时已经带上了 CHARSET/COLLATE,这里只补 ENGINE,
|
||
# 并把闭合括号后面的那一串选项统一成一种写法,免得两份 charset 打架
|
||
# (MySQL 会把 "utf8mb4_unicode_ciCHARSET=utf8mb4" 当成一个非法 collation 名)。
|
||
TABLE_OPTIONS = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
|
||
CLOSE_PAREN = re.compile(r"\n\)\s*[^\n]*$")
|
||
LINE = "-- " + "=" * 72
|
||
THIN = "-- " + "-" * 72
|
||
|
||
HEADER = f"""{LINE}
|
||
-- 四算项目管理系统(fourcal-pms)生产建表脚本
|
||
-- {THIN[3:]}
|
||
-- 生成方式:backend/scripts/gen_schema.py 由 SQLAlchemy 元数据编译
|
||
-- (CreateTable / CreateIndex + mysql dialect),因此这份 DDL 与
|
||
-- backend/app/models 里的模型定义一一对应,不会手写走样。
|
||
-- 改了模型请重新生成,不要手改本文件:
|
||
-- python3 backend/scripts/gen_schema.py
|
||
-- 比对是否走样(可挂 CI):
|
||
-- python3 backend/scripts/gen_schema.py --check
|
||
--
|
||
-- 已验证:在 MySQL 8 上建空库逐条执行全部语句通过(脚本末尾有校验查询)。
|
||
--
|
||
-- 什么时候用:生产环境把 config.prod.toml 的 auto_create_schema 设为 false,
|
||
-- 建表交 DBA,就跑这个文件。开发档(auto_create_schema=true)不需要它。
|
||
--
|
||
-- 用法:
|
||
-- mysql -h <host> -P <port> -u <user> -p < backend/sql/schema.sql
|
||
-- 或先自己建库再执行本文件(下面 CREATE DATABASE 默认注释掉,
|
||
-- 避免 DBA 用高权限账号跑脚本时误建库)。
|
||
--
|
||
-- 注意
|
||
-- 1. 本文件只建表,不种数据。基础数据(权限节点、角色、超管、演示流程)
|
||
-- 由后端首次启动时的 seed 流程写入,只在库里没有对应记录时生效。
|
||
-- 2. 老四算库 unis_fourcal_dev 不在本文件范围内,它是只读数据源,
|
||
-- 导数用 scripts/migrate_legacy.py。
|
||
-- 3. 字符集统一 utf8mb4 / utf8mb4_unicode_ci,金额列一律 DECIMAL,
|
||
-- 不要用 FLOAT/DOUBLE,也不要用 VARCHAR 存金额。
|
||
{LINE}
|
||
"""
|
||
|
||
|
||
def compile_ddl() -> tuple[list[str], list[str]]:
|
||
"""返回 (建表语句, 建索引语句),顺序按外键依赖排好。"""
|
||
dialect = mysql.dialect()
|
||
tables: list[str] = []
|
||
for table in Base.metadata.sorted_tables:
|
||
ddl = str(CreateTable(table).compile(dialect=dialect)).strip().rstrip(";")
|
||
tables.append(f"{CLOSE_PAREN.sub(chr(10) + ')', ddl, count=1)}{TABLE_OPTIONS};")
|
||
|
||
indexes: list[str] = []
|
||
for table in Base.metadata.sorted_tables:
|
||
for index in sorted(table.indexes, key=lambda item: item.name or ""):
|
||
indexes.append(
|
||
str(CreateIndex(index).compile(dialect=dialect)).rstrip().rstrip(";") + ";"
|
||
)
|
||
return tables, indexes
|
||
|
||
|
||
def render() -> str:
|
||
tables, indexes = compile_ddl()
|
||
parts = [HEADER, ""]
|
||
parts += [
|
||
"-- CREATE DATABASE IF NOT EXISTS `fourcal_pms`",
|
||
"-- DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;",
|
||
"-- USE `fourcal_pms`;",
|
||
"",
|
||
"SET NAMES utf8mb4;",
|
||
"SET FOREIGN_KEY_CHECKS = 0;",
|
||
"",
|
||
THIN,
|
||
f"-- 建表({len(tables)} 张,按依赖顺序)",
|
||
THIN,
|
||
"",
|
||
]
|
||
for ddl in tables:
|
||
parts += [ddl, ""]
|
||
parts += [THIN, f"-- 索引({len(indexes)} 条)", THIN, ""]
|
||
parts += [f"{ddl};" if not ddl.endswith(";") else ddl for ddl in indexes]
|
||
parts += [
|
||
"",
|
||
"SET FOREIGN_KEY_CHECKS = 1;",
|
||
"",
|
||
LINE,
|
||
f"-- 完。共 {len(tables)} 张表、{len(indexes)} 条索引语句。",
|
||
"-- 建完可以抽查一条确认口径:",
|
||
"-- SHOW CREATE TABLE project\\G",
|
||
"-- SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE();",
|
||
LINE,
|
||
"",
|
||
]
|
||
return "\n".join(parts)
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
parser = argparse.ArgumentParser(description="生成/校验生产建表脚本")
|
||
parser.add_argument("--check", action="store_true",
|
||
help="只比对现有 sql/schema.sql,不写文件")
|
||
opts = parser.parse_args(argv)
|
||
|
||
content = render()
|
||
tables, indexes = compile_ddl()
|
||
|
||
if opts.check:
|
||
current = OUT_PATH.read_text(encoding="utf-8") if OUT_PATH.exists() else ""
|
||
if current == content:
|
||
print(f"schema.sql 与模型一致({len(tables)} 张表 / {len(indexes)} 条索引)")
|
||
return 0
|
||
print("schema.sql 已走样,请重新运行:python3 scripts/gen_schema.py", file=sys.stderr)
|
||
return 1
|
||
|
||
OUT_PATH.write_text(content, encoding="utf-8")
|
||
print(f"已生成 {OUT_PATH}({len(tables)} 张表 / {len(indexes)} 条索引)")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|