# -*- coding: utf-8 -*- """testdata —— 造价审核 测试数据生成器(核心引擎,2026-10-09)。 定位:放在 release/ 下的独立工具,**不改任何软件代码、不碰真实库**。 写入目标是独立测试库文件 history-test.db(后台)与 session-test.db(工作台); 测试库首次生成时从同名真实库克隆底子(schema/设置随带)。主人对接软件时 自行把测试库改名换上去即可,真实数据零污染。所有数据 Name 带「测试」前缀 + is_mock=1(批次库)双标记。删除走本文件的分块循环(每块 2 万个批次 id), **不依赖后台内置「清空模拟数据」按钮**——那条 SQL 一次绑定全部 id,批次数超过 SQLite 变量上限(32766)会直接报错。 随母体变化目录:全部相对定位。从本文件位置逐级向上找 <某级>/CostReview/data/history.db (工作区或包内) <某级>/PricingReview*/CostReview/data/history.db(绿色包改名也能找到) 找到即随包整体挪走照常用;界面里也可手动指定数据目录(存 config.json)。 命令行: python gen_testdata.py --check # 统计现有测试数据 python gen_testdata.py --run run_cfg.json # 按参数生成(控制台写这份 json) python gen_testdata.py --bench # 性能体检:只读实测母体热点查询耗时 python gen_testdata.py --delete --yes # 分块删除全部测试数据(含附件文件) python gen_testdata.py --delete --yes --keep-files # 只删库行不删附件文件 测「数据库上限」的方法(2026-10-11):从小到大逐级生成(如 1千 → 5千 → 1万 → 5万 项目),每级跑一次 --bench,哪条查询突破可接受阈值(如 1 秒),哪里就是软件的实际 容量上限。体检结果自动追加存档 bench_history.jsonl,逐级对比即可画曲线。 """ import argparse import glob import hashlib import json import os import random import re import shutil import sqlite3 import sys import time def _safe_stdio(): """Windows GBK 控制台兜底:路径里的 U+200C 等字符编码不了时替换成 ?,不崩。""" for s in (sys.stdout, sys.stderr): try: s.reconfigure(errors="replace") except Exception: pass _safe_stdio() def _disp(p): """仅用于显示的路径:剔掉零宽字符(工作区路径 review 后带 U+200C)。""" return (p or "").replace("\u200c", "") HERE = os.path.dirname(os.path.abspath(__file__)) CFG_PATH = os.path.join(HERE, "config.json") RUN_CFG = os.path.join(HERE, "run_cfg.json") PAUSE_FLAG = os.path.join(HERE, "pause.flag") CHUNK = 20000 # 每块删除的批次/会话 id 数(远离 32766 上限) PARSER_VER_FALLBACK = "2026.10.08-1" # ---------------- 定位数据目录(随母体变化目录) ---------------- REAL_H = "history.db" TEST_H = "history-test.db" # 后台测试库(主人定的隔离文件名) TEST_S = "session-test.db" # 工作台测试库 def _has_anchor(d): return (os.path.exists(os.path.join(d, REAL_H)) or os.path.exists(os.path.join(d, TEST_H))) REF_DIR = None # 参考库目录(None = 与数据目录同目录) def db_paths(dd): """返回 (真实history, 测试history, 真实session, 测试session) 四个绝对路径。 参考库可在独立目录(REF_DIR);测试库与附件一律落在数据目录 dd。""" rd = REF_DIR or dd return (os.path.join(rd, REAL_H), os.path.join(dd, TEST_H), os.path.join(rd, "session.db"), os.path.join(dd, TEST_S)) def ensure_test_dbs(dd, log=print): """测试库不存在时从同名真实库克隆(schema/索引/设置随底子带上)。 真实库本体绝不打开写。返回 (测试history路径, 测试session路径)。""" rh, th, rs, ts = db_paths(dd) if not os.path.exists(th): if not os.path.exists(rh): raise SystemExit("!! 参考目录里没有 %s(参考目录:%s),无法建测试库" % (REAL_H, _disp(os.path.dirname(rh) or dd))) os.makedirs(dd, exist_ok=True) # 测试库独立目录可能还不存在 s = sqlite3.connect(rh) d = sqlite3.connect(th) s.backup(d) d.close() s.close() log("已从 %s 克隆出测试库 %s(真实库未动)" % (REAL_H, TEST_H)) if not os.path.exists(ts) and os.path.exists(rs): s = sqlite3.connect(rs) d = sqlite3.connect(ts) s.backup(d) d.close() s.close() log("已从 session.db 克隆出测试库 %s(真实库未动)" % TEST_S) return th, ts def find_data_dir(): if os.path.exists(CFG_PATH): try: with open(CFG_PATH, encoding="utf-8") as f: p = (json.load(f) or {}).get("data_dir") or "" if p and _has_anchor(p): return os.path.normpath(p) except Exception: pass d = HERE for _ in range(8): cand = os.path.join(d, "CostReview", "data") if _has_anchor(cand): return cand pat = os.path.join(d, "PricingReview*", "CostReview", "data") for g in glob.glob(pat): if _has_anchor(g): return g nd = os.path.dirname(d) if nd == d: break d = nd return None def set_data_dir(p, ref_dir=None): cfg = {} if os.path.exists(CFG_PATH): try: with open(CFG_PATH, encoding="utf-8") as f: cfg = json.load(f) or {} except Exception: cfg = {} cfg["data_dir"] = p if ref_dir is not None: cfg["ref_dir"] = ref_dir tmp = CFG_PATH + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=2) os.replace(tmp, CFG_PATH) # ---------------- 归一化 / 哈希(复刻 core/import_job.py 口径) ---------------- def norm(s): s = (s or "").strip() s = s.replace("(", "(").replace(")", ")").replace(",", ",").replace(";", ";") s = s.replace("×", "*").replace("*", "*").replace("X", "*").replace("x", "*") s = s.replace("㎡", "m2").replace("m²", "m2").replace("m2", "m2") s = re.sub(r"\s+", "", s) return s.lower() def md5(*parts): return hashlib.md5("|".join(norm(p) for p in parts).encode("utf-8")).hexdigest() def clean_attr(s): t = norm(s) t = re.sub(r"(?= 6] except Exception: out["stems"] = [] try: rows = con.execute("SELECT Number, Name, Unit FROM norms LIMIT 4000").fetchall() seen, nm = set(), [] for r in rows: if r[0] and r[1] and r[0] not in seen: seen.add(r[0]) nm.append((r[0], r[1], r[2] or "项")) out["norms"] = nm except Exception: out["norms"] = [] try: rows = con.execute( "SELECT Number, Name, Specification, Unit, Kind, TaxPrice FROM lmes " "WHERE Name IS NOT NULL AND Name <> '' LIMIT 60000").fetchall() seen, lm = set(), [] for r in rows: if r[1] and r[1] not in seen: seen.add(r[1]) lm.append((r[0] or "", r[1], r[2] or "", r[3] or "项", r[4] or 2, r[5] or 0)) out["lmes"] = lm except Exception: out["lmes"] = [] try: rows = con.execute( "SELECT DISTINCT BulidUnit FROM batches WHERE BulidUnit IS NOT NULL " "AND BulidUnit <> '' AND is_mock=0 LIMIT 300").fetchall() out["builders"] = [r[0] for r in rows] except Exception: out["builders"] = [] return out class Words: """词料聚合:真实优先、内置兜底。""" def __init__(self, con): h = harvest(con) self.stems = h["stems"] or PROJECT_STEMS self.norms = (h["norms"] if len(h["norms"]) >= 12 else []) or NORM_ITEMS self.lmes = (h["lmes"] if len(h["lmes"]) >= 60 else []) or LME_BUILTIN self.builders = h["builders"] or [gen_builder(random.Random(i)) for i in range(80)] self.norm_ix, self.hint_ix = build_norm_index(self.norms) # ---------------- 附件文件(名字确定性 → 重跑原地覆盖,不累积孤儿文件) ---------------- def _fake_bytes(fname, lo=1024, hi=6144): ext = fname.rsplit(".", 1)[-1].lower() if ext == "pdf": head = b"%PDF-1.4\n" elif ext in ("zip", "rar", "xlsx", "docx"): head = b"PK\x03\x04" if ext != "rar" else b"Rar!\x1a\x07" else: head = b"" return head + (b"\ntestdata sample: " + fname.encode("utf-8") + b"\n") \ + os.urandom(random.randint(lo, hi)) def write_file_rel(data_dir, subdir, sha, fname): d = os.path.join(data_dir, subdir, sha[:2]) os.makedirs(d, exist_ok=True) fn = "%s_%s" % (sha, fname) p = os.path.join(d, fn) if not os.path.exists(p): with open(p, "wb") as f: f.write(_fake_bytes(fname)) return os.path.join(subdir, sha[:2], fn) def del_file(data_dir, rel): """安全删文件:只动 data 目录内、且文件名以 sha 前缀开头的生成物。""" try: p = os.path.join(data_dir, rel) if os.path.isfile(p) and os.path.basename(p)[:2] == os.path.basename(os.path.dirname(p)) \ and "_" in os.path.basename(p): os.remove(p) except Exception: pass # ---------------- 默认参数 ---------------- DEFAULTS = { "n_project": 10, "bill_lo": 300, "bill_hi": 800, "norm_lo": 3, "norm_hi": 5, "res_lo": 3, "res_hi": 5, "inq_per_project": 4, "bind_rate": 50, "n_market": 20, "market_lo": 500, "market_hi": 800, "market_attach_rate": 80, "n_info": 20, "info_lo": 500, "info_hi": 800, "info_attach_rate": 90, "session_linked": True, "n_session": 5, "sbill_lo": 150, "sbill_hi": 400, "from_ym": "2024-01", "to_ym": "2026-10", } # ---------------- 小工具 ---------------- def _ym_range(cfg): def _m(s): y, mo = str(s).split("-") return int(y) * 12 + int(mo) a, b = _m(cfg["from_ym"]), _m(cfg["to_ym"]) if a > b: a, b = b, a return a, b def _rand_ym(rng, a, b): m = rng.randint(a, b) return (m // 12, m % 12, m) def _rand_dt(rng, a, b): y, mo, _ = _rand_ym(rng, a, b) return "%04d-%02d-%02d %02d:%02d:%02d" % ( y, mo, rng.randint(1, 28), rng.randint(8, 18), rng.randint(0, 59), rng.randint(0, 59)) def _qty_for_unit(rng, unit): u = unit or "" if u in ("m2", "m²", "㎡"): return round(rng.uniform(50, 2600), 2) if u == "m3": return round(rng.uniform(20, 900), 2) if u == "m": return round(rng.uniform(10, 1200), 2) if u == "t": return round(rng.uniform(0.5, 220), 2) return round(rng.uniform(1, 80), 2) def _res_qty(rng, kind): if kind == 1: return round(rng.uniform(0.05, 2.5), 3) if kind == 3: return round(rng.uniform(0.02, 1.2), 3) return round(rng.uniform(0.1, 150), 2) PARSER_VER_PRICE_FALLBACK = "2026.10.02-1" # 价格解析器兜底(读不到母体源码时用) def _parser_vers(dd): """从母体 app 源码读当前解析器版本(工程/价格两条线)。 stale_batches() 按 kind 分开比,生成器必须同样分开盖版本号,否则全部误报过期。""" proj, price = PARSER_VER_FALLBACK, PARSER_VER_PRICE_FALLBACK bases = [os.path.dirname(dd)] if REF_DIR: rb = os.path.dirname(REF_DIR) if rb not in bases: bases.append(rb) # 测试库在自定义目录时,参考库旁才是母体 for base in bases: core = os.path.join(base, "app", "core") for fname, defv in (("import_job.py", "proj"), ("price_html.py", "price")): try: txt = open(os.path.join(core, fname), encoding="utf-8").read() m = re.search(r"PARSER_VER\s*=\s*['\"]([^'\"]+)", txt) if m: if defv == "proj": proj = m.group(1) else: price = m.group(1) except Exception: pass if proj != PARSER_VER_FALLBACK and price != PARSER_VER_PRICE_FALLBACK: break return proj, price def _paused(): return os.path.exists(PAUSE_FLAG) def _open_db(path, bulk=False): """bulk=False:常规读写(版本对齐等小批量写,含可能打开真实库)——保守参数。 bulk=True:仅用于测试库批量生成——synchronous=OFF(测试数据可再生,断电大不了重来) + 关自动 checkpoint(实测 2GB 库上每次 commit 触发 checkpoint 要 7s,百兆脏页随机 回拷是生成最大拖累;关掉后 commit 0.1s,WAL 增长由 _ckpt 每 10 份做一次 PASSIVE 兜底,收尾 run() 再 TRUNCATE 清干净)。""" con = sqlite3.connect(path, timeout=60) con.execute("PRAGMA busy_timeout=30000") con.execute("PRAGMA cache_size=-65536") con.execute("PRAGMA temp_store=MEMORY") if bulk: con.execute("PRAGMA synchronous=OFF") con.execute("PRAGMA wal_autocheckpoint=0") con.execute("PRAGMA cache_size=-262144") # 256MB:索引页散布全库,缓存大些少读盘 else: # WAL 下 NORMAL 进程崩溃不丢数据(仅断电才可能丢最后一笔),大批量插入也明显提速 con.execute("PRAGMA synchronous=NORMAL") return con def _open_ro(path, timeout=3): """只读打开,短超时:库被其它进程(造价审核软件 / 生成子进程)占用时快速失败返回 None,绝不死等。原 stats_of/totals_of 用 15~30s 超时,会导致面板整页卡死。""" try: con = sqlite3.connect("file:%s?mode=ro" % path.replace("\\", "/"), uri=True, timeout=timeout) con.execute("PRAGMA busy_timeout=%d" % int(timeout * 1000)) return con except Exception: return None _CKPT_N = [0] # 跨生成阶段的调用计数 def _ckpt(con, every=10): """生成中定期 PASSIVE checkpoint:面板统计等读者会挡住 auto-checkpoint, WAL 会无限膨胀(实测 1000 项目攒出 6.7GB,后续生成恢复时被锁死)。 每 every 次调用做一次,失败静默(checkpoint 只是保健,不值得中断生成)。""" _CKPT_N[0] += 1 if _CKPT_N[0] % every: return try: con.execute("PRAGMA wal_checkpoint(PASSIVE)") except Exception: pass def _merge(st, add): """统计累加:分块/多阶段各自返回新字典,st.update 会覆盖(只留最后一块), 汇总数字必然失真——必须逐键相加。""" for k, v in add.items(): st[k] = st.get(k, 0) + v return st def _db_mb(p): """库文件体积(含 -wal/-shm),MB。""" n = 0.0 for e in ("", "-wal", "-shm"): try: n += os.path.getsize(p + e) except OSError: pass return n / 1048576.0 # ---------------- 结构级插入(history 与 session 两库共用一份逻辑数据) ---------------- # 逻辑行里的 owner 索引是本地序号,插入时映射为真实 id。 SQL_H = { "sec": "INSERT INTO sections(batch_id, Number, Name, Total, Ratios) VALUES(?,?,?,?,?)", "uw": "INSERT INTO unit_works(batch_id, Number, Name, Specialty, Total, section_id," " Construction, DivisionalAndElementalWorks, Preliminaries, CostForHSE," " SundryCosts, Tax) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", "div": "INSERT INTO divides(batch_id, uw_id, parent_id, Kind, Number, Name, Total," " Code, x_seq) VALUES(?,?,?,?,?,?,?,?,?)", "bill": "INSERT INTO bills(batch_id, uw_id, div_id, Number, Name, Attr, Unit, Quantity," " Price, Total, Kind, src_remark, x_name_norm, x_attr_norm, x_unit_norm," " x_hash_exact, x_hash_semi, x_seq, x_period_start_m, x_period_end_m)" " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "norm": "INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total)" " VALUES(?,?,?,?,?,?,?)", "res": "INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)", "lme": "INSERT INTO lmes(batch_id, Number, Name, Specification, Unit, Quantity," " NoTaxPrice, TaxRate, TaxPrice, Kind, x_name_norm, x_spec_norm, x_unit_norm," " x_hash_exact, x_period_start_m, x_period_end_m) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "lib": "INSERT INTO lme_lib(batch_id, code, name, spec, unit, kind, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?)", "proj": "INSERT INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?,?)", } SQL_S = { "sec": "INSERT INTO s_sections(session_id, Number, Name, Total, Ratios) VALUES(?,?,?,?,?)", "uw": "INSERT INTO s_unit_works(session_id, Number, Name, Specialty, Total, section_id," " Construction, DivisionalAndElementalWorks, Preliminaries, CostForHSE," " SundryCosts, Tax) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", "div": "INSERT INTO s_divides(session_id, uw_id, parent_id, Kind, Number, Name, Total," " Code, x_seq) VALUES(?,?,?,?,?,?,?,?,?)", "bill": "INSERT INTO s_bills(session_id, uw_id, div_id, Number, Name, Attr, Unit, Quantity," " Price, Total, Kind, src_remark, x_name_norm, x_attr_norm, x_unit_norm," " x_hash_exact, x_hash_semi, x_seq) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "norm": "INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total)" " VALUES(?,?,?,?,?,?,?)", "res": "INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)", "lme": "INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit, Quantity," " NoTaxPrice, TaxRate, TaxPrice, Kind, x_name_norm, x_spec_norm, x_unit_norm," " x_hash_exact) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "lib": "INSERT INTO s_lme_lib(session_id, code, name, spec, unit, kind, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?)", "proj": "INSERT INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?,?)", } def _cols(con, t): return {r[1] for r in con.execute("PRAGMA table_info(%s)" % t)} def _dyn_sql(con, pfx, what, ym): """按库实际列拼 bills/lmes 的 INSERT —— 兼容新旧母体(如旧库无 src_remark)。""" t = pfx + "bills" if what == "bill" else pfx + "lmes" have = _cols(con, t) owner = "batch_id" if pfx == "" else "session_id" if what == "bill": cols = [owner, "uw_id", "div_id", "Number", "Name", "Attr", "Unit", "Quantity", "Price", "Total", "Kind"] nfixed = 11 if "src_remark" in have: cols.append("src_remark") nfixed = 12 cols += ["x_name_norm", "x_attr_norm", "x_unit_norm", "x_hash_exact", "x_hash_semi", "x_seq"] nfixed += 6 if pfx == "" and "x_period_start_m" in have: cols += ["x_period_start_m", "x_period_end_m"] nfixed += 2 else: cols = [owner, "Number", "Name", "Specification", "Unit", "Quantity", "NoTaxPrice", "TaxRate", "TaxPrice", "Kind", "x_name_norm", "x_spec_norm", "x_unit_norm", "x_hash_exact"] nfixed = 14 if pfx == "" and "x_period_start_m" in have: cols += ["x_period_start_m", "x_period_end_m"] nfixed += 2 has_srcrem = "src_remark" in cols has_period = "x_period_start_m" in cols return ("INSERT INTO %s(%s) VALUES(%s)" % (t, ",".join(cols), ",".join("?" * len(cols)))), has_srcrem, has_period def insert_tree(con, sqls, owner_id, data, ym=None): """把一份逻辑结构写进指定库(列按库实际情况自适应)。 history 传 ym;session 不传。bill_ids 顺序与 data["norms"] 一一对应。""" cur = con.cursor() pfx = "" if sqls is SQL_H else "s_" bill_sql, sr, pd = _dyn_sql(con, pfx, "bill", ym) lme_sql, _, pdl = _dyn_sql(con, pfx, "lme", ym) sec_map, uw_map, div_map = {}, {}, {} for row in data["secs"]: # (本地序号, Number, Name, Total, Ratios) cur.execute(sqls["sec"], (owner_id,) + tuple(row[1:])) sec_map[row[0]] = cur.lastrowid for row in data["uws"]: vals = [owner_id, row[1], row[2], row[3], row[4], sec_map.get(row[5])] + list(row[6:]) cur.execute(sqls["uw"], vals) uw_map[row[0]] = cur.lastrowid for row in data["divs"]: cur.execute(sqls["div"], (owner_id, uw_map.get(row[0]), 0, row[1], row[2], row[3], row[4], row[5], row[6])) div_map[(row[0], row[6])] = cur.lastrowid bill_ids = [] for row in data["bills"]: # 逻辑行:(本地uw, (本地uw,div序号), Number, Name, Attr, Unit, Qty, Price, # Total, Kind, src_remark, x_seq) vals = [owner_id, uw_map.get(row[0]), div_map.get(row[1]), row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]] if sr: # 库里有 src_remark vals.append(row[10]) vals += [norm(row[3]), clean_attr(row[4]), norm(row[5]), md5(row[2], row[3], row[5]), md5(row[2], row[5]), row[11]] if pd: # history 库带期次两列 vals += [ym, ym] cur.execute(bill_sql, vals) bill_ids.append(cur.lastrowid) data["bill_ids"] = bill_ids # 定额逐条插(要 lastrowid 挂消耗),消耗行攒齐一个项目一次 executemany—— # 万级项目下 norm_res 有上亿行,逐条 execute 光 Python 调用开销就要数小时 res_rows = [] for bi, norms in enumerate(data["norms"]): for nrow in norms: cur.execute(sqls["norm"], (bill_ids[bi],) + tuple(nrow[:6])) nid = cur.lastrowid for (res_code, rq) in nrow[6]: res_rows.append((nid, res_code, rq)) if res_rows: cur.executemany(sqls["res"], res_rows) lme_vals = [] for row in data["lmes"]: vals = [owner_id] + list(row[:13]) if pdl: vals += [ym, ym] lme_vals.append(vals) if lme_vals: cur.executemany(lme_sql, lme_vals) if data["lib"]: cur.executemany(sqls["lib"], [[owner_id] + list(r) for r in data["lib"]]) if data["proj"]: cur.executemany(sqls["proj"], [[owner_id] + list(r) for r in data["proj"]]) return {"sec": sec_map, "uw": uw_map, "div": div_map} # ---------------- 单个项目(逻辑数据生成,两库共用) ---------------- def build_project_data(rng, cfg, words, m_idx, bid_local=True): """生成一份项目的完整逻辑数据(不落库)。结构键: secs/uws/divs/bills/norms/norms_of_bill/lmes/lib/proj""" n_sec = rng.randint(1, 2) secs, uws, divs, bills, norms, bill_ids = [], [], [], [], [], [] uw_ix = 0 for s in range(1, n_sec + 1): sname = rng.choice(SECTION_NAMES) if n_sec > 1 else "" secs.append((s, str(s), sname, 0.0, rng.choice([0, 0, round(rng.uniform(0.5, 3.2), 2)]))) # 先铺单位工程与分部 div_local = 0 for s in range(1, n_sec + 1): for _ in range(rng.randint(2, 4)): uw_ix += 1 uwn = rng.choice(UW_NAMES) uws.append((uw_ix, "%d.%d" % (s, uw_ix), uwn, rng.randint(1, 5), 0.0, s, 0, 0, 0, 0, 0, 0)) # 费用构成列先置 0, bills 后回填 pool_d = DIV_NAMES[:8] if uwn in ("土建工程", "装饰装修工程") else DIV_NAMES[8:] chosen = rng.sample(pool_d, min(len(pool_d), rng.randint(2, 5))) for di, dvn in enumerate(chosen, 1): div_local += 1 divs.append((uw_ix, "item", "%d.%d" % (s, div_local), dvn, 0.0, "", di)) if rng.random() < 0.75: divs.append((uw_ix, "prelim", "%d.%d" % (s, div_local + 1), "措施项目", 0.0, "", len(chosen) + 1)) # 清单 bill_target = rng.randint(int(cfg["bill_lo"]), max(int(cfg["bill_lo"]), int(cfg["bill_hi"]))) uw_ids = [u[0] for u in uws] divs_by_uw = {} for d in divs: divs_by_uw.setdefault(d[0], []).append(d) seq = 0 for i in range(bill_target): uw_l = rng.choice(uw_ids) ds = divs_by_uw.get(uw_l) if not ds: continue d = rng.choice(ds) if d[1] == "prelim": code10, bnm, unit, attr = rng.choice(PRELIM_ITEMS) kind = "prelim" else: code10, bnm, unit, attr = rng.choice(BILL_ITEMS) kind = None num = "%s%03d" % (code10, rng.randint(1, 999)) qty = _qty_for_unit(rng, unit) price = guess_price(bnm, unit, m_idx) total = round(qty * price, 2) seq += 1 bills.append((uw_l, (d[0], d[6]), num, bnm, attr, unit, qty, price, total, kind, "", seq)) # 每条清单的定额 + 每条定额的工料机 nrm_lo, nrm_hi = int(cfg["norm_lo"]), max(int(cfg["norm_lo"]), int(cfg["norm_hi"])) res_lo, res_hi = int(cfg["res_lo"]), max(int(cfg["res_lo"]), int(cfg["res_hi"])) _u = {} # 真实库同 code 跨批次重复,lme_lib 有 for it in words.lmes: # (batch_id, code) 唯一约束 → 先按 code 去重 _u.setdefault(it[0], it) _seen = set() # lmes 还有 (batch_id, x_hash_exact) 唯一约束: _uniq = [] # 不同 code 的同名同规格同单位也要去重 for it in _u.values(): k = md5(it[1], it[2], it[3]) # 与落库 x_hash_exact 同口径 if k in _seen: continue _seen.add(k) _uniq.append(it) lme_pool = rng.sample(_uniq, min(len(_uniq), rng.randint(260, 520))) lme_by_kind = {1: [], 2: [], 3: []} for it in lme_pool: lme_by_kind.setdefault(it[4] or 2, []).append(it) # 语义匹配走倒排索引(words.norm_ix / words.hint_ix,Words 里一次构建) for b in bills: cand = None for hint, _hs in HINTS: if hint in b[3]: cand = words.hint_ix.get(hint) or None if cand: break if not cand: keys = [kk for kk in NKEYS if kk in b[3]] if keys: merged, seen = [], set() for kk in keys: for n in words.norm_ix.get(kk, ()): if id(n) not in seen: seen.add(id(n)) merged.append(n) cand = merged cand = cand or words.norms k = rng.randint(nrm_lo, nrm_hi) bl = [] used = set() big = len(cand) > 12 for _ in range(k): if big: # 池大时随机试探替代「全池过滤重建」:同是优先未用定额,免去每次 k×全池扫描 pick = None for _t in range(10): n_ = rng.choice(cand) if n_[0] not in used: pick = n_ break if pick is None: pick = rng.choice(cand) else: pickable = [n for n in cand if n[0] not in used] or cand pick = rng.choice(pickable) ncode, nname, nunit = pick used.add(ncode) nqty = max(round(b[6] * rng.uniform(0.05, 0.6), 2), 0.01) nprice = guess_price(nname, nunit, m_idx) rlist = [] # 人工必配 1 条 lab = lme_by_kind.get(1) or lme_pool it = rng.choice(lab) rlist.append((it[0], _res_qty(rng, 1))) # 材料按剩余名额 nmat = max(1, rng.randint(res_lo, res_hi) - 1) mats = [n for n in words.norms] # 占位避免歧义 mat_pool = lme_by_kind.get(2) or lme_pool for _ in range(nmat): it = rng.choice(mat_pool) rlist.append((it[0], _res_qty(rng, 2))) # 定额名含机械词才配机械(更贴近真实消耗结构) if any(mk in nname for mk in MKEYS) and lme_by_kind.get(3): it = rng.choice(lme_by_kind[3]) rlist.append((it[0], _res_qty(rng, 3))) bl.append((ncode, nname, nunit, nqty, nprice, round(nqty * nprice, 2), rlist)) norms.append(bl) # 工料机主表 / lib / proj lmes, lib, proj = [], [], [] agg = {} for (code, nm2, spec, unit, kind, price0) in lme_pool: if not price0: price0 = guess_price(nm2, unit, m_idx) rate = rng.choice([0.13, 0.09, 0.03]) ntp = round(price0, 2) taxp = round(price0 * (1 + rate), 2) lmes.append((code, nm2, spec, unit, round(rng.uniform(1, 500), 2), ntp, rate, taxp, kind, norm(nm2), norm(spec), norm(unit), md5(nm2, spec, unit))) lib.append((code, nm2, spec, unit, kind, ntp, taxp)) agg[code] = [nm2, spec, unit, kind, 0.0, ntp, taxp] for bl in norms: for nrow in bl: for (rc, rq) in nrow[6]: if rc in agg: agg[rc][4] += rq for code, (nm2, spec, unit, kind, q, ntp, taxp) in agg.items(): proj.append((code, nm2, spec, unit, kind, round(q, 2), ntp, taxp)) # 单位工程费用构成 + 分部/单项合计 uw_sum = {} prelim_sum = {} for b in bills: uw_sum[b[0]] = uw_sum.get(b[0], 0) + b[8] if b[9] == "prelim": prelim_sum[b[0]] = prelim_sum.get(b[0], 0) + b[8] uws2 = [] for u in uws: item = uw_sum.get(u[0], 0.0) pre = prelim_sum.get(u[0], 0.0) hse = round(item * rng.uniform(0.02, 0.04), 2) tax = round((item + pre) * 0.09, 2) sund = round(item * 0.01, 2) total = round(item + pre + hse + tax + sund, 2) uws2.append((u[0], u[1], u[2], u[3], total, u[5], round(item + pre + hse + sund, 2), item, pre, hse, sund, tax)) # 分部合计 dsum = {} for b in bills: dsum[b[1]] = dsum.get(b[1], 0) + b[8] return { "secs": secs, "uws": uws2, "divs": divs, "bills": bills, "norms": norms, "bill_ids": bill_ids, "lmes": lmes, "lib": lib, "proj": proj, "div_sum": dsum, } # ---------------- 项目主循环 ---------------- def gen_projects(hc, sc, dd, cfg, rng, words, log, start=0): y_a, y_b = _ym_range(cfg) pver = _parser_vers(dd)[0] # 工程线版本 n = int(cfg["n_project"]) linked = bool(cfg.get("session_linked")) t0 = time.time() stats = {"project": 0, "bills": 0, "norms": 0, "res": 0, "lmes": 0, "inq": 0, "binds": 0, "sessions": 0} for i in range(n): if _paused(): log(" 软暂停:第 %d/%d 个项目处停止(已生成的保留)。" % (i + 1, n)) break stem = rng.choice(words.stems).strip()[:22] name = "测试项目%03d-%s" % (start + i + 1, stem) sha_src = hashlib.sha256(("testdata-src|%s" % name).encode("utf-8")).hexdigest() src_name = "%s_%s.cos4" % (sha_src, name) _, _, m_idx = _rand_ym(rng, y_a, y_b) prov, city, dist = rng.choice(REGIONS) bu = rng.choice(words.builders) dt = _rand_dt(rng, y_a, y_b) data = build_project_data(rng, cfg, words, m_idx) total = round(sum(u[4] for u in data["uws"]), 2) info = {"编号": "TC-%04d-%02d" % (m_idx // 12, m_idx % 12), "专业": rng.choice(["市政", "建筑", "安装", "园林"]), "计价标准": "2025造价数据标准", "建设单位": bu} feat = [{"n": "合同工期", "v": "%d 日历天" % rng.randint(120, 900)}, {"n": "质量要求", "v": rng.choice(["合格", "市优", "省优"])}] cur = hc.cursor() bcols = ("kind Name FileKind BulidUnit x_province x_city x_district" " x_period_start_m x_period_end_m x_enabled x_total x_rows_bill" " x_rows_lme x_imported_at x_src_hash x_note x_parser_ver x_info" " x_feat is_mock").split() bvals = ["project", name, rng.choice([1, 2, 3, 4]), bu, prov, city, dist, m_idx, m_idx, 1, total, len(data["bills"]), len(data["lmes"]), dt, src_name, "testdata 自动生成", pver, json.dumps(info, ensure_ascii=False), json.dumps(feat, ensure_ascii=False), 1] assert len(bcols) == len(bvals), (len(bcols), len(bvals)) cur.execute("INSERT INTO batches(%s) VALUES(%s)" % (",".join(bcols), ",".join("?" * len(bcols))), bvals) bid = cur.lastrowid maps = insert_tree(hc, SQL_H, bid, data, ym=m_idx) # 分部 / 单项合计回填 cur.executemany("UPDATE divides SET Total=? WHERE id=?", [(t, maps["div"][k]) for k, t in data["div_sum"].items() if k in maps["div"]]) sec_sum = {} for u in data["uws"]: sec_sum[u[5]] = round(sec_sum.get(u[5], 0) + u[4], 2) cur.executemany("UPDATE sections SET Total=? WHERE id=?", [(t, maps["sec"][s]) for s, t in sec_sum.items() if s in maps["sec"]]) # 询价附件 inq_n = max(0, int(cfg.get("inq_per_project", 0))) inq_ids = [] for k in range(inq_n): fname = "%s-%d%s.%s" % (name, k + 1, rng.choice(INQ_NAMES), rng.choice(INQ_EXT)) sha = hashlib.sha256(("testdata-inq|%s|%d" % (name, k)).encode("utf-8")).hexdigest() rel = write_file_rel(dd, "inquiry", sha, fname) sz = os.path.getsize(os.path.join(dd, rel)) cur.execute( """INSERT INTO inquiry_files(batch_id, sha256, original_name, stored_path, size, ext, uploaded_at) VALUES(?,?,?,?,?,?,?)""", (bid, sha, fname, rel, sz, fname.rsplit(".", 1)[-1], time.strftime("%Y-%m-%d %H:%M:%S"))) inq_ids.append(cur.lastrowid) stats["inq"] += len(inq_ids) # 工料机绑定率 bind_rate = max(0, min(100, int(cfg.get("bind_rate", 0)))) lme_ids = [r[0] for r in cur.execute( "SELECT id FROM lmes WHERE batch_id=?", (bid,)).fetchall()] if inq_ids and bind_rate and lme_ids: bind_n = max(1, int(round(len(lme_ids) * bind_rate / 100.0))) picks = rng.sample(lme_ids, min(bind_n, len(lme_ids))) cur.executemany( "INSERT OR REPLACE INTO lme_attach(lme_id, batch_id, file_id) VALUES(?,?,?)", [(l, bid, rng.choice(inq_ids)) for l in picks]) stats["binds"] += len(picks) # uploads 源文件占位(联动/重新解析不缺文件) write_file_rel(dd, "uploads", sha_src, "%s.cos4" % name) hc.commit() _ckpt(hc) stats["project"] += 1 stats["bills"] += len(data["bills"]) stats["norms"] += sum(len(x) for x in data["norms"]) stats["res"] += sum(len(n2[6]) for x in data["norms"] for n2 in x) stats["lmes"] += len(data["lmes"]) # 联动会话:同一份逻辑数据镜像进 session.db if linked and sc is not None: scur = sc.cursor() scur.execute( """INSERT INTO sessions(name, base_period_m, period_from, period_to, x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_total, x_info, x_feat, x_batch_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (name, m_idx, m_idx, m_idx, prov, city, dist, bu, src_name, dt, total, json.dumps(info, ensure_ascii=False), json.dumps(feat, ensure_ascii=False), bid)) sid = scur.lastrowid insert_tree(sc, SQL_S, sid, data, ym=None) sc.commit() stats["sessions"] += 1 log(" [%d/%d] %s:清单 %d、定额 %d、工料机 %d 种、附件 %d 份%s" % ( i + 1, n, name, len(data["bills"]), sum(len(x) for x in data["norms"]), len(data["lmes"]), len(inq_ids), "(+镜像会话)" if linked else "")) # 量级进度:上限测试跑的是万级项目,光看逐条日志没有体积/速率概念 if (i + 1) % 25 == 0 or i + 1 == n: el = time.time() - t0 log(" …进度 %d/%d | %.0fs | 累计清单 %d(%.0f 行/s)| history %.0f MB%s" % ( i + 1, n, el, stats["bills"], stats["bills"] / max(el, 0.001), _db_mb(db_paths(dd)[1]), (" + session %.0f MB" % _db_mb(db_paths(dd)[3])) if sc is not None else "")) return stats # ---------------- 独立工作台会话 ---------------- def gen_sessions_standalone(sc, dd, cfg, rng, words, log): y_a, y_b = _ym_range(cfg) n = int(cfg.get("n_session", 0)) sub = dict(cfg) sub["bill_lo"], sub["bill_hi"] = cfg.get("sbill_lo", 150), cfg.get("sbill_hi", 400) t0 = time.time() stats = {"sessions": 0, "bills": 0, "norms": 0, "res": 0, "lmes": 0} for i in range(n): if _paused(): log(" 软暂停:第 %d/%d 份会话处停止。" % (i + 1, n)) break name = "测试工作台-%03d-%s" % (i + 1, rng.choice(words.stems).strip()[:18]) sha_src = hashlib.sha256(("testdata-src|%s" % name).encode("utf-8")).hexdigest() src_name = "%s_%s.cos4" % (sha_src, name) _, _, m_idx = _rand_ym(rng, y_a, y_b) prov, city, dist = rng.choice(REGIONS) bu = rng.choice(words.builders) dt = _rand_dt(rng, y_a, y_b) data = build_project_data(rng, sub, words, m_idx) total = round(sum(u[4] for u in data["uws"]), 2) scur = sc.cursor() scur.execute( """INSERT INTO sessions(name, base_period_m, period_from, period_to, x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_total, x_info, x_feat, x_batch_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,0)""", (name, m_idx, m_idx, m_idx, prov, city, dist, bu, src_name, dt, total, json.dumps({"编号": "TC-%04d-%02d" % (m_idx // 12, m_idx % 12)}, ensure_ascii=False), "[]")) sid = scur.lastrowid insert_tree(sc, SQL_S, sid, data, ym=None) sc.commit() _ckpt(sc) stats["sessions"] += 1 stats["bills"] += len(data["bills"]) stats["norms"] += sum(len(x) for x in data["norms"]) stats["res"] += sum(len(n2[6]) for x in data["norms"] for n2 in x) stats["lmes"] += len(data["lmes"]) log(" [%d/%d] %s:清单 %d(独立会话)" % (i + 1, n, name, len(data["bills"]))) if (i + 1) % 25 == 0 or i + 1 == n: el = time.time() - t0 log(" …进度 %d/%d | %.0fs | 累计清单 %d(%.0f 行/s)| session %.0f MB" % ( i + 1, n, el, stats["bills"], stats["bills"] / max(el, 0.001), _db_mb(db_paths(dd)[3]))) return stats # ---------------- 市场价 / 信息价 ---------------- def gen_prices(hc, dd, cfg, rng, words, log): y_a, y_b = _ym_range(cfg) pver = _parser_vers(dd)[1] # 价格线版本 seen, pool = set(), [] for it in words.lmes: key = (it[1], it[2], it[3]) if key not in seen: seen.add(key) pool.append(it) stats = {"market": 0, "info": 0, "price_rows": 0, "price_attach": 0} plan = [ ("market", "测试市场价", int(cfg.get("n_market", 0)), int(cfg.get("market_lo", 500)), int(cfg.get("market_hi", 800)), int(cfg.get("market_attach_rate", 80))), ("info", "测试信息价", int(cfg.get("n_info", 0)), int(cfg.get("info_lo", 500)), int(cfg.get("info_hi", 800)), int(cfg.get("info_attach_rate", 90))), ] for kind, prefix, cnt, lo, hi, rate in plan: if cnt <= 0: continue lo = max(1, min(lo, len(pool))) hi = max(lo, min(hi, len(pool))) for i in range(cnt): if _paused(): log(" 软暂停:%s 第 %d/%d 份处停止。" % (prefix, i + 1, cnt)) break _, _, m_idx = _rand_ym(rng, y_a, y_b) prov, city, dist = rng.choice(REGIONS) pub = rng.choice(PUBLISHERS) if kind == "info" else "" bname = "%s-%s%03d" % (prefix, rng.choice(BLOCKS)[:6], i + 1) dt = _rand_dt(rng, y_a, y_b) cur = hc.cursor() bcols = ("kind Name FileKind BulidUnit x_province x_city x_district" " x_period_start_m x_period_end_m x_enabled x_total x_rows_bill" " x_rows_lme x_imported_at x_src_hash x_note x_publisher" " x_parser_ver is_mock").split() bvals = [kind, bname[:200], None, "", prov, city, dist, m_idx, m_idx, 1, 0, 0, 0, dt, "mock://%s" % sha_src_of(bname), "testdata 自动生成", pub, pver, 1] assert len(bcols) == len(bvals), (len(bcols), len(bvals)) cur.execute("INSERT INTO batches(%s) VALUES(%s)" % (",".join(bcols), ",".join("?" * len(bcols))), bvals) bid = cur.lastrowid n_rows = rng.randint(lo, hi) sample = rng.sample(pool, n_rows) block = rng.choice(BLOCKS) rows = [] for (code, nm2, spec, unit, kindl, price0) in sample: nt = guess_price(nm2, unit, m_idx) rate2 = rng.choice([0.13, 0.09, 0.03, None]) tp = round(nt * (1 + rate2), 2) if rate2 else None rows.append((bid, code, nm2, spec, unit, nt, rate2, tp, rng.choice(BLOCK_CLASSES[block]), "testdata 模拟区间价", block, norm(nm2), norm(spec), norm(unit), md5(nm2, spec, unit), m_idx, m_idx)) cur.executemany( """INSERT INTO prices(batch_id, Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice, Class, Note, Block, x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_period_start_m, x_period_end_m) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", rows) cur.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n_rows, bid)) # 附件率:命中才挂价格原件 if rng.random() * 100 < rate: fname = "%s-%s.%s" % (bname, rng.choice(INQ_NAMES), rng.choice(INQ_EXT)) sha = hashlib.sha256(("testdata-att|%s" % bname).encode("utf-8")).hexdigest() rel = write_file_rel(dd, "attachments", sha, fname) sz = os.path.getsize(os.path.join(dd, rel)) cur.execute( """INSERT OR IGNORE INTO attachments(sha256, stored_path, original_name, size, uploaded_at) VALUES(?,?,?,?,?)""", (sha, rel, fname, sz, time.strftime("%Y-%m-%d %H:%M:%S"))) cur.execute("UPDATE batches SET x_attach_sha=? WHERE id=?", (sha, bid)) stats["price_attach"] += 1 hc.commit() _ckpt(hc) stats[kind] += 1 stats["price_rows"] += n_rows if (i + 1) % 200 == 0 or i + 1 == cnt: log(" …%s 进度 %d/%d | history %.0f MB" % ( prefix, i + 1, cnt, _db_mb(db_paths(dd)[1]))) log(" %s:%d 份完成(每份 %d~%d 条,附件率 %d%%)" % (prefix, cnt, lo, hi, rate)) return stats def sha_src_of(s): return hashlib.sha256(("testdata-price|%s" % s).encode("utf-8")).hexdigest() # ---------------- 一键换库(测试库换上,原库留底 -y) ---------------- def switch_dbs(dd, log=print): """history-test.db→history.db(原 history.db→history-y.db 留底),session 同理。 -wal/-shm 随主文件一起走;任何一步失败自动逆序回滚。 软件运行中会因文件占用失败——先关闭造价审核软件再点。""" rh, th, rs, ts = db_paths(dd) yh = os.path.join(dd, "history-y.db") ys = os.path.join(dd, "session-y.db") EXT = ("-wal", "-shm") for p in (th, ts): if not os.path.exists(p): raise RuntimeError("!! %s 不存在——请先点「开始生成」" % os.path.basename(p)) done = [] # 已完成的 (src, dst),回滚时逆序 def mv(a, b): os.rename(a, b) done.append((a, b)) try: for t, r, y in ((th, rh, yh), (ts, rs, ys)): if os.path.exists(r): if os.path.exists(y): raise RuntimeError("留底 %s 已存在(上次换库留的)。确认覆盖请先手动删除它。" % os.path.basename(y)) mv(r, y) for e in EXT: if os.path.exists(r + e): mv(r + e, y + e) mv(t, r) for e in EXT: if os.path.exists(t + e): mv(t + e, r + e) log("%s 已换上,原库留底为 %s" % (os.path.basename(t), os.path.basename(y)) if os.path.exists(y) else "%s 已换上" % os.path.basename(t)) except OSError as e: for a2, b2 in reversed(done): try: os.rename(b2, a2) except Exception: pass raise RuntimeError("换库失败已回滚:%s(多半是造价审核软件还在运行占用文件,请先关闭再试)" % e) return yh, ys # ---------------- 版本对齐(测试库搬到别的母体后用) ---------------- def align_testdata(dd, log=print): """把「测试」批次的解析器版本对齐到本数据目录旁母体 app 的当前版本。 测试库从 A 母体生成、换到 B 母体(如工作区)使用时,stale_batches 会误报过期—— 跑一次本函数即可。只动 Name LIKE '测试%' 的行。""" proj, price = _parser_vers(dd) log("母体当前解析器:工程=%s / 价格=%s" % (proj, price)) total = 0 for path in (db_paths(dd)[1], db_paths(dd)[0]): # 优先测试库;已换名成 history.db 的也认 if not os.path.exists(path): continue con = _open_db(path) try: n = con.execute("SELECT COUNT(*) FROM batches WHERE Name LIKE '测试%'").fetchone()[0] except Exception: con.close() continue if not n: con.close() continue a = con.execute( "UPDATE batches SET x_parser_ver=? WHERE kind='project' AND Name LIKE '测试%' " "AND (x_parser_ver IS NULL OR x_parser_ver<>?)", (proj, proj)).rowcount b = con.execute( "UPDATE batches SET x_parser_ver=? WHERE kind<>'project' AND Name LIKE '测试%' " "AND (x_parser_ver IS NULL OR x_parser_ver<>?)", (price, price)).rowcount con.commit() con.close() log("%s:对齐 %d 个批次(工程 %d / 价格 %d)" % (os.path.basename(path), a + b, a, b)) total += a + b if not total: log("没有需要改版本的测试批次。") return total # ---------------- 统计 ---------------- def stats_of(dd): out = {"data_dir": dd, "db_file": TEST_H} th, ts = db_paths(dd)[1], db_paths(dd)[3] if not os.path.exists(th): out["note"] = "测试库尚未生成(%s 不存在),真实库从未被本工具写过" % TEST_H return out hc = _open_ro(th) if hc is None: out["note"] = "测试库被占用(可能正在生成或造价审核软件打开中),稍后点「刷新统计」重试" return out q = "FROM batches WHERE is_mock=1 AND Name LIKE '测试%'" for k in ("project", "market", "info"): out["b_%s" % k] = hc.execute("SELECT COUNT(*) " + q + " AND kind=?", (k,)).fetchone()[0] joins = { "bills": "FROM bills b JOIN batches bt ON bt.id=b.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "norms": "FROM norms n JOIN bills b ON b.id=n.bill_id JOIN batches bt ON bt.id=b.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "norm_res": "FROM norm_res r JOIN norms n ON n.id=r.norm_id JOIN bills b ON b.id=n.bill_id JOIN batches bt ON bt.id=b.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lmes": "FROM lmes l JOIN batches bt ON bt.id=l.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "prices": "FROM prices p JOIN batches bt ON bt.id=p.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "inquiry_files": "FROM inquiry_files f JOIN batches bt ON bt.id=f.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lme_attach": "FROM lme_attach a JOIN batches bt ON bt.id=a.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lme_lib": "FROM lme_lib l JOIN batches bt ON bt.id=l.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lme_proj": "FROM lme_proj l JOIN batches bt ON bt.id=l.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", } for t, sql in joins.items(): try: out[t] = hc.execute("SELECT COUNT(*) " + sql).fetchone()[0] except Exception: out[t] = -1 out["price_attach_batches"] = hc.execute( "SELECT COUNT(*) " + q + " AND x_attach_sha IS NOT NULL").fetchone()[0] hc.close() sp = ts if os.path.exists(sp): sc = _open_ro(sp) if sc is None: out["s_sessions"] = -1 for t in ("s_bills", "s_norms", "s_lmes"): out[t] = -1 else: out["s_sessions"] = sc.execute( "SELECT COUNT(*) FROM sessions WHERE name LIKE '测试%'").fetchone()[0] for t in ("s_bills", "s_norms", "s_lmes"): try: if t == "s_norms": # s_norms.bill_id 挂在 s_bills 上,要经两层 out[t] = sc.execute( "SELECT COUNT(*) FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills " "WHERE session_id IN (SELECT id FROM sessions WHERE name LIKE '测试%'))" ).fetchone()[0] else: out[t] = sc.execute( "SELECT COUNT(*) FROM %s WHERE session_id IN " "(SELECT id FROM sessions WHERE name LIKE '测试%%')" % t).fetchone()[0] except Exception: out[t] = -1 sc.close() return out # ---------------- 数据库资产总览(两库全量家底,打开面板即看) ---------------- def totals_of(dd): """参考库与测试库的全量资产计数(不区分 mock,只数行数)。 缺文件 / 被占用的库返回 None。全部走只读短超时连接,库被造价审核软件或生成子进程 占用时快速返回(带 locked 标记),绝不死等——否则 /api/stats 卡 15~30s 会让整页假死。""" rh, th, rs, ts = db_paths(dd) def one(p, tables): if not os.path.exists(p): return None, False c = _open_ro(p, timeout=3) if c is None: return None, True # 被占用 out = {} for t in tables: try: out[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0] except Exception: out[t] = -1 c.close() return out, False H = ("batches", "bills", "norms", "norm_res", "lmes", "lme_lib", "prices", "attachments") S = ("sessions", "s_bills", "s_norms", "s_lmes") rh_d, l1 = one(rh, H); th_d, l2 = one(th, H) rs_d, l3 = one(rs, S); ts_d, l4 = one(ts, S) locked = [n for n, f in (("参考history", l1), ("参考session", l3), ("测试history", l2), ("测试session", l4)) if f] return {"ref_h": rh_d, "ref_s": rs_d, "test_h": th_d, "test_s": ts_d, "locked": locked} # ---------------- 分块删除 ---------------- def delete_testdata(dd, keep_files=False, log=print): th, ts = db_paths(dd)[1], db_paths(dd)[3] if not os.path.exists(th): log("测试库 %s 不存在——没有可删的测试数据(真实库从未被本工具写过)。" % TEST_H) return {"batches": 0, "_remaining": stats_of(dd)} hc = _open_db(th) cur = hc.cursor() n0 = cur.execute( "SELECT COUNT(*) FROM batches WHERE is_mock=1 AND Name LIKE '测试%'").fetchone()[0] log("待删除测试批次:%d 份(分块 %d/块)" % (n0, CHUNK)) st = {} del_files = [] t0 = time.time() def rec(key, n): st[key] = st.get(key, 0) + max(n or 0, 0) while True: ids = [r[0] for r in cur.execute( "SELECT id FROM batches WHERE is_mock=1 AND Name LIKE '测试%' LIMIT ?", (CHUNK,)).fetchall()] if not ids: break ph = ",".join("?" * len(ids)) # 先收集要删的物理文件(询价附件 / 价格原件 / uploads 源文件占位) for (rel,) in cur.execute( "SELECT stored_path FROM inquiry_files WHERE batch_id IN (%s)" % ph, ids): del_files.append(rel) shas = [r[0] for r in cur.execute( "SELECT DISTINCT x_attach_sha FROM batches WHERE id IN (%s)" % ph, ids) if r[0]] if shas: for (rel,) in cur.execute( "SELECT stored_path FROM attachments WHERE sha256 IN (%s)" % ",".join("?" * len(shas)), shas): del_files.append(rel) for (src,) in cur.execute( "SELECT x_src_hash FROM batches WHERE id IN (%s) AND x_src_hash LIKE '%%_%%'" % ph, ids): sha = src.split("_", 1)[0] if len(sha) == 64: del_files.append(os.path.join("uploads", sha[:2], src)) # 子查询链:norm_res → norms → bills(bills 删之前删) rec("norm_res", cur.execute( "DELETE FROM norm_res WHERE norm_id IN (SELECT n.id FROM norms n " "JOIN bills b ON b.id=n.bill_id WHERE b.batch_id IN (%s))" % ph, ids).rowcount) rec("norms", cur.execute( "DELETE FROM norms WHERE bill_id IN " "(SELECT id FROM bills WHERE batch_id IN (%s))" % ph, ids).rowcount) for t in ("bills", "lmes", "lme_res", "lme_lib", "lme_proj", "divides", "unit_works", "sections", "prices", "inquiry_files", "lme_attach"): rec(t, cur.execute("DELETE FROM %s WHERE batch_id IN (%s)" % (t, ph), ids).rowcount) if shas: rec("attachments", cur.execute( "DELETE FROM attachments WHERE sha256 IN (%s)" % ",".join("?" * len(shas)), shas).rowcount) rec("batches", cur.execute( "DELETE FROM batches WHERE id IN (%s)" % ph, ids).rowcount) hc.commit() log(" 已删 %d 份(累计)" % (n0 - cur.execute( "SELECT COUNT(*) FROM batches WHERE is_mock=1 AND Name LIKE '测试%'").fetchone()[0])) hc.close() # 工作台(测试库) sp = ts s0 = 0 if os.path.exists(sp): sc = _open_db(sp) scur = sc.cursor() s0 = scur.execute( "SELECT COUNT(*) FROM sessions WHERE name LIKE '测试%'").fetchone()[0] if s0: log("工作台测试会话:%d 份" % s0) while True: ids = [r[0] for r in scur.execute( "SELECT id FROM sessions WHERE name LIKE '测试%' LIMIT ?", (CHUNK,)).fetchall()] if not ids: break ph = ",".join("?" * len(ids)) rec("s_remarks", scur.execute( "DELETE FROM s_remarks WHERE src_key IN " "(SELECT src_name FROM sessions WHERE id IN (%s))" % ph, ids).rowcount) rec("s_norm_res", scur.execute( "DELETE FROM s_norm_res WHERE norm_id IN (SELECT n.id FROM s_norms n " "JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id IN (%s))" % ph, ids).rowcount) rec("s_norms", scur.execute( "DELETE FROM s_norms WHERE bill_id IN " "(SELECT id FROM s_bills WHERE session_id IN (%s))" % ph, ids).rowcount) for t in ("s_bills", "s_lmes", "s_lme_res", "s_lme_lib", "s_lme_proj", "s_divides", "s_unit_works", "s_sections"): rec(t, scur.execute( "DELETE FROM %s WHERE session_id IN (%s)" % (t, ph), ids).rowcount) rec("sessions", scur.execute( "DELETE FROM sessions WHERE id IN (%s)" % ph, ids).rowcount) sc.commit() sc.close() # 物理文件 n_files = 0 if not keep_files: for rel in del_files: del_file(dd, rel) n_files += 1 log("删除完成,用时 %.1fs。物理文件:%s(%d 个路径)" % ( time.time() - t0, "已删" if not keep_files else "保留(--keep-files)", len(del_files))) # 统计:删了多少 / 还剩多少 st["batches_total"] = st.get("batches", 0) st["_remaining"] = stats_of(dd) return st # ---------------- 性能体检(测「数据库上限」用,全程只读) ---------------- # 复刻母体 match.lme_list_where() 的过滤口径(2026-10-11 版)——体检查询与工作台/后台 # 「项目工料机」完全同形;不 import 母体代码,母体口径若变以那边为准。 LME_WHERE = ("CAST(IFNULL(%sKind,'') AS TEXT) NOT IN ('6','7') " "AND TRIM(IFNULL(%sUnit,'')) NOT IN ('元','工日','台班')") BENCH_HIST = os.path.join(HERE, "bench_history.jsonl") class _BenchAbort(Exception): pass def bench_testdata(dd, log=print): """按母体真实热点查询做一次只读体检:输出当前库规模 + 各查询毫秒数,并追加存档 bench_history.jsonl。测上限用法:从小到大逐级生成(1千→5千→1万→…项目),每级跑 一次体检,哪条查询突破可接受阈值(如 1 秒),哪里就是软件的实际容量上限。 测试库不存在时退而测参考库(只读),并在输出里注明。""" rh, th, rs, ts = db_paths(dd) hp = th if os.path.exists(th) else rh if not os.path.exists(hp): log("!! 没有 history.db / history-test.db 可测(数据目录:%s)" % _disp(dd)) return None res = {"ts": time.strftime("%Y-%m-%d %H:%M:%S"), "db": os.path.basename(hp), "rows": {}, "db_mb": round(_db_mb(hp), 1), "q_ms": {}} log("== 性能体检(只读)==") log("被测库:%s(%.1f MB 含 WAL)%s" % ( res["db"], res["db_mb"], "〔测试库〕" if hp == th else "〔参考库——测试库尚未生成,测的是真实库,只读不写〕")) con = _open_ro(hp, timeout=15) if con is None: log("!! 库被占用(生成中或造价审核软件打开中),稍后再试。") return None def timed(name, sql, args=(), con_=None): if _paused(): raise _BenchAbort c = con_ or con t0 = time.perf_counter() try: rows = c.execute(sql, args).fetchall() except Exception as e: log(" %-28s —— 跳过(%s)" % (name, str(e).split("\n")[0][:60])) return [] ms = (time.perf_counter() - t0) * 1000.0 res["q_ms"][name] = round(ms, 1) log(" %-28s %10.1f ms 返回 %s 行" % (name, ms, format(len(rows), ","))) return rows try: # —— 规模 —— log("-- 数据规模 --") for t, label in (("batches", "批次"), ("bills", "清单"), ("norms", "定额"), ("norm_res", "定额消耗"), ("lmes", "工料机"), ("prices", "价格明细")): try: n = con.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0] res["rows"][t] = n log(" %-8s %15s 行" % (label, format(n, ","))) except Exception: pass n_bat = res["rows"].get("batches", 0) # —— 后台(history)热点 —— log("-- 后台热点查询 --") timed("批次列表·首页50", "SELECT id,Name,kind FROM batches ORDER BY id DESC LIMIT 50") timed("批次列表·深翻页50", "SELECT id,Name,kind FROM batches ORDER BY id DESC LIMIT 50 OFFSET %d" % max(0, n_bat - 50)) timed("批次筛选·project计数", "SELECT COUNT(*) FROM batches WHERE kind='project'") row = con.execute( "SELECT id FROM batches WHERE kind='project' ORDER BY id DESC LIMIT 1").fetchone() bid = row[0] if row else 0 timed("打开项目·清单树全拉", "SELECT id,Number,Name,Attr,Unit,Quantity,Price,Total,Kind" " FROM bills WHERE batch_id=? ORDER BY id", (bid,)) timed("工料机列表·统一过滤", "SELECT id FROM lmes WHERE batch_id=? AND %s ORDER BY id" % (LME_WHERE % ("", "")), (bid,)) timed("工料机检索·LIKE%混凝土%", "SELECT l.id FROM lmes l JOIN batches bt ON bt.id=l.batch_id" " WHERE bt.kind='project' AND l.x_name_norm LIKE '%混凝土%' LIMIT 200") timed("单批次·定额消耗链计数", "SELECT COUNT(*) FROM norm_res r JOIN norms n ON n.id=r.norm_id" " JOIN bills b ON b.id=n.bill_id WHERE b.batch_id=?", (bid,)) # 类似清单命中:与 match.py 一致,按哈希逐条查询,这里实测 20 次合计 hashes = [r[0] for r in con.execute( "SELECT x_hash_exact FROM bills WHERE batch_id=? LIMIT 20", (bid,))] if hashes: t0 = time.perf_counter() n_hit = 0 for h in hashes: n_hit += len(con.execute( "SELECT b.id FROM bills b JOIN batches bt ON bt.id=b.batch_id" " WHERE b.x_hash_exact=? AND bt.kind='project' LIMIT 20", (h,)).fetchall()) ms = (time.perf_counter() - t0) * 1000.0 res["q_ms"]["类似清单·精确命中x20"] = round(ms, 1) log(" %-28s %10.1f ms 20次合计,命中 %d" % ("类似清单·精确命中x20", ms, n_hit)) hashes = [r[0] for r in con.execute( "SELECT x_hash_exact FROM lmes WHERE batch_id=? LIMIT 20", (bid,))] if hashes and res["rows"].get("prices"): t0 = time.perf_counter() n_hit = 0 for h in hashes: n_hit += len(con.execute( "SELECT p.id FROM prices p JOIN batches bt ON bt.id=p.batch_id" " WHERE p.x_hash_exact=? AND bt.kind IN ('market','info') LIMIT 20", (h,)).fetchall()) ms = (time.perf_counter() - t0) * 1000.0 res["q_ms"]["价格命中x20"] = round(ms, 1) log(" %-28s %10.1f ms 20次合计,命中 %d" % ("价格命中x20", ms, n_hit)) con.close() con = None # —— 工作台(session)热点 —— sp = ts if os.path.exists(ts) else rs if os.path.exists(sp): scon = _open_ro(sp, timeout=15) if scon is not None: res["s_db_mb"] = round(_db_mb(sp), 1) log("-- 工作台热点查询(%s,%.1f MB)--" % (os.path.basename(sp), res["s_db_mb"])) try: n_sess = scon.execute("SELECT COUNT(*) FROM sessions").fetchone()[0] res["rows"]["sessions"] = n_sess res["rows"]["s_bills"] = scon.execute( "SELECT COUNT(*) FROM s_bills").fetchone()[0] log(" 会话 %s 份 / 清单 %s 行" % ( format(n_sess, ","), format(res["rows"]["s_bills"], ","))) # 最近审核页核心 SQL(api_sessions 原样复刻:3 个关联子查询聚合) timed("最近审核·列表聚合", "SELECT b.session_id, COUNT(DISTINCT b.id)," " (SELECT COUNT(*) FROM s_norms n WHERE n.bill_id IN" " (SELECT id FROM s_bills WHERE session_id=b.session_id))," " (SELECT COUNT(*) FROM s_lmes l WHERE l.session_id=b.session_id)," " (SELECT COUNT(*) FROM s_unit_works u WHERE u.session_id=b.session_id)," " SUM(CASE WHEN b.x_remark IS NOT NULL AND TRIM(b.x_remark)<>''" " THEN 1 ELSE 0 END)" " FROM s_bills b GROUP BY b.session_id", con_=scon) row = scon.execute( "SELECT id FROM sessions ORDER BY id DESC LIMIT 1").fetchone() sid = row[0] if row else 0 timed("工作台打开·清单全拉", "SELECT id,Number,Name,Attr,Unit,Quantity,Price,Total" " FROM s_bills WHERE session_id=? ORDER BY id", (sid,), con_=scon) timed("工作台·工料机过滤列表", "SELECT id FROM s_lmes WHERE session_id=? AND %s ORDER BY id" % (LME_WHERE % ("", "")), (sid,), con_=scon) finally: scon.close() except _BenchAbort: log("软暂停:体检中止(只读操作,无残留)。") try: con.close() except Exception: pass return None finally: if con is not None: try: con.close() except Exception: pass try: with open(BENCH_HIST, "a", encoding="utf-8") as f: f.write(json.dumps(res, ensure_ascii=False) + "\n") log("体检结果已追加存档 %s——逐级加量各跑一次,即可对比画出「容量-耗时」曲线。" % os.path.basename(BENCH_HIST)) except Exception: pass log("== 体检完成。判读:哪条查询突破可接受阈值(如 1 秒),哪里就是当前规模下的瓶颈;") log(" 逐级加量(1千→5千→1万→5万项目)重复「生成→体检」,阈值 Crossing 点即数据库上限。") return res # ---------------- 编排入口 ---------------- def _has_col(con, table, col): try: return any(r[1] == col for r in con.execute('PRAGMA table_info("%s")' % table)) except Exception: return False def _clean_orphans(con, parent="batches", pcol="batch_id"): """删除孤儿子表行(父批次/会话已不存在),避免新批次复用 id 时撞唯一约束。 只删 batch_id/session_id 不在父表里的行,从不碰任何有效数据。""" try: tabs = [r[0] for r in con.execute( "SELECT name FROM sqlite_master WHERE type='table'").fetchall()] # 保险:父表为空时绝不反删子表(否则 NOT IN(空) 会全删) pcount = con.execute('SELECT COUNT(*) FROM "%s"' % parent).fetchone()[0] if pcount == 0: con.commit() return for t in tabs: if t == parent or not _has_col(con, t, pcol): continue con.execute('DELETE FROM "%s" WHERE "%s" NOT IN (SELECT id FROM "%s")' % (t, pcol, parent)) if parent == "batches": if _has_col(con, "norms", "bill_id"): con.execute("DELETE FROM norms WHERE bill_id NOT IN (SELECT id FROM bills)") if _has_col(con, "norm_res", "norm_id"): con.execute("DELETE FROM norm_res WHERE norm_id NOT IN (SELECT id FROM norms)") else: if _has_col(con, "s_norms", "bill_id"): con.execute("DELETE FROM s_norms WHERE bill_id NOT IN (SELECT id FROM s_bills)") if _has_col(con, "s_norm_res", "norm_id"): con.execute("DELETE FROM s_norm_res WHERE norm_id NOT IN (SELECT id FROM s_norms)") con.commit() except Exception: try: con.rollback() except Exception: pass raise def _estimate_run(cfg): """按行宽×行数粗估本次生成的库体积(GB)与附件文件个数,供磁盘空间预警。 系数为经验值:bills≈340B/行、norms≈180B、norm_res≈48B、工料机三表≈390 种×730B、 prices≈220B,再乘 1.7 覆盖索引与表结构冗余;文件按 8KB/个(内容 1~6KB + NTFS 簇)。""" def _avg(a, b): return (float(a or 0) + float(b or 0)) / 2.0 np_ = float(cfg.get("n_project", 0) or 0) nb = _avg(cfg.get("bill_lo", 0), cfg.get("bill_hi", 0)) nn = nb * _avg(cfg.get("norm_lo", 0), cfg.get("norm_hi", 0)) nr = nn * _avg(cfg.get("res_lo", 0), cfg.get("res_hi", 0)) rows = np_ * (nb * 340 + nn * 180 + nr * 48 + 390 * 730 + 400) ns = np_ if cfg.get("session_linked") else float(cfg.get("n_session", 0) or 0) sb = _avg(cfg.get("sbill_lo", 0), cfg.get("sbill_hi", 0)) rows += ns * (sb * 340 + sb * 4 * 180 + sb * 4 * 4 * 48 + 390 * 730 + 400) rows += float(cfg.get("n_market", 0) or 0) * _avg(cfg.get("market_lo", 0), cfg.get("market_hi", 0)) rows += float(cfg.get("n_info", 0) or 0) * _avg(cfg.get("info_lo", 0), cfg.get("info_hi", 0)) gb = rows * 1.7 / 1e9 nfiles = np_ * float(cfg.get("inq_per_project", 0) or 0) + ns + np_ return gb, int(nfiles), nfiles * 8192 / 1e9 def run(cfg, log=print): global REF_DIR REF_DIR = (cfg.get("ref_dir") or "").strip() or None dd = cfg.get("data_dir") or find_data_dir() if not dd: log("!! 找不到数据目录(history.db)。请在控制台里手动指定数据目录。") return False th, ts = ensure_test_dbs(dd, log) hc = _open_db(th, bulk=True) _clean_orphans(hc, "batches", "batch_id") sc = _open_db(ts, bulk=True) if os.path.exists(ts) else None if sc is not None: _clean_orphans(sc, "sessions", "session_id") rng = random.Random() # 每次运行真随机(不固定种子) words = Words(hc) log("参考库目录:%s" % _disp(os.path.dirname(db_paths(dd)[0]))) log("测试库目录:%s" % _disp(dd)) log("词料:项目名 %d / 定额 %d / 工料机 %d / 建设单位 %d" % ( len(words.stems), len(words.norms), len(words.lmes), len(words.builders))) # 磁盘空间预警:上限测试动辄几十上百 GB,写满中途失败虽然已提交数据保留,但白跑几小时 est_gb, est_files, est_fgb = _estimate_run(cfg) try: free_gb = shutil.disk_usage(dd).free / 1e9 except Exception: free_gb = None log("规模预估:库 ≈ %.1f GB + 附件文件 %d 个(≈ %.1f GB)%s" % ( est_gb, est_files, est_fgb, (";数据盘剩余 %.0f GB" % free_gb) if free_gb is not None else "")) if free_gb is not None and est_gb + est_fgb > 0.5 and free_gb < (est_gb + est_fgb) * 1.1: log("⚠ 剩余空间低于预估——中途磁盘写满会报错停止(已提交数据保留),请减小规模或换盘。") t0 = time.time() st = {} if int(cfg.get("n_project", 0)) > 0: log("== 后台项目(%d 份,清单 %d~%d/项目,定额 %d~%d/清单,工料机 %d~%d/定额)==" % ( cfg["n_project"], cfg["bill_lo"], cfg["bill_hi"], cfg["norm_lo"], cfg["norm_hi"], cfg["res_lo"], cfg["res_hi"])) chunk = int(cfg.get("chunk", 0) or 0) if chunk > 0 and chunk < int(cfg["n_project"]): total = int(cfg["n_project"]); off = 0 while off < total: piece = dict(cfg); piece["n_project"] = min(chunk, total - off) log(" —— 分批推进:第 %d~%d / %d 份 ——" % (off + 1, off + piece["n_project"], total)) _merge(st, gen_projects(hc, sc, dd, piece, rng, words, log, start=off)) off += piece["n_project"] else: _merge(st, gen_projects(hc, sc, dd, cfg, rng, words, log)) if int(cfg.get("n_market", 0)) or int(cfg.get("n_info", 0)): log("== 市场价/信息价 ==") _merge(st, gen_prices(hc, dd, cfg, rng, words, log)) if sc is not None and not cfg.get("session_linked") and int(cfg.get("n_session", 0)) > 0: log("== 独立工作台会话(%d 份,清单 %d~%d/份)==" % ( cfg["n_session"], cfg.get("sbill_lo", 150), cfg.get("sbill_hi", 400))) _merge(st, gen_sessions_standalone(sc, dd, cfg, rng, words, log)) # 收尾 checkpoint:全部读连接断开时把 WAL 收干净,不留巨型 WAL 给下次恢复 for c in (hc, sc): if c is not None: try: c.execute("PRAGMA wal_checkpoint(TRUNCATE)") except Exception: pass hc.close() if sc is not None: sc.close() log("== 汇总 ==") for k, v in sorted(st.items()): log(" %s: %s" % (k, v)) log("完成,用时 %.1fs。" % (time.time() - t0)) return True def main(): ap = argparse.ArgumentParser(description="testdata 测试数据生成器") ap.add_argument("--check", action="store_true", help="统计现有测试数据") ap.add_argument("--run", metavar="CFG_JSON", help="按参数 json 生成") ap.add_argument("--bench", action="store_true", help="性能体检:只读实测母体热点查询耗时(测数据库上限用)") ap.add_argument("--align-ver", action="store_true", help="把测试批次的解析器版本对齐到本母体当前版本(换母体使用后跑一次)") ap.add_argument("--delete", action="store_true", help="分块删除全部测试数据") ap.add_argument("--yes", action="store_true", help="跳过删除确认") ap.add_argument("--keep-files", action="store_true", help="删除时保留附件物理文件") args = ap.parse_args() dd = find_data_dir() if args.check: if not dd: print("!! 找不到数据目录(history.db)") sys.exit(1) s = stats_of(dd) print("数据目录:%s" % _disp(dd)) for k, v in s.items(): print(" %s: %s" % (k, v)) return if args.bench: if not dd: print("!! 找不到数据目录(history.db)") sys.exit(1) bench_testdata(dd) return if args.delete: if not dd: print("!! 找不到数据目录(history.db)") sys.exit(1) if not args.yes: ans = input("确认真删除全部测试数据?(输入 yes 继续)").strip().lower() if ans != "yes": print("已取消。") return st = delete_testdata(dd, keep_files=args.keep_files) print("== 删除统计 ==") for k, v in sorted(st.items()): if k != "_remaining": print(" 已删 %s: %s" % (k, v)) r = st.get("_remaining", {}) print("== 现在还剩(测试数据)==") for k, v in r.items(): print(" %s: %s" % (k, v)) return if args.align_ver: if not dd: print("!! 找不到数据目录") sys.exit(1) align_testdata(dd) return if args.run: with open(args.run, encoding="utf-8") as f: cfg = json.load(f) run(cfg) return print("用法:gen_testdata.py --check | --run cfg.json | --delete [--yes] [--keep-files]") if __name__ == "__main__": main()