sql-dialect-master 1.11.0__tar.gz → 1.12.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/README.md +1 -1
  3. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/metadata.py +2 -2
  4. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/ir.py +23 -0
  5. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/orchestrator.py +184 -4
  6. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/renderer.py +147 -1
  7. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/pyproject.toml +1 -1
  8. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/PKG-INFO +2 -2
  9. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/LICENSE +0 -0
  10. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/__init__.py +0 -0
  11. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/__init__.py +0 -0
  12. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/auth.py +0 -0
  13. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/client_identity.py +0 -0
  14. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/main.py +0 -0
  15. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/metrics.py +0 -0
  16. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/middleware.py +0 -0
  17. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/rate_limit_store.py +0 -0
  18. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/readiness.py +0 -0
  19. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/api/workers.py +0 -0
  20. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/__init__.py +0 -0
  21. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/cache.py +0 -0
  22. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/column_hint_validation.py +0 -0
  23. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/config.py +0 -0
  24. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/constants.py +0 -0
  25. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/exceptions.py +0 -0
  26. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/function_call_scanner.py +0 -0
  27. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/function_semantics.py +0 -0
  28. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/functions_db.json +0 -0
  29. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/functions_lookup.py +0 -0
  30. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql.py +0 -0
  31. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/__init__.py +0 -0
  32. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  33. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  34. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  35. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/evidence.py +0 -0
  36. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/mappings.py +0 -0
  37. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/relations.py +0 -0
  38. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/templates.py +0 -0
  39. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  40. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_legacy.py +0 -0
  41. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_llm.py +0 -0
  42. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  43. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  44. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  45. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  46. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  47. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  48. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  49. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  50. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  51. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  52. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/validation.py +0 -0
  53. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_schema.py +0 -0
  54. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/setup.cfg +0 -0
  67. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  68. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  69. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  70. {sql_dialect_master-1.11.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sql-dialect-master
3
- Version: 1.11.0
3
+ Version: 1.12.0
4
4
  Summary: SQL Dialect Master - Multi-database SQL conversion engine
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -38,7 +38,7 @@ Dynamic: license-file
38
38
 
39
39
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
40
40
 
41
- Current release: 1.11.0
41
+ Current release: 1.12.0
42
42
 
43
43
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
44
44
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -2,7 +2,7 @@
2
2
 
3
3
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
4
4
 
5
- Current release: 1.11.0
5
+ Current release: 1.12.0
6
6
 
7
7
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -17,8 +17,8 @@ Design rules:
17
17
  from __future__ import annotations
18
18
 
19
19
  # ── Release version facts (sole source of truth) ────────────────────────
20
- PROJECT_VERSION = "1.11.0"
21
- API_VERSION = "1.11.0"
20
+ PROJECT_VERSION = "1.12.0"
21
+ API_VERSION = "1.12.0"
22
22
  # Frontend v2 architecture — independent of the product release version.
23
23
  FRONTEND_ARCHITECTURE_VERSION = 2
24
24
 
@@ -21,6 +21,26 @@ class DistinctCountPlan:
21
21
  exclude_null_identity: bool = True
22
22
 
23
23
 
24
+ @dataclass(frozen=True)
25
+ class PathStep:
26
+ """One validated relationship edge in a schema-only count path."""
27
+
28
+ from_table: str
29
+ to_table: str
30
+ column_pairs: tuple[tuple[str, str], ...]
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class PathDistinctCountPlan:
35
+ """Validated two-hop target identity count plan."""
36
+
37
+ subject_table: str
38
+ path_steps: tuple[PathStep, ...]
39
+ group_identity: tuple[str, ...]
40
+ target_identity: tuple[str, ...]
41
+ exclude_null_identity: bool = True
42
+
43
+
24
44
  @dataclass
25
45
  class QueryIR:
26
46
  """Structured intermediate representation for an NL2SQL query.
@@ -45,6 +65,7 @@ class QueryIR:
45
65
  evidence: GenerationEvidence = field(default_factory=GenerationEvidence)
46
66
  orderings: Optional[List[Tuple[str, str]]] = None
47
67
  distinct_count_plan: Optional[DistinctCountPlan] = None
68
+ path_distinct_count_plan: Optional[PathDistinctCountPlan] = None
48
69
 
49
70
 
50
71
  def build_ir(
@@ -61,6 +82,7 @@ def build_ir(
61
82
  dialect: str,
62
83
  orderings: Optional[List[Tuple[str, str]]] = None,
63
84
  distinct_count_plan: Optional[DistinctCountPlan] = None,
85
+ path_distinct_count_plan: Optional[PathDistinctCountPlan] = None,
64
86
  ) -> QueryIR:
65
87
  """Thin positional-arg adapter mirroring the legacy call site.
66
88
 
@@ -81,4 +103,5 @@ def build_ir(
81
103
  dialect=dialect,
82
104
  orderings=orderings,
83
105
  distinct_count_plan=distinct_count_plan,
106
+ path_distinct_count_plan=path_distinct_count_plan,
84
107
  )
@@ -1355,7 +1355,7 @@ class PipelineNL2SQLGenerator:
1355
1355
  raise SchemaValidationError("complex whose predicates are unsupported")
1356
1356
  stripped_tail = tail.strip()
1357
1357
  if stripped_tail and not re.match(
1358
- r"^(?:and|order(?:ed)?\s+by|sort(?:ed)?\s+by)\b",
1358
+ r"^(?:and|order(?:ed)?\s+by|sort(?:ed)?\s+by|limit)\b",
1359
1359
  stripped_tail,
1360
1360
  re.IGNORECASE,
1361
1361
  ):
@@ -1856,6 +1856,132 @@ class PipelineNL2SQLGenerator:
1856
1856
  })
1857
1857
  return subject, joins
1858
1858
 
1859
+ def _schema_resolve_multihop_unique_path(
1860
+ self,
1861
+ text: str,
1862
+ table_hint: Optional[str],
1863
+ schema: SchemaContext,
1864
+ ) -> tuple[SchemaTableContext, tuple[object, ...], tuple[int, int]] | None:
1865
+ """Resolve one bounded two-hop path for a subject-grouped unique count."""
1866
+ if not self._schema_unique_count_spans(text, ("count", None)):
1867
+ return None
1868
+ executable = mask_non_executable(text)
1869
+ group_match = re.search(
1870
+ r"\b(?:per|each)\s+([A-Za-z_][A-Za-z0-9_$]*)\b",
1871
+ executable,
1872
+ re.IGNORECASE,
1873
+ )
1874
+ if group_match is None:
1875
+ group_match = re.search(
1876
+ r"(?:每个|各个|每位)\s*([\u4e00-\u9fff]{1,8}?)"
1877
+ r"(?=的|数量|数|$)",
1878
+ executable,
1879
+ )
1880
+ if group_match is None:
1881
+ return None
1882
+ label = group_match.group(1)
1883
+ if table_hint:
1884
+ subject_candidates = schema.table_candidates(table_hint)
1885
+ else:
1886
+ subject_candidates = schema.table_candidates(label)
1887
+ if not subject_candidates:
1888
+ mapped = {
1889
+ pattern: table
1890
+ for pattern, table in self.TABLE_PATTERNS.items()
1891
+ if pattern.casefold() == label.casefold()
1892
+ }
1893
+ subject_candidates = tuple(
1894
+ candidate
1895
+ for table_name in mapped.values()
1896
+ for candidate in schema.table_candidates(table_name)
1897
+ )
1898
+ if not subject_candidates:
1899
+ return None
1900
+ if len(subject_candidates) != 1:
1901
+ raise SchemaValidationError("multi-hop group subject is not unique")
1902
+ subject = subject_candidates[0]
1903
+ if not subject.primary_key:
1904
+ raise SchemaValidationError("multi-hop group subject has no primary key")
1905
+
1906
+ masked_group = self._schema_mask_span(executable, group_match.span())
1907
+ mentions = self._schema_table_mentions(masked_group, schema)
1908
+ target_candidates = tuple(table for table in mentions if table.key != subject.key)
1909
+ if len(target_candidates) != 1:
1910
+ raise SchemaValidationError("multi-hop target table is not unique")
1911
+ target = target_candidates[0]
1912
+ if not target.primary_key:
1913
+ raise SchemaValidationError("multi-hop target has no primary key")
1914
+
1915
+ direct = schema.relationship_candidates(subject.name, target.name)
1916
+ if len(direct) > 1:
1917
+ raise SchemaValidationError("direct multi-hop target relationship is ambiguous")
1918
+ if direct:
1919
+ return None
1920
+
1921
+ def complete_edge(edge, left: SchemaTableContext, right: SchemaTableContext) -> bool:
1922
+ if left.key == edge.from_table.casefold():
1923
+ pairs = edge.column_pairs
1924
+ else:
1925
+ pairs = tuple((to_column, from_column) for from_column, to_column in edge.column_pairs)
1926
+ if len(left.primary_key) > 1 and not {
1927
+ pair[0].casefold() for pair in pairs
1928
+ }.issuperset(column.casefold() for column in left.primary_key):
1929
+ return False
1930
+ if len(right.primary_key) > 1 and not {
1931
+ pair[1].casefold() for pair in pairs
1932
+ }.issuperset(column.casefold() for column in right.primary_key):
1933
+ return False
1934
+ return True
1935
+
1936
+ def oriented_step(edge, left: SchemaTableContext, right: SchemaTableContext):
1937
+ if edge.from_table.casefold() == left.key:
1938
+ pairs = edge.column_pairs
1939
+ else:
1940
+ pairs = tuple((to_column, from_column) for from_column, to_column in edge.column_pairs)
1941
+ return _nl2sql_ir.PathStep(left.name, right.name, tuple(pairs))
1942
+
1943
+ queue: list[tuple[SchemaTableContext, list[object]]] = [(subject, [])]
1944
+ paths: list[list[object]] = []
1945
+ expansions = 0
1946
+ while queue:
1947
+ current, path = queue.pop(0)
1948
+ if len(path) >= 2:
1949
+ continue
1950
+ for edge in schema.relationships:
1951
+ endpoints = {edge.from_table.casefold(), edge.to_table.casefold()}
1952
+ if current.key not in endpoints:
1953
+ continue
1954
+ next_name = (
1955
+ edge.to_table
1956
+ if edge.from_table.casefold() == current.key
1957
+ else edge.from_table
1958
+ )
1959
+ candidates = schema.table_candidates(next_name)
1960
+ if len(candidates) != 1:
1961
+ continue
1962
+ next_table = candidates[0]
1963
+ if next_table.key == subject.key or any(
1964
+ step.to_table.casefold() == next_table.key for step in path
1965
+ ):
1966
+ continue
1967
+ expansions += 1
1968
+ if expansions > 4096:
1969
+ raise SchemaValidationError("multi-hop path search budget exceeded")
1970
+ if not complete_edge(edge, current, next_table):
1971
+ continue
1972
+ next_path = [*path, oriented_step(edge, current, next_table)]
1973
+ if next_table.key == target.key:
1974
+ paths.append(next_path)
1975
+ else:
1976
+ queue.append((next_table, next_path))
1977
+ if not paths:
1978
+ raise SchemaValidationError("multi-hop target path is missing")
1979
+ shortest_length = min(len(path) for path in paths)
1980
+ shortest = [path for path in paths if len(path) == shortest_length]
1981
+ if shortest_length != 2 or len(shortest) != 1:
1982
+ raise SchemaValidationError("multi-hop target path is ambiguous or unsupported")
1983
+ return subject, tuple(shortest[0]), group_match.span()
1984
+
1859
1985
  def _schema_finalize(
1860
1986
  self, result: NL2SQLResult, schema: SchemaContext
1861
1987
  ) -> NL2SQLResult:
@@ -1899,8 +2025,17 @@ class PipelineNL2SQLGenerator:
1899
2025
  joined_with_resolution = self._schema_resolve_joined_with(
1900
2026
  text, table_hint, schema
1901
2027
  )
1902
- label_resolution = None
2028
+ multihop_unique_resolution = None
1903
2029
  if joined_on_resolution is None and joined_with_resolution is None:
2030
+ multihop_unique_resolution = self._schema_resolve_multihop_unique_path(
2031
+ text, table_hint, schema
2032
+ )
2033
+ label_resolution = None
2034
+ if (
2035
+ joined_on_resolution is None
2036
+ and joined_with_resolution is None
2037
+ and multihop_unique_resolution is None
2038
+ ):
1904
2039
  label_resolution = self._schema_resolve_english_group_label(executable_text, schema)
1905
2040
  if label_resolution is None:
1906
2041
  label_resolution = self._schema_resolve_chinese_group_label(executable_text, schema)
@@ -1922,6 +2057,10 @@ class PipelineNL2SQLGenerator:
1922
2057
  elif joined_with_resolution is not None:
1923
2058
  table_context, joins, joined_with_span = joined_with_resolution
1924
2059
  metric_text = self._schema_mask_span(text_lower, joined_with_span)
2060
+ elif multihop_unique_resolution is not None:
2061
+ table_context, path_steps, group_span = multihop_unique_resolution
2062
+ joins = []
2063
+ metric_text = self._schema_mask_span(text_lower, group_span)
1925
2064
  elif label_resolution is not None:
1926
2065
  table_context = label_resolution[0]
1927
2066
  label_group_column = label_resolution[1]
@@ -1933,6 +2072,7 @@ class PipelineNL2SQLGenerator:
1933
2072
  metric_text = text_lower
1934
2073
  whose_resolution = self._schema_resolve_whose(text, table_context, schema)
1935
2074
  whose_condition = None
2075
+ ordinary_conditions: list[str] = []
1936
2076
  condition_text = text_lower
1937
2077
  condition_original = text
1938
2078
  if joined_on_span is not None:
@@ -1949,6 +2089,8 @@ class PipelineNL2SQLGenerator:
1949
2089
  count_metric = self._schema_resolve_count_metric(
1950
2090
  text_lower, table_context, schema
1951
2091
  )
2092
+ if multihop_unique_resolution is not None and count_metric is None:
2093
+ count_metric = ("count", None)
1952
2094
  unique_count_spans = self._schema_unique_count_spans(
1953
2095
  text_lower, count_metric
1954
2096
  )
@@ -1966,6 +2108,7 @@ class PipelineNL2SQLGenerator:
1966
2108
  table_context,
1967
2109
  schema,
1968
2110
  )
2111
+ ordinary_conditions = list(conditions)
1969
2112
  if whose_condition is not None:
1970
2113
  conditions = [*conditions, whose_condition]
1971
2114
  parsed = self._parse_text(text_lower, text)
@@ -1975,7 +2118,9 @@ class PipelineNL2SQLGenerator:
1975
2118
  metric_text, table_context, schema, count_metric
1976
2119
  )
1977
2120
  group_by = (
1978
- [label_group_column]
2121
+ []
2122
+ if multihop_unique_resolution is not None
2123
+ else [label_group_column]
1979
2124
  if label_resolution is not None
1980
2125
  else self._schema_resolve_group_by(
1981
2126
  self._schema_mask_clause_tail(text_lower)
@@ -1988,6 +2133,7 @@ class PipelineNL2SQLGenerator:
1988
2133
  )
1989
2134
  distinct = self._check_distinct(text_lower)
1990
2135
  distinct_count_plan = None
2136
+ path_distinct_count_plan = None
1991
2137
  if unique_count_intent:
1992
2138
  if len(unique_count_spans) != 1:
1993
2139
  raise SchemaValidationError(
@@ -2004,6 +2150,35 @@ class PipelineNL2SQLGenerator:
2004
2150
  raise SchemaValidationError(
2005
2151
  "unique count with relationships is unsupported"
2006
2152
  )
2153
+ if multihop_unique_resolution is not None:
2154
+ if whose_condition is not None:
2155
+ qualified = re.match(
2156
+ r"([A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)*)\."
2157
+ r"[A-Za-z_][A-Za-z0-9_$]*",
2158
+ whose_condition,
2159
+ )
2160
+ if qualified and qualified.group(1).casefold() != table_context.key:
2161
+ raise SchemaValidationError(
2162
+ "multi-hop unique count whose predicate is not subject-owned"
2163
+ )
2164
+ if ordinary_conditions:
2165
+ raise SchemaValidationError(
2166
+ "multi-hop unique count only supports subject whose predicates"
2167
+ )
2168
+ if self._schema_has_explicit_ordering(text_lower):
2169
+ raise SchemaValidationError(
2170
+ "multi-hop unique count ordering is unsupported"
2171
+ )
2172
+ subject, path_steps, _ = multihop_unique_resolution
2173
+ path_distinct_count_plan = _nl2sql_ir.PathDistinctCountPlan(
2174
+ subject_table=subject.name,
2175
+ path_steps=tuple(path_steps),
2176
+ group_identity=tuple(subject.primary_key),
2177
+ target_identity=tuple(
2178
+ schema.table_candidates(path_steps[-1].to_table)[0].primary_key
2179
+ ),
2180
+ exclude_null_identity=True,
2181
+ )
2007
2182
  if len(table_context.primary_key) == 0:
2008
2183
  raise SchemaValidationError(
2009
2184
  "unique count requires a declared primary key"
@@ -2015,7 +2190,9 @@ class PipelineNL2SQLGenerator:
2015
2190
  raise SchemaValidationError(
2016
2191
  "unique count cannot combine with non-COUNT aggregation"
2017
2192
  )
2018
- if len(table_context.primary_key) == 1:
2193
+ if path_distinct_count_plan is not None:
2194
+ aggregations = []
2195
+ elif len(table_context.primary_key) == 1:
2019
2196
  aggregations = [
2020
2197
  f"COUNT(DISTINCT {table_context.primary_key[0]}) AS count"
2021
2198
  ]
@@ -2073,6 +2250,7 @@ class PipelineNL2SQLGenerator:
2073
2250
  dialect,
2074
2251
  orderings=orderings,
2075
2252
  distinct_count_plan=distinct_count_plan,
2253
+ path_distinct_count_plan=path_distinct_count_plan,
2076
2254
  )
2077
2255
  result = self._apply_confidence_policy(NL2SQLResult(
2078
2256
  success=sql is not None,
@@ -2281,6 +2459,7 @@ class PipelineNL2SQLGenerator:
2281
2459
  dialect,
2282
2460
  orderings=None,
2283
2461
  distinct_count_plan=None,
2462
+ path_distinct_count_plan=None,
2284
2463
  ) -> tuple:
2285
2464
  """Build SQL statement from extracted components.
2286
2465
 
@@ -2293,6 +2472,7 @@ class PipelineNL2SQLGenerator:
2293
2472
  group_by, ordering, limit, joins, distinct, dialect,
2294
2473
  orderings=orderings,
2295
2474
  distinct_count_plan=distinct_count_plan,
2475
+ path_distinct_count_plan=path_distinct_count_plan,
2296
2476
  )
2297
2477
  return _render_sql_impl(ir)
2298
2478
 
@@ -24,7 +24,7 @@ from ..nl2sql_components.evidence import (
24
24
  GenerationEvidence,
25
25
  )
26
26
  from .dialect import apply_dialect_adjustments
27
- from .ir import DistinctCountPlan, QueryIR
27
+ from .ir import DistinctCountPlan, PathDistinctCountPlan, QueryIR
28
28
  from .validation import validate_sql
29
29
 
30
30
 
@@ -239,6 +239,148 @@ def _render_distinct_count_plan(
239
239
  return sql, " | ".join(explanation_parts), evidence.score, evidence
240
240
 
241
241
 
242
+ def _qualify_subject_condition(condition: str, subject_table: str) -> str:
243
+ """Qualify simple whose predicates against the outer subject table."""
244
+ pattern = re.compile(
245
+ r"(?<![\w$.])([A-Za-z_][A-Za-z0-9_$]*)(?=\s*(?:=|!=|<>|>=|<=|>|<))"
246
+ )
247
+ return pattern.sub(lambda match: f"{subject_table}.{match.group(1)}", condition)
248
+
249
+
250
+ def _render_path_distinct_count_plan(
251
+ ir: QueryIR,
252
+ ) -> Tuple[Optional[str], str, float, GenerationEvidence]:
253
+ """Render a bounded inner-join path and count distinct terminal targets."""
254
+ plan: PathDistinctCountPlan = ir.path_distinct_count_plan # type: ignore[assignment]
255
+ if ir.operation != "SELECT":
256
+ return _render_plan_failure("only SELECT operations are supported")
257
+ if ir.joins or ir.aggregations or ir.distinct:
258
+ return _render_plan_failure("joins, aggregations, and DISTINCT are unsupported")
259
+ if ir.ordering or ir.orderings:
260
+ return _render_plan_failure("ORDER BY is unsupported")
261
+ if len(plan.path_steps) != 2:
262
+ return _render_plan_failure("exactly two path steps are required")
263
+ if not _safe_identifier(plan.subject_table) or plan.subject_table != ir.table:
264
+ return _render_plan_failure("subject table is invalid")
265
+ if not plan.group_identity or not plan.target_identity:
266
+ return _render_plan_failure("group and target identities are required")
267
+ if any(not _safe_identifier(column) for column in (*plan.group_identity, *plan.target_identity)):
268
+ return _render_plan_failure("identity columns are invalid")
269
+
270
+ table_names = [plan.subject_table]
271
+ for step in plan.path_steps:
272
+ if (
273
+ not _safe_identifier(step.from_table)
274
+ or not _safe_identifier(step.to_table)
275
+ or step.from_table != table_names[-1]
276
+ or not step.column_pairs
277
+ or any(
278
+ not _safe_identifier(column)
279
+ for pair in step.column_pairs
280
+ for column in pair
281
+ )
282
+ ):
283
+ return _render_plan_failure("path step is invalid")
284
+ table_names.append(step.to_table)
285
+ if len(set(name.casefold() for name in table_names)) != len(table_names):
286
+ return _render_plan_failure("path repeats a table")
287
+ target_table = table_names[-1]
288
+
289
+ inner_projection = [
290
+ f"{plan.subject_table}.{column} AS _group_{index}"
291
+ for index, column in enumerate(plan.group_identity)
292
+ ] + [
293
+ f"{target_table}.{column} AS _target_{index}"
294
+ for index, column in enumerate(plan.target_identity)
295
+ ]
296
+ inner_sql = f"SELECT DISTINCT {', '.join(inner_projection)}\nFROM {plan.subject_table}"
297
+ for step in plan.path_steps:
298
+ conditions = " AND ".join(
299
+ f"{step.from_table}.{from_column} = {step.to_table}.{to_column}"
300
+ for from_column, to_column in step.column_pairs
301
+ )
302
+ inner_sql += f"\nJOIN {step.to_table} ON {conditions}"
303
+
304
+ conditions = ir.conditions
305
+ inner_conditions = (
306
+ [_qualify_subject_condition(condition, plan.subject_table) for condition in conditions if condition.strip()]
307
+ if isinstance(conditions, list)
308
+ else ([_qualify_subject_condition(conditions, plan.subject_table)] if conditions.strip() else [])
309
+ )
310
+ if plan.exclude_null_identity:
311
+ inner_conditions.extend(
312
+ f"{plan.subject_table}.{column} IS NOT NULL"
313
+ for column in plan.group_identity
314
+ )
315
+ inner_conditions.extend(
316
+ f"{target_table}.{column} IS NOT NULL"
317
+ for column in plan.target_identity
318
+ )
319
+ if inner_conditions:
320
+ inner_sql += "\nWHERE " + " AND ".join(inner_conditions)
321
+ indented_inner = "\n".join(f" {line}" for line in inner_sql.splitlines())
322
+
323
+ group_aliases = [f"_group_{index}" for index in range(len(plan.group_identity))]
324
+ select_clause = ", ".join([*group_aliases, "COUNT(*) AS count"])
325
+ sql = (
326
+ f"SELECT {select_clause}\n"
327
+ f"FROM (\n{indented_inner}\n) AS _distinct_targets\n"
328
+ f"GROUP BY {', '.join(group_aliases)}"
329
+ )
330
+ explanation_parts = ["聚合: COUNT(*) AS count", f"表: {plan.subject_table}", f"分组: {', '.join(group_aliases)}"]
331
+ evidence = ir.evidence
332
+ evidence.items.append(EvidenceItem("base", "Base confidence for multi-hop distinct count", 0.5))
333
+ evidence.items.append(EvidenceItem(
334
+ EVIDENCE_AGGREGATION_PRESENT,
335
+ "Derived multi-hop distinct entity count",
336
+ 0.15,
337
+ detail=", ".join(plan.target_identity),
338
+ ))
339
+ evidence.items.append(EvidenceItem(
340
+ EVIDENCE_GROUP_BY,
341
+ f"GROUP BY clause: {', '.join(group_aliases)}",
342
+ 0.1,
343
+ ))
344
+ if inner_conditions and conditions:
345
+ explanation_parts.append(
346
+ f"条件: {len(conditions) if isinstance(conditions, list) else 1}个"
347
+ )
348
+ evidence.items.append(EvidenceItem(
349
+ EVIDENCE_CONDITIONS_PRESENT,
350
+ "Subject predicates in multi-hop derived count input",
351
+ 0.1,
352
+ ))
353
+ if ir.limit is not None:
354
+ sql = add_limit(sql, ir.limit, ir.dialect)
355
+ explanation_parts.append(f"限制: {ir.limit}条")
356
+ evidence.items.append(EvidenceItem(
357
+ EVIDENCE_LIMIT,
358
+ f"Explicit limit: {ir.limit}",
359
+ 0.1,
360
+ detail=str(ir.limit),
361
+ ))
362
+ sql = f"-- Generated for {ir.dialect.upper()}\n{sql}"
363
+ sql = apply_dialect_adjustments(sql, ir.dialect)
364
+ parse_adjustment = validate_sql(sql, ir.dialect)
365
+ if parse_adjustment > 0:
366
+ evidence.items.append(EvidenceItem(
367
+ EVIDENCE_PARSE_OK,
368
+ "Target dialect parser accepted the generated SQL",
369
+ parse_adjustment,
370
+ ))
371
+ elif parse_adjustment < 0:
372
+ evidence.items.append(EvidenceItem(
373
+ EVIDENCE_PARSE_FAIL,
374
+ "Target dialect parser rejected the generated SQL",
375
+ parse_adjustment,
376
+ ))
377
+ return None, (
378
+ "Generated SQL failed target-dialect validation: "
379
+ + " | ".join(explanation_parts)
380
+ ), 0.0, evidence
381
+ return sql, " | ".join(explanation_parts), evidence.score, evidence
382
+
383
+
242
384
  # ── Renderer ────────────────────────────────────────────────────────────────
243
385
 
244
386
  def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEvidence]:
@@ -253,6 +395,10 @@ def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEviden
253
395
  Returns the same 4-tuple the legacy ``_build_sql_enhanced`` returns:
254
396
  ``(sql, explanation, confidence, evidence)``.
255
397
  """
398
+ if ir.path_distinct_count_plan is not None and ir.distinct_count_plan is not None:
399
+ return _render_plan_failure("multiple derived count plans are unsupported")
400
+ if ir.path_distinct_count_plan is not None:
401
+ return _render_path_distinct_count_plan(ir)
256
402
  if ir.distinct_count_plan is not None:
257
403
  return _render_distinct_count_plan(ir)
258
404
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sql-dialect-master"
3
- version = "1.11.0"
3
+ version = "1.12.0"
4
4
  description = "SQL Dialect Master - Multi-database SQL conversion engine"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sql-dialect-master
3
- Version: 1.11.0
3
+ Version: 1.12.0
4
4
  Summary: SQL Dialect Master - Multi-database SQL conversion engine
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -38,7 +38,7 @@ Dynamic: license-file
38
38
 
39
39
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
40
40
 
41
- Current release: 1.11.0
41
+ Current release: 1.12.0
42
42
 
43
43
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
44
44
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)