From 913ed9d2c423af98c21345c6b6aa1ae47b477435 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Sat, 3 Oct 2026 11:21:03 +0800 Subject: [PATCH] =?UTF-8?q?=E5=91=BD=E5=90=8D=E6=8E=A8=E6=96=AD=E8=AE=A4?= =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E5=89=8D=E7=BC=80=E3=80=81SQL=20=E6=A3=80?= =?UTF-8?q?=E6=9F=A5=E8=AE=A4=E5=85=84=E5=BC=9F=E5=85=B3=E8=81=94=EF=BC=9A?= =?UTF-8?q?=E8=A1=A8=E5=90=8D=E5=B8=A6=E4=B8=9A=E5=8A=A1=E5=89=8D=E7=BC=80?= =?UTF-8?q?=E3=80=81=E5=88=97=E5=90=8D=E5=8F=AA=E5=86=99=E8=AF=8D=E6=A0=B9?= =?UTF-8?q?=E6=97=B6=E6=8E=A8=E4=B8=8D=E5=87=BA=E5=85=B3=E7=B3=BB=EF=BC=8C?= =?UTF-8?q?=E4=B8=A4=E5=BC=A0=E8=A1=A8=E5=90=84=E8=87=AA=E6=8C=87=E5=90=91?= =?UTF-8?q?=E5=90=8C=E4=B8=80=E5=BC=A0=E7=88=B6=E8=A1=A8=E3=80=81=E5=BD=BC?= =?UTF-8?q?=E6=AD=A4=E7=9B=B8=E8=BF=9E=E4=B9=9F=E8=A2=AB=E5=BD=93=E6=88=90?= =?UTF-8?q?=E8=BF=9E=E9=94=99=E4=BA=86=E5=88=97=E2=80=94=E2=80=94=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E7=9B=B4=E6=8E=A5=E5=AF=B9=E4=B8=8D=E4=B8=8A=E6=97=B6?= =?UTF-8?q?=E6=8C=89=E5=BC=95=E7=94=A8=E8=A1=A8=E5=85=B1=E7=94=A8=E7=9A=84?= =?UTF-8?q?=E5=89=8D=E7=BC=80=E6=89=BE=E5=94=AF=E4=B8=80=E4=B8=80=E5=BC=A0?= =?UTF-8?q?=EF=BC=8C=E5=85=84=E5=BC=9F=E5=85=B3=E8=81=94=E5=8F=AA=E6=8F=90?= =?UTF-8?q?=E7=A4=BA=E8=A1=8C=E6=95=B0=E5=8F=AF=E8=83=BD=E6=88=90=E5=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/data/catalog.py | 9 +++++ backend/app/data/sqlcheck.py | 44 ++++++++++++++++++++++-- backend/tests/fixtures/catalog/scenic.py | 8 +++-- backend/tests/test_catalog_draft.py | 25 ++++++++++++++ backend/tests/test_sqlcheck.py | 10 ++++++ 5 files changed, 91 insertions(+), 5 deletions(-) diff --git a/backend/app/data/catalog.py b/backend/app/data/catalog.py index 463a5077..05a0fdb5 100644 --- a/backend/app/data/catalog.py +++ b/backend/app/data/catalog.py @@ -882,6 +882,15 @@ def infer_name_relations(schema_cache: Mapping[str, Any] | None, table: str, *, candidates: set[str] = set() for form in _singulars(words[-1]): candidates |= index.get((prefix, form), set()) + if not candidates: + # 直接对不上:库里的表常带业务前缀(store_tags),列名却只写词根(tagId)。 + # 只认和引用它的表共用前缀的那张,从最长的共用前缀试起;仍然不止一张就不推 + own = _words(table) + for k in range(len(own) - 1, 0, -1): + for form in _singulars(words[-1]): + candidates |= index.get(("".join(own[:k]) + prefix, form), set()) + if candidates: + break if len(candidates) != 1: continue target = next(iter(candidates)) diff --git a/backend/app/data/sqlcheck.py b/backend/app/data/sqlcheck.py index e1fd9ae0..d5207577 100644 --- a/backend/app/data/sqlcheck.py +++ b/backend/app/data/sqlcheck.py @@ -169,13 +169,17 @@ class SqlChecker: 和助手挑表看到的是同一张图(catalog.relation_graph):目录里的关系,加上没起草过的表按外键、命名现推的; 被驳回的关系不进图,也不会被现推回来。 """ + return [e for e in self.edges_from(a) if e.to_table.lower() == b.lower()] + + def edges_from(self, a: str) -> list[catalog.JoinEdge]: + """从 a 出发的全部边。关系图第一次用到时才建,之后复用。""" if self._edges is None: graph = catalog.relation_graph(self._raw, schema_cache=self.schema_cache) index: dict[str, list[catalog.JoinEdge]] = {} for table, edges in graph.items(): index.setdefault(table.lower(), []).extend(edges) self._edges = index - return [e for e in self._edges.get(a.lower(), []) if e.to_table.lower() == b.lower()] + return list(self._edges.get(a.lower(), [])) # ---- 检查 @@ -557,10 +561,46 @@ class _ScopeCheck: continue # 两张表都没写目录:没有可对照的,不判 condition = " AND ".join(filter(None, (self.excerpt(c) for c in group["conds"]))) if best is None: - self._join_checks.append(self._join_unknown(a, b, candidates, condition)) + parent = self._shared_parent(a, b, pairs) + self._join_checks.append(self._join_sibling(a, b, parent, condition) if parent + else self._join_unknown(a, b, candidates, condition)) elif best.status not in _STRONG: self._join_checks.append(self._join_proposed(a, b, best, condition)) + def _shared_parent(self, a: _Table, b: _Table, pairs: set[tuple[str, str]]) -> str | None: + """兄弟关联:每一对连接列都是两边各自指向同一张父表的同一组列(a.member_id → members.id ← b.member_id)。 + 返回父表名;不是这种连法返回 None。 + + 目录里不会记 a 和 b 之间的关系,但这不是「连错了列」:比如评价表和标签关联表各自按门店编号指向门店、 + 彼此按门店编号相连。照「对不上任何关系」报警告是误报。 + """ + def parents(table: _Table, column: str) -> set[tuple[str, tuple[str, ...]]]: + return {(e.to_table.lower(), tuple(c.lower() for c in e.to_columns)) + for e in self.checker.edges_from(table.name) + if tuple(c.lower() for c in e.from_columns) == (column,) + and e.cardinality in (None, "many_to_one", "one_to_one")} + + shared: set[tuple[str, tuple[str, ...]]] | None = None + for left, right in pairs: + common = parents(a, left) & parents(b, right) + shared = common if shared is None else shared & common + if not shared: + return None + names = {table for table, _ in shared or ()} + return next(iter(names)) if len(names) == 1 else None + + def _join_sibling(self, a: _Table, b: _Table, parent: str, condition: str) -> SqlCheck: + item = (self.checker.notes_of(parent) or {}).get("label") + label = str(item["value"]) if isinstance(item, dict) and isinstance(item.get("value"), str) \ + and item["value"].strip() else parent + return SqlCheck( + code="join_unconfirmed", level="info", table=b.name, sql_excerpt=condition or None, + message=(f"「{a.label()}」与「{b.label()}」之间没有直接的关系,这里经共同的「{label}」相连。" + "关联后行数可能成倍增加:确认其中一侧每个键只有一行,或先各自汇总再关联"), + for_model=(f"{a.name} 和 {b.name} 按 {condition or '这组条件'} 关联:两边都指向 {parent},彼此是一对多对多。" + "如果其中一侧每个键不止一行,关联后另一侧的行会被重复,求和、计数会放大;" + "先把一侧筛到每个键一行(例如只取主记录),或分别汇总到这个键再关联")) + def _join_unknown(self, a: _Table, b: _Table, candidates: list[catalog.JoinEdge], condition: str) -> SqlCheck: known = ";".join(dict.fromkeys(e.condition() for e in candidates)) hint = f"目录里这两张表的关系是:{known}。照它改关联条件" if known else \ diff --git a/backend/tests/fixtures/catalog/scenic.py b/backend/tests/fixtures/catalog/scenic.py index fd7ffb87..b5269a5b 100644 --- a/backend/tests/fixtures/catalog/scenic.py +++ b/backend/tests/fixtures/catalog/scenic.py @@ -9,8 +9,9 @@ 从 visits 到 channels 要经过它,正好是两跳的连接路径。group_visits 同理(旅行团与入园记录)。 - **命名推断必须放过的列**(NOT_INFERRED):自引用(employees.employee_id 是工号,不是指向自己)、 多个候选(guide 和 guides 两张表都在,tour_assignments.guide_id 不知道指哪张)、没有对应的表 - (parking_records.lot_id、operation_logs.operator_id、categories.parentId)、类型对不上 - (feedback_forms.store_id 是文字,stores.id 是整数)。 + (operation_logs.operator_id、categories.parentId)、类型对不上(feedback_forms.store_id 是文字,stores.id 是整数)。 + parking_records.lot_id 没有直接对上的 lot / lots,但和引用它的表共用 parking 前缀的 parking_lots 只有一张, + 推得出来(在 NAME_RELATIONS 里)。 - **唯一约束 / 唯一索引。** orders.order_no、channels.channel_code 是列上的 UNIQUE;members.member_no、 visits.ticket_no 是单独建的唯一索引。 @@ -188,6 +189,8 @@ NAME_RELATIONS = frozenset({ ("tour_groups", ("agency_id",), "agencies", ("id",)), ("tour_assignments", ("tour_group_id",), "tour_groups", ("id",)), ("lost_and_found", ("park_id",), "parks", ("id",)), + # 没有 lot / lots,按引用表共用的 parking 前缀对上 parking_lots + ("parking_records", ("lot_id",), "parking_lots", ("id",)), # 视图没有约束,按列名同样推得出来:按日汇总的入园人数照样能按 park_id 连到景区 ("v_daily_visits", ("park_id",), "parks", ("id",)), }) @@ -196,7 +199,6 @@ NAME_RELATIONS = frozenset({ NOT_INFERRED = { ("employees", "employee_id"): "自引用:工号,不是指向本表", ("tour_assignments", "guide_id"): "多个候选:guide 与 guides", - ("parking_records", "lot_id"): "没有名为 lot / lots 的表", ("operation_logs", "operator_id"): "没有名为 operator / operators 的表", ("categories", "parentId"): "没有名为 parent / parents 的表", ("feedback_forms", "store_id"): "类型对不上:文字列指向整数主键", diff --git a/backend/tests/test_catalog_draft.py b/backend/tests/test_catalog_draft.py index a0d3c528..2989d92f 100644 --- a/backend/tests/test_catalog_draft.py +++ b/backend/tests/test_catalog_draft.py @@ -157,6 +157,31 @@ def test_name_inference_negative(tables, why): assert _infer(tables, next(iter(tables))) == set(), why +def test_name_inference_falls_back_to_a_table_sharing_the_prefix(): + """库里没有 tags,只有带前缀的 store_tags 和 menu_tag:和引用它的表共用 store 前缀的那张才是它要指的。 + 以前这种命名推不出关系,SQL 检查跟着误报「对不上任何关系」。""" + tables = { + "store_tag_links": _table(_col("id"), _col("tagId"), _col("storeID")), + "store_tags": _table(_col("id")), + "menu_tag": _table(_col("id")), + "store": _table(_col("id")), + } + assert _infer(tables, "store_tag_links") == { + (("tagId",), "store_tags", ("id",)), (("storeID",), "store", ("id",))} + + +@pytest.mark.parametrize("tables, why", [ + # 直接对得上就用直接的,不去找带前缀的 + ({"shop_category_links": _table(_col("id"), _col("category_id")), "categories": _table(_col("id")), + "shop_categories": _table(_col("id"))}, {(("category_id",), "categories", ("id",))}), + # 引用它的表没有可共用的前缀:带前缀的表不止一张时照旧不推 + ({"links": _table(_col("id"), _col("tag_id")), "store_tags": _table(_col("id")), + "menu_tags": _table(_col("id"))}, set()), +]) +def test_prefix_fallback_only_when_direct_match_is_missing(tables, why): + assert _infer(tables, next(iter(tables))) == why + + def test_name_inference_one_to_one_when_column_is_own_key(): tables = {"member_profiles": _table(_col("member_id"), pk=("member_id",)), "members": _table(_col("id"))} rel = catalog.infer_name_relations(_source(tables).schema_cache, "member_profiles")[0] diff --git a/backend/tests/test_sqlcheck.py b/backend/tests/test_sqlcheck.py index 79c896e7..329087b8 100644 --- a/backend/tests/test_sqlcheck.py +++ b/backend/tests/test_sqlcheck.py @@ -254,6 +254,16 @@ async def test_join_unconfirmed_negative(cache, sql): assert "join_unconfirmed" not in codes(cache, sql) +async def test_sibling_join_through_a_shared_parent_is_only_a_note(cache): + """两张表各自按 member_id 指向会员(都是外键),彼此按 member_id 相连:目录里没有这两张表之间的关系, + 但这是经共同父表推得出来的连法,不是「连错了列」。只提示一句:关联后行数可能成倍增加。""" + sql = "SELECT COUNT(*) FROM orders o JOIN member_tag_links t ON t.member_id = o.member_id WHERE o.status = 1" + [check] = [c for c in run(cache, sql) if c.code == "join_unconfirmed"] + assert check.level == "info" + assert "会员" in check.message or "members" in check.message + assert "成倍" in check.message + + async def test_join_level_follows_status(cache): sql = "SELECT SUM(i.amount) FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.status = 1" assert "join_unconfirmed" not in codes(cache, sql, "confirmed")