feat(core): 工料机子级按单位工程源声明入库,不跨单位并集
This commit is contained in:
@@ -266,18 +266,23 @@ def wipe(con, sid, clean_orphans=True):
|
||||
|
||||
|
||||
def dedupe_lme_res(con=None):
|
||||
"""存量自愈:s_lme_res 按 (session_id, p_code, res_code) 去重,保最新一行。
|
||||
"""存量自愈:s_lme_res 按 (session_id, uw_id, p_code, res_code) 去重,保最新一行。
|
||||
|
||||
2026-10-10 一次性清理(上面 wipe 漏表的存量受害者),幂等——反复跑无副作用。
|
||||
2026-11-04 主人定「耗弹框不许重复」:去重键去掉 qty/seq——此前同码不同 qty/seq 的重复套
|
||||
(采纳补子级跨批次灌入的脏数据)能躲过去重、弹框照样重复;组成同码只该有一条。
|
||||
保留 MAX(rowid):越新的行采集口径越全(name 列早期常为空)。"""
|
||||
决策 351(2026-11-15):去重按**同一单位内**同码——不同单位各有各的源声明,不能跨单位删;
|
||||
同单位同码重复才是脏数据。保留 MAX(rowid):越新的行采集口径越全。"""
|
||||
own = con is None
|
||||
if own:
|
||||
con = connect()
|
||||
try:
|
||||
_cols = {x[1] for x in con.execute("PRAGMA table_info(s_lme_res)")}
|
||||
except Exception:
|
||||
_cols = set()
|
||||
_grp = "session_id, p_code, res_code" if "uw_id" not in _cols else \
|
||||
"session_id, uw_id, p_code, res_code"
|
||||
con.execute("""DELETE FROM s_lme_res WHERE rowid NOT IN
|
||||
(SELECT MAX(rowid) FROM s_lme_res
|
||||
GROUP BY session_id, p_code, res_code)""")
|
||||
GROUP BY %s)""" % _grp)
|
||||
if own:
|
||||
con.commit()
|
||||
con.close()
|
||||
@@ -498,6 +503,7 @@ def upgrade_cols(con):
|
||||
"""老库补列(已存在的列报 duplicate column 忽略)。connect() 与 open_project
|
||||
双入口共用——测试手建库/直连 open_project 的路径同样自愈(决策322 收口)。"""
|
||||
# ⚠️ 每个表各补各的 —— 别把 A 表的列塞进 B 表的循环里,那会给 B 表凭空造出无用列
|
||||
_created_at_just_added = False # 决策 334 补记一:本次 upgrade_cols 是否刚补出 sessions.created_at
|
||||
for tbl, cols in (
|
||||
# 2026-10-06:x_batch_id = 后台批次 id(同一份源文件导入过就能关联上,
|
||||
# 工作台靠它只读展示该项目的询价附件)。老库没有这列,这里补。
|
||||
@@ -505,7 +511,9 @@ def upgrade_cols(con):
|
||||
"x_info TEXT", "x_feat TEXT", "x_batch_id INTEGER",
|
||||
"x_manual INTEGER DEFAULT 0",
|
||||
# 决策 245(2026-11-01):单价类型随「打开项目」落库(老库补列)
|
||||
"file_kind INTEGER")),
|
||||
"file_kind INTEGER",
|
||||
# 决策 334 补记一(2026-11-15 主人定):创建时间=导入那一刻写死永不变化
|
||||
"created_at TEXT")),
|
||||
("s_unit_works", ("section_id INTEGER",
|
||||
"Construction REAL", "DivisionalAndElementalWorks REAL",
|
||||
"Preliminaries REAL", "CostForHSE REAL",
|
||||
@@ -567,13 +575,38 @@ def upgrade_cols(con):
|
||||
for col in cols:
|
||||
try:
|
||||
con.execute("ALTER TABLE %s ADD COLUMN %s" % (tbl, col))
|
||||
# 决策 334 补记一:标记「这次升级刚补出创建时间列」= 老库第一次升级,出循环后回填一次
|
||||
if tbl == "sessions" and col.split()[0] == "created_at":
|
||||
_created_at_just_added = True
|
||||
except Exception as e:
|
||||
if "duplicate column" not in str(e).lower():
|
||||
# 幂等补列:列已存在是正常路径;其余失败要喊出来(2026-10-07)
|
||||
print("补列失败 %s.%s:%s" % (tbl, col.split()[0], e), flush=True)
|
||||
# 决策 334 补记一(2026-11-15 主人定「甲案」):创建时间老行**只在补出这列的那一次**回填——
|
||||
# 旧行唯一已知的导入时刻就是它的 imported_at;此后重新解析的 UPDATE 永不碰这列,只有删除后
|
||||
# 重新导入(新 INSERT)才产生新时刻。
|
||||
# ⚠️ 不许改成「每次 connect 都 UPDATE WHERE NULL」:那是 upgrade_cols 里第一个无条件写,
|
||||
# 会持着写锁撞上启动里的其他会话库连接(database is locked,实测启动 2 秒变 35 秒)。
|
||||
# 回填与 ALTER 同一事务、立刻提交放锁;提交前进程崩 = 连列带回填一起回滚,下次重走(自愈)。
|
||||
if _created_at_just_added:
|
||||
con.execute("UPDATE sessions SET created_at=imported_at WHERE created_at IS NULL")
|
||||
con.commit()
|
||||
# 2026-10-01:分组/匹配 设置的持久化(分组关键词、匹配过滤词)
|
||||
con.execute("""CREATE TABLE IF NOT EXISTS s_settings(
|
||||
scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT, PRIMARY KEY(scope,k))""")
|
||||
# 决策 334 补记一:老库回填兜底(设置键整库只跑一次)。v1 曾出过「半迁移态」——ALTER 是
|
||||
# DDL 自动提交,回填 UPDATE 却随调用方 close() 回滚(列已在、行全 NULL,真库 2026-11-15
|
||||
# 实录),此后 flag 判「列已在」永远补不回。这里见 NULL 就修、修完落设置键,不再有每次
|
||||
# connect 的常驻写(锁口径同上)。新库/已迁移库此句零行,毫秒级空转。
|
||||
try:
|
||||
_mig = con.execute(
|
||||
"SELECT v FROM s_settings WHERE scope='sys' AND k='mig_created_at_334'").fetchone()
|
||||
if _mig is None:
|
||||
con.execute("UPDATE sessions SET created_at=imported_at WHERE created_at IS NULL")
|
||||
con.execute("INSERT OR REPLACE INTO s_settings(scope,k,v) VALUES('sys','mig_created_at_334','1')")
|
||||
con.commit()
|
||||
except Exception as e:
|
||||
print("创建时间回填兜底失败(不影响启动):%s" % e, flush=True)
|
||||
return con
|
||||
|
||||
|
||||
@@ -588,6 +621,17 @@ def connect():
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
except Exception:
|
||||
pass
|
||||
# 2026-11-15 性能(主人拍板「开干」):大库批量写入提速。默认页缓存只有 2MB,
|
||||
# 287MB 会话库写 15 万行时逐页换入换出,「打开大工程等一会」的大头就在这——
|
||||
# 实测同一份 71.9MB 件:写库 5.10s→2.18s,整次打开 9.75s→6.74s。
|
||||
# synchronous=NORMAL 仅对 WAL 生效(官方推荐组合):断电/蓝屏最多丢最后一次提交,
|
||||
# 库本身不会损坏;会话库是临时审核数据,主人 2026-11-15 拍板接受。
|
||||
try:
|
||||
con.execute("PRAGMA cache_size=-131072") # 128MB 页缓存
|
||||
con.execute("PRAGMA temp_store=MEMORY")
|
||||
con.execute("PRAGMA synchronous=NORMAL")
|
||||
except Exception:
|
||||
pass
|
||||
con.executescript(io.open(SCHEMA, encoding="utf-8").read())
|
||||
upgrade_cols(con) # 老库补列(提取共用,open_project 同款)
|
||||
return con
|
||||
@@ -613,13 +657,15 @@ def open_project(con, files, meta, job, sid=None):
|
||||
if pf is not None and pt is not None and int(pt) < int(pf):
|
||||
pf, pt = pt, pf
|
||||
if sid is None:
|
||||
# 决策 334 补记一:created_at=导入那一刻写死(重新解析走下面 UPDATE 分支,永不碰它)
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district,
|
||||
bulid_unit, file_kind, src_name, imported_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
bulid_unit, file_kind, src_name, imported_at, created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(meta.get("name") or "", pf, pf, pt,
|
||||
meta.get("province", ""), meta.get("city", ""), meta.get("district", ""),
|
||||
meta.get("bulid_unit", ""), _fk(meta.get("file_kind")),
|
||||
";".join(n for _, n in files),
|
||||
time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
else:
|
||||
@@ -872,24 +918,31 @@ def open_project(con, files, meta, job, sid=None):
|
||||
else:
|
||||
_nr_agg[k] = (q, express)
|
||||
_nr_order.append(k)
|
||||
_nr_rows = []
|
||||
for nidx, code in _nr_order:
|
||||
q, express = _nr_agg[(nidx, code)]
|
||||
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
|
||||
cur.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
||||
(nid, code, q, express or None))
|
||||
_nr_rows.append((nid, code, q, express or None))
|
||||
stat["nres"] = stat.get("nres", 0) + 1
|
||||
# 2026-11-15 性能:10 万级消耗量一次 executemany(逐条 execute 时这一张表就占 1.4–2.2s)
|
||||
if _nr_rows:
|
||||
cur.executemany("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
||||
_nr_rows)
|
||||
|
||||
for num, nm, spec, unit, ntp, tax, tp, qty, kind in out["lmes"]:
|
||||
cur.execute("""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, x_hash_semi)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, num, nm, spec, unit, qty, ntp, tax, tp, kind,
|
||||
norm(nm), norm(spec), norm(unit), md5(nm, spec, unit), md5(nm, unit)))
|
||||
stat["lme"] += 1
|
||||
# 2026-11-15 性能:工料机两表按批写(无逐行 id 依赖,口径不变)
|
||||
_lme_rows = [(sid, num, nm, spec, unit, qty, ntp, tax, tp, kind,
|
||||
norm(nm), norm(spec), norm(unit), md5(nm, spec, unit), md5(nm, unit))
|
||||
for num, nm, spec, unit, ntp, tax, tp, qty, kind in out["lmes"]]
|
||||
if _lme_rows:
|
||||
cur.executemany("""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, x_hash_semi)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", _lme_rows)
|
||||
stat["lme"] += len(_lme_rows)
|
||||
|
||||
# 2026-10-11 决策 41:各单位工程**自己的工料机汇总**按 uw 归属原样入库(s_lme_uw),
|
||||
# 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
|
||||
_luw_rows = []
|
||||
for _i, _row in enumerate(out.get("lme_uw") or []):
|
||||
k, num, nm, spec, unit, ntp, tax, tp, qty, kind = _row[:10]
|
||||
_x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(SWT/老结构为 None)
|
||||
@@ -899,22 +952,67 @@ def open_project(con, files, meta, job, sid=None):
|
||||
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
|
||||
if not uwid:
|
||||
continue
|
||||
cur.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind,
|
||||
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags, x_rid)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp) + tuple(_x)
|
||||
+ (_flags, _rid))
|
||||
_luw_rows.append((sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp)
|
||||
+ tuple(_x) + (_flags, _rid))
|
||||
if _luw_rows:
|
||||
cur.executemany("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind,
|
||||
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags, x_rid)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", _luw_rows)
|
||||
|
||||
# 2026-10-02:机械台班 / 配合比的下一级组成(s_lme_res)
|
||||
# 决策 351(2026-11-15 主人定):子级**按本单位工程源声明原样入库**(带 uw_id),
|
||||
# 行数/码/含量逐行等于源声明;本单位没有的才用项目级声明;不跨单位并集。
|
||||
_lname = out.get("lme_name") or {}
|
||||
for pcode, subs in (out.get("lme_res") or {}).items():
|
||||
_wrote_edge = False
|
||||
for pcode, subs in (out.get("lme_res_uw") or {}).items():
|
||||
for i, (uidx, code, q) in enumerate(subs):
|
||||
if not code:
|
||||
continue
|
||||
_uwid = uw_ids[uidx] if (uidx is not None and 0 <= uidx < len(uw_ids)) else None
|
||||
_nm = _lname.get(code) or _lname.get(code.split("-")[0]) or None
|
||||
cur.execute("""INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name, uw_id)
|
||||
VALUES(?,?,?,?,?,?,?)""", (sid, pcode, code, q, i, _nm, _uwid))
|
||||
stat["lres"] = stat.get("lres", 0) + 1
|
||||
_wrote_edge = True
|
||||
for pcode, subs in (out.get("lme_res_proj") or {}).items():
|
||||
for i, (code, q) in enumerate(subs):
|
||||
if not code:
|
||||
continue
|
||||
_nm = _lname.get(code) or _lname.get(code.split("-")[0]) or None
|
||||
cur.execute("""INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)
|
||||
VALUES(?,?,?,?,?,?)""", (sid, pcode, code, q, i, _nm))
|
||||
cur.execute("""INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name, uw_id)
|
||||
VALUES(?,?,?,?,?,?,NULL)""", (sid, pcode, code, q, i, _nm))
|
||||
stat["lres"] = stat.get("lres", 0) + 1
|
||||
_wrote_edge = True
|
||||
if not _wrote_edge:
|
||||
# 老/假解析器只填 lme_res(无单位归属)→ 按项目级旧口径落,行为不变
|
||||
for pcode, subs in (out.get("lme_res") or {}).items():
|
||||
for i, (code, q) in enumerate(subs):
|
||||
if not code:
|
||||
continue
|
||||
_nm = _lname.get(code) or _lname.get(code.split("-")[0]) or None
|
||||
cur.execute("""INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name)
|
||||
VALUES(?,?,?,?,?,?)""", (sid, pcode, code, q, i, _nm))
|
||||
stat["lres"] = stat.get("lres", 0) + 1
|
||||
|
||||
# 决策 351 闸(2026-11-15 主人定「单位工程子级=源声明行数,不出 6/4 条」):
|
||||
# 逐单位逐母码,库内行数必须等于源声明行数——多一行少一行当场拦,不允许带病入库。
|
||||
if out.get("lme_res_uw"):
|
||||
_exp = {}
|
||||
for pcode, subs in out["lme_res_uw"].items():
|
||||
for uidx, code, q in subs:
|
||||
if not code:
|
||||
continue
|
||||
_uwid = uw_ids[uidx] if (uidx is not None and 0 <= uidx < len(uw_ids)) else None
|
||||
_exp[(pcode, _uwid)] = _exp.get((pcode, _uwid), 0) + 1
|
||||
for (pcode, _uwid), _n in _exp.items():
|
||||
_got = cur.execute("""SELECT COUNT(*) FROM s_lme_res
|
||||
WHERE session_id=? AND p_code=? AND uw_id IS ?""",
|
||||
(sid, pcode, _uwid)).fetchone()[0]
|
||||
if _got != _n:
|
||||
raise RuntimeError(
|
||||
"决策 351 子级行数闸:单位 %s 母码 %s 库内 %d 行,源声明 %d 行"
|
||||
% (_uwid, pcode, _got, _n))
|
||||
stat["edge_gate"] = len(_exp)
|
||||
|
||||
# 2026-10-07:项目级工料机资源库(s_lme_lib)——与批次库 lme_lib 同口径,
|
||||
# 源文件汇总节点全集,子目工料机名称/规格的兜底来源
|
||||
|
||||
Reference in New Issue
Block a user