Files
pricing_review/CostReview/app/tools/rebuild_batch_db.py
2026-10-11 10:52:01 +08:00

178 lines
6.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""全量重建后台批次库(history.db)并重新导入「后台需要导入的项目」目录里的文件。
为什么需要:2026-10-01 给批次库补了层级表(sections/unit_works/divides/norm_res/remarks)
与工程量列(bills.Quantity/Total/uw_id),**已导入的老批次没有这些字段的数据**(导入时才写)。
开发阶段数据可全量重导,故直接重建,不做兼容迁移。
安全:执行前**先备份**原库到 history.db.bak_<时间戳>;失败也不会丢数据。
用法:
python app/tools/rebuild_batch_db.py # 备份 + 重建 + 导入 + 验证
python app/tools/rebuild_batch_db.py --no-import # 只备份 + 重建(不导入)
"""
import io, os, sys, shutil, sqlite3, time, hashlib, traceback
# __file__ = <根>/造价审核/app/tools/rebuild_batch_db.py
# dirname×1 = 造价审核/app/tools dirname×2 = 造价审核/app dirname×3 = 造价审核(项目根)
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DB = os.path.join(ROOT, "data", "history.db")
SCHEMA = os.path.join(ROOT, "app", "store", "schema.sql")
SRC = os.path.join(os.path.dirname(ROOT), "后台需要导入的项目")
# 起手先自检:路径不对就直接停,绝不能把库删错地方
assert os.path.isfile(SCHEMA), "schema.sql 找不到:%s" % SCHEMA
assert os.path.basename(ROOT) == "造价审核", "项目根算错了:%s" % ROOT
assert os.path.isdir(SRC), "导入目录找不到:%s" % SRC
# 价格类(信息价/市场价)走另一条导入路径,与工程文件区分
PRICE_SUFFIX = ("price_html",)
def log(s):
print(s, flush=True)
def backup():
if not os.path.exists(DB):
log(" 原库不存在,无需备份")
return None
stamp = time.strftime("%Y%m%d_%H%M%S")
dst = DB + ".bak_" + stamp
shutil.copy2(DB, dst)
for ext in ("-wal", "-shm"):
p = DB + ext
if os.path.exists(p):
shutil.copy2(p, dst + ext)
log(" 已备份 → %s (%.1f MB)" % (os.path.basename(dst), os.path.getsize(dst) / 1048576.0))
return dst
def drop():
for p in (DB, DB + "-wal", DB + "-shm"):
if os.path.exists(p):
os.remove(p)
log(" 已删除 %s" % os.path.basename(p))
def create():
sql = io.open(SCHEMA, encoding="utf-8").read()
c = sqlite3.connect(DB)
c.executescript(sql)
c.commit()
tabs = [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")]
c.close()
log(" 已按 schema.sql 建库:%d 张表" % len(tabs))
return tabs
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 main():
do_import = "--no-import" not in sys.argv
log("=" * 62)
log("全量重建批次库 history.db")
log("=" * 62)
log("\n[1/4] 备份原库")
bak = backup()
log("\n[2/4] 删除旧库")
drop()
log("\n[3/4] 按新 schema 建库")
create()
if not do_import:
log("\n(--no-import:跳过导入)")
return 0
# 导入依赖生产环境模块,这里 stub 掉测试机上没有的包
import types
sys.modules.setdefault("openpyxl", types.SimpleNamespace(
Workbook=object, load_workbook=lambda *a, **k: None))
sys.modules.setdefault("search_demo", types.SimpleNamespace(build=lambda *a, **k: None))
sys.path.insert(0, os.path.join(ROOT, "app", "server"))
import api_server as A
log("\n[4/4] 导入 %s" % SRC)
files = A.api_scan().get("files", [])
if not files:
log(" 目录里没有可导入文件")
return 1
ok, fail = 0, []
for f in files:
fn, st = f["name"], f.get("state")
price = st in PRICE_SUFFIX
body = {
"kind": "info" if price else "project",
"path": f["path"],
"name": os.path.splitext(fn)[0],
"province": "", "city": "", "district": "",
"period_from": None, "period_to": None,
"bulid_unit": "", "sha": sha1_of(f["path"]), "force": True,
}
t0 = time.time()
try:
con = A.conn()
try:
r = A.api_import(con, body)
if r.get("ok"):
con.commit()
else:
con.rollback()
finally:
con.close()
except Exception as e:
r = {"ok": False, "msg": "异常:" + str(e)}
traceback.print_exc()
dt = time.time() - t0
if r.get("ok"):
ok += 1
extra = ""
if not price:
extra = " 清单%s 定额%s 工料机%s" % (r.get("n_bill", "-"), r.get("n_norm", "-"), r.get("n_lme", "-"))
log(" [OK] %-52s %6.1fs%s" % (fn[:52], dt, extra))
else:
fail.append((fn, str(r.get("msg", ""))[:70]))
log(" [FAIL] %-50s %s" % (fn[:50], str(r.get("msg", ""))[:70]))
log("\n导入结果:成功 %d / 失败 %d" % (ok, len(fail)))
for fn, msg in fail:
log(" × %s → %s" % (fn, msg))
log("\n" + "=" * 62)
log("验证")
log("=" * 62)
c = sqlite3.connect(DB)
for t in ("batches", "bills", "norms", "lmes", "unit_works", "sections", "divides", "norm_res", "prices"):
try:
log(" %-12s %s" % (t, c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0]))
except Exception as e:
log(" %-12s 查询失败 %s" % (t, e))
log("\n各批次层级 / 工程量:")
for r in c.execute("SELECT id, Name FROM batches ORDER BY id"):
uw = c.execute("SELECT COUNT(*) FROM unit_works WHERE batch_id=?", (r[0],)).fetchone()[0]
sc = c.execute("SELECT COUNT(*) FROM sections WHERE batch_id=?", (r[0],)).fetchone()[0]
bl = c.execute("SELECT COUNT(*) FROM bills WHERE batch_id=?", (r[0],)).fetchone()[0]
q = c.execute("SELECT COUNT(*) FROM bills WHERE batch_id=? AND Quantity IS NOT NULL AND Quantity<>0",
(r[0],)).fetchone()[0]
flag = "OK" if (bl == 0 or uw > 0) else "无层级!"
log(" #%-3d %-44s 单项%s 单位工程%-4s 清单%-6s 有工程量%-6s %s"
% (r[0], str(r[1])[:44], sc, uw, bl, q, flag))
c.close()
if bak:
log("\n原库备份在:%s" % bak)
return 0 if not fail else 2
if __name__ == "__main__":
sys.exit(main())