#!/usr/bin/env python # -*- coding: utf-8 -*- """按「源文件格式」清理批次库里已导入的批次。 用途:某种格式不再支持导入后,把历史上由该格式导入的批次一并清掉,避免库里留着 「现在再也导不进来」的数据(会造成困惑:看得见、但没法重建)。 识别方式:**按源文件 SHA1 指纹匹配** batches.x_src_hash —— 不看文件名。 (实测 #13「…施工6.29xml.cos4」名字里带 xml 但其实是 cos4,按名字判断会误删。) 安全:删除前**先备份**整库;只删显式命中的批次,其余原样保留。 用法: python app/tools/purge_batches.py --by-ext .xml # 清理 xml 导入的批次 python app/tools/purge_batches.py --by-ext .xml --dry # 只列不删 python app/tools/purge_batches.py --ids 3,5,7 # 按批次 id 删 """ import io, os, sys, shutil, sqlite3, time, hashlib ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DB = os.path.join(ROOT, "data", "history.db") SRC = os.path.join(os.path.dirname(ROOT), "后台需要导入的项目") assert os.path.basename(ROOT) == "造价审核", "项目根算错了:%s" % ROOT assert os.path.isdir(SRC), "导入目录找不到:%s" % SRC def log(s): print(s, flush=True) def sha1_of(p): h = hashlib.sha1() with open(p, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def ids_by_ext(ext): """扫描导入目录里该扩展名的文件,用指纹反查批次 id""" ext = ext.lower() hashes = {} for fn in sorted(os.listdir(SRC)): if not fn.lower().endswith(ext): continue hashes[sha1_of(os.path.join(SRC, fn))] = fn c = sqlite3.connect(DB) c.row_factory = sqlite3.Row out = [] for r in c.execute("SELECT id,Name,x_src_hash FROM batches"): if r["x_src_hash"] in hashes: out.append((r["id"], str(r["Name"]), hashes[r["x_src_hash"]])) c.close() return out def purge(ids): """级联删除批次及其全部子数据""" c = sqlite3.connect(DB) before = {} for t in ("batches", "bills", "norms", "lmes", "unit_works", "sections", "divides", "norm_res", "prices", "import_log"): try: before[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0] except Exception: before[t] = None for bid in ids: c.execute("DELETE FROM norm_res WHERE norm_id IN " "(SELECT id FROM norms WHERE bill_id IN (SELECT id FROM bills WHERE batch_id=?))", (bid,)) c.execute("DELETE FROM norms WHERE bill_id IN (SELECT id FROM bills WHERE batch_id=?)", (bid,)) for t in ("bills", "lmes", "unit_works", "sections", "divides", "prices", "import_log"): try: c.execute("DELETE FROM %s WHERE batch_id=?" % t, (bid,)) except Exception: pass c.execute("DELETE FROM batches WHERE id=?", (bid,)) # 兜底:清掉任何漏网的孤儿(父行已删但子行还在) c.execute("DELETE FROM norm_res WHERE norm_id NOT IN (SELECT id FROM norms)") c.execute("DELETE FROM norms WHERE bill_id NOT IN (SELECT id FROM bills)") # divides 有两层归属(batch_id + uw_id + parent_id 层级),循环清到稳定为止 for _ in range(5): n1 = c.execute("DELETE FROM divides WHERE uw_id IS NOT NULL " "AND uw_id NOT IN (SELECT id FROM unit_works)").rowcount n2 = c.execute("DELETE FROM divides WHERE parent_id IS NOT NULL " "AND parent_id NOT IN (SELECT id FROM divides)").rowcount if n1 + n2 == 0: break c.commit() c.execute("VACUUM") c.commit() after = {} for t in before: try: after[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0] except Exception: after[t] = None c.close() return before, after def main(): dry = "--dry" in sys.argv ext = None ids = None for i, a in enumerate(sys.argv): if a == "--by-ext" and i + 1 < len(sys.argv): ext = sys.argv[i + 1] if a == "--ids" and i + 1 < len(sys.argv): ids = [int(x) for x in sys.argv[i + 1].split(",") if x.strip().isdigit()] if not os.path.exists(DB): log("库不存在:%s" % DB) return 1 if not ids and not ext: log("请指定 --by-ext <扩展名> 或 --ids ") return 1 if ext: found = ids_by_ext(ext) if not found: log("没有由 %s 导入的批次" % ext) return 0 log("匹配到 %d 个批次(按源文件指纹):" % len(found)) for bid, nm, fn in found: log(" #%-3d %-40s ← %s" % (bid, nm[:40], fn[:46])) ids = [x[0] for x in found] else: c = sqlite3.connect(DB) log("指定删除批次:") for bid in ids: r = c.execute("SELECT Name FROM batches WHERE id=?", (bid,)).fetchone() log(" #%-3d %s" % (bid, (r[0] if r else "(不存在)"))) c.close() if dry: log("\n--dry:只列出,未删除") return 0 stamp = time.strftime("%Y%m%d_%H%M%S") bak = DB + ".bak_" + stamp shutil.copy2(DB, bak) log("\n已备份 → %s (%.1f MB)" % (os.path.basename(bak), os.path.getsize(bak) / 1048576.0)) log("\n删除 %d 个批次及级联数据…" % len(ids)) before, after = purge(ids) log("\n%12s %12s %12s" % ("表", "删前", "删后")) for t in before: if before[t] is None: continue log("%12s %12s %12s" % (t, before[t], after[t])) log("\n库大小:%.1f MB" % (os.path.getsize(DB) / 1048576.0)) log("备份在:%s" % bak) return 0 if __name__ == "__main__": sys.exit(main())