am-freescan/scripts/build_bootstrap_assets.py
2026-10-22 16:18:37 +08:00

107 lines
4.7 KiB
Python

"""Offline extraction of DDL and whitelisted reference seeds from copied source SQL.
No database connection. No source INSERT for users, tenants, files, equipment,
tasks, results, credentials, logs or third-party configuration is retained.
"""
from pathlib import Path
import re
from bootstrap_db import split_sql
ROOT = Path(__file__).resolve().parents[1]
SQL = ROOT / "am-backend" / "sql"
OUT = SQL / "freescan"
LAB_ORDER = ["lab-master", "lab-task", "lab-resource", "lab-execution", "lab-artifact", "lab-result", "lab-document", "lab-integration", "lab-integration-provider", "lab-integration-v1-rc2", "lab-integration-v2", "lab-integration-failure-aggregate", "lab-fusion-02-09", "lab-scan-workflow-v1", "lab-scan-plan-multi-v1"]
def expressions(source):
result, chunk, quote, depth, i = [], [], None, 0, 0
while i < len(source):
ch = source[i]
if quote:
chunk.append(ch)
if ch == "\\" and i + 1 < len(source):
i += 1
chunk.append(source[i])
elif ch == quote:
quote = None
elif ch in "'\"`":
quote = ch
chunk.append(ch)
elif ch == "(":
depth += 1
chunk.append(ch)
elif ch == ")":
depth -= 1
chunk.append(ch)
elif ch == "," and depth == 0:
result.append("".join(chunk).strip())
chunk = []
else:
chunk.append(ch)
i += 1
if chunk:
result.append("".join(chunk).strip())
return result
def literal(value):
if value.startswith("'"):
return value[1:-1].replace("\\'", "'").replace("''", "'").replace('\\"', '"')
return value
def base_rows(source, table):
pattern = re.compile(r"INSERT INTO `" + table + r"`\s*\((.*?)\) VALUES \((.*)\)$", re.S)
for statement in split_sql(source):
match = pattern.match(statement)
if match:
columns = [v.strip().strip("`") for v in expressions(match.group(1))]
values = expressions(match.group(2))
yield dict(zip(columns, map(literal, values))), statement
def generate():
OUT.mkdir(parents=True, exist_ok=True)
dump = (SQL / "AM.sql").read_text(encoding="utf-8")
tables = {}
for match in re.finditer(r"(?ms)^CREATE TABLE `([a-z_0-9]+)`\s*\(.*?^\).*?;", dump):
table = match.group(1)
if not table.startswith(("system_", "infra_", "lab_")):
continue
ddl = match.group(0).replace("CREATE TABLE `", "CREATE TABLE IF NOT EXISTS `", 1)
ddl = re.sub(r"AUTO_INCREMENT\s*=\s*\d+", "", ddl)
tables[table] = ddl
(OUT / "001_schema.sql").write_text("-- Clean final schema only; no source rows or destructive statements.\n-- Source: sql/AM.sql DDL, reconciled with all current system/infra/lab DO fields.\n\n" + "\n\n".join(tables.values()) + "\n", encoding="utf-8")
base = (SQL / "mysql" / "ruoyi-vue-pro.sql").read_text(encoding="utf-8")
seed = ["-- Whitelist only: supported dictionaries, system/infra menus, lab roles/menus/dictionaries.", "-- No historical people, business master data, jobs, tokens, cloud or provider settings."]
dictionary_types = set()
for row, statement in base_rows(base, "system_dict_type"):
if row["type"].startswith(("system_", "infra_", "common_")):
dictionary_types.add(row["type"])
seed.append(statement.replace("INSERT INTO", "INSERT IGNORE INTO", 1) + ";")
for row, statement in base_rows(base, "system_dict_data"):
if row["dict_type"] in dictionary_types:
seed.append(statement.replace("INSERT INTO", "INSERT IGNORE INTO", 1) + ";")
menus = list(base_rows(base, "system_menu"))
keep = {"1", "2"}
while True:
extended = keep | {row["id"] for row, _ in menus if row["parent_id"] in keep}
if extended == keep:
break
keep = extended
for row, statement in menus:
if row["id"] in keep:
seed.append(statement.replace("INSERT INTO", "INSERT IGNORE INTO", 1) + ";")
allowed = r"(?:system_dict_type|system_dict_data|system_role|system_menu|system_role_menu)"
for file in LAB_ORDER:
seed.append(f"-- Reference changes from {file}.sql (DDL already merged in 001_schema.sql)")
for statement in split_sql((SQL / "mysql" / (file + ".sql")).read_text(encoding="utf-8")):
if re.match(r"(?:INSERT INTO|UPDATE) `" + allowed + r"`", statement):
seed.append(statement + ";")
(OUT / "002_reference_seeds.sql").write_text("\n\n".join(seed) + "\n", encoding="utf-8")
print(f"Generated {len(tables)} clean tables and {len(seed)} reference statements/comments; no database connection")
if __name__ == "__main__":
generate()