sql-dialect-master 1.11.0__tar.gz → 1.13.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.13.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/README.md +1 -1
  3. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/metadata.py +2 -2
  4. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/ir.py +23 -0
  5. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/orchestrator.py +188 -4
  6. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/renderer.py +147 -1
  7. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/pyproject.toml +1 -1
  8. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/sql_dialect_master.egg-info/PKG-INFO +2 -2
  9. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/LICENSE +0 -0
  10. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/__init__.py +0 -0
  11. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/__init__.py +0 -0
  12. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/auth.py +0 -0
  13. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/client_identity.py +0 -0
  14. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/main.py +0 -0
  15. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/metrics.py +0 -0
  16. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/middleware.py +0 -0
  17. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/rate_limit_store.py +0 -0
  18. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/readiness.py +0 -0
  19. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/api/workers.py +0 -0
  20. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/__init__.py +0 -0
  21. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/cache.py +0 -0
  22. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/column_hint_validation.py +0 -0
  23. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/config.py +0 -0
  24. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/constants.py +0 -0
  25. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/exceptions.py +0 -0
  26. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/function_call_scanner.py +0 -0
  27. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/function_semantics.py +0 -0
  28. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/functions_db.json +0 -0
  29. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/functions_lookup.py +0 -0
  30. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql.py +0 -0
  31. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/__init__.py +0 -0
  32. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  33. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  34. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  35. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/evidence.py +0 -0
  36. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/mappings.py +0 -0
  37. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/relations.py +0 -0
  38. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/templates.py +0 -0
  39. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  40. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_legacy.py +0 -0
  41. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_llm.py +0 -0
  42. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  43. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  44. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  45. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  46. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  47. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  48. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  49. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  50. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  51. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  52. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_pipeline/validation.py +0 -0
  53. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/nl2sql_schema.py +0 -0
  54. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/setup.cfg +0 -0
  67. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  68. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  69. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  70. {sql_dialect_master-1.11.0 → sql_dialect_master-1.13.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.13.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.13.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.13.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.13.0"
21
+ API_VERSION = "1.13.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,136 @@ 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
+ def complete_edge(edge, left: SchemaTableContext, right: SchemaTableContext) -> bool:
1916
+ if left.key == edge.from_table.casefold():
1917
+ pairs = edge.column_pairs
1918
+ else:
1919
+ pairs = tuple((to_column, from_column) for from_column, to_column in edge.column_pairs)
1920
+ if len(left.primary_key) > 1 and not {
1921
+ pair[0].casefold() for pair in pairs
1922
+ }.issuperset(column.casefold() for column in left.primary_key):
1923
+ return False
1924
+ if len(right.primary_key) > 1 and not {
1925
+ pair[1].casefold() for pair in pairs
1926
+ }.issuperset(column.casefold() for column in right.primary_key):
1927
+ return False
1928
+ return True
1929
+
1930
+ def oriented_step(edge, left: SchemaTableContext, right: SchemaTableContext):
1931
+ if edge.from_table.casefold() == left.key:
1932
+ pairs = edge.column_pairs
1933
+ else:
1934
+ pairs = tuple((to_column, from_column) for from_column, to_column in edge.column_pairs)
1935
+ return _nl2sql_ir.PathStep(left.name, right.name, tuple(pairs))
1936
+
1937
+ direct = schema.relationship_candidates(subject.name, target.name)
1938
+ if len(direct) > 1:
1939
+ raise SchemaValidationError("direct multi-hop target relationship is ambiguous")
1940
+ if direct:
1941
+ if len(subject.primary_key) == 1:
1942
+ return None
1943
+ if not complete_edge(direct[0], subject, target):
1944
+ raise SchemaValidationError("direct relationship does not cover composite identity")
1945
+ return subject, (oriented_step(direct[0], subject, target),), group_match.span()
1946
+
1947
+ queue: list[tuple[SchemaTableContext, list[object]]] = [(subject, [])]
1948
+ paths: list[list[object]] = []
1949
+ expansions = 0
1950
+ while queue:
1951
+ current, path = queue.pop(0)
1952
+ if len(path) >= 2:
1953
+ continue
1954
+ for edge in schema.relationships:
1955
+ endpoints = {edge.from_table.casefold(), edge.to_table.casefold()}
1956
+ if current.key not in endpoints:
1957
+ continue
1958
+ next_name = (
1959
+ edge.to_table
1960
+ if edge.from_table.casefold() == current.key
1961
+ else edge.from_table
1962
+ )
1963
+ candidates = schema.table_candidates(next_name)
1964
+ if len(candidates) != 1:
1965
+ continue
1966
+ next_table = candidates[0]
1967
+ if next_table.key == subject.key or any(
1968
+ step.to_table.casefold() == next_table.key for step in path
1969
+ ):
1970
+ continue
1971
+ expansions += 1
1972
+ if expansions > 4096:
1973
+ raise SchemaValidationError("multi-hop path search budget exceeded")
1974
+ if not complete_edge(edge, current, next_table):
1975
+ continue
1976
+ next_path = [*path, oriented_step(edge, current, next_table)]
1977
+ if next_table.key == target.key:
1978
+ paths.append(next_path)
1979
+ else:
1980
+ queue.append((next_table, next_path))
1981
+ if not paths:
1982
+ raise SchemaValidationError("multi-hop target path is missing")
1983
+ shortest_length = min(len(path) for path in paths)
1984
+ shortest = [path for path in paths if len(path) == shortest_length]
1985
+ if shortest_length != 2 or len(shortest) != 1:
1986
+ raise SchemaValidationError("multi-hop target path is ambiguous or unsupported")
1987
+ return subject, tuple(shortest[0]), group_match.span()
1988
+
1859
1989
  def _schema_finalize(
1860
1990
  self, result: NL2SQLResult, schema: SchemaContext
1861
1991
  ) -> NL2SQLResult:
@@ -1899,8 +2029,17 @@ class PipelineNL2SQLGenerator:
1899
2029
  joined_with_resolution = self._schema_resolve_joined_with(
1900
2030
  text, table_hint, schema
1901
2031
  )
1902
- label_resolution = None
2032
+ multihop_unique_resolution = None
1903
2033
  if joined_on_resolution is None and joined_with_resolution is None:
2034
+ multihop_unique_resolution = self._schema_resolve_multihop_unique_path(
2035
+ text, table_hint, schema
2036
+ )
2037
+ label_resolution = None
2038
+ if (
2039
+ joined_on_resolution is None
2040
+ and joined_with_resolution is None
2041
+ and multihop_unique_resolution is None
2042
+ ):
1904
2043
  label_resolution = self._schema_resolve_english_group_label(executable_text, schema)
1905
2044
  if label_resolution is None:
1906
2045
  label_resolution = self._schema_resolve_chinese_group_label(executable_text, schema)
@@ -1922,6 +2061,10 @@ class PipelineNL2SQLGenerator:
1922
2061
  elif joined_with_resolution is not None:
1923
2062
  table_context, joins, joined_with_span = joined_with_resolution
1924
2063
  metric_text = self._schema_mask_span(text_lower, joined_with_span)
2064
+ elif multihop_unique_resolution is not None:
2065
+ table_context, path_steps, group_span = multihop_unique_resolution
2066
+ joins = []
2067
+ metric_text = self._schema_mask_span(text_lower, group_span)
1925
2068
  elif label_resolution is not None:
1926
2069
  table_context = label_resolution[0]
1927
2070
  label_group_column = label_resolution[1]
@@ -1933,6 +2076,7 @@ class PipelineNL2SQLGenerator:
1933
2076
  metric_text = text_lower
1934
2077
  whose_resolution = self._schema_resolve_whose(text, table_context, schema)
1935
2078
  whose_condition = None
2079
+ ordinary_conditions: list[str] = []
1936
2080
  condition_text = text_lower
1937
2081
  condition_original = text
1938
2082
  if joined_on_span is not None:
@@ -1949,6 +2093,8 @@ class PipelineNL2SQLGenerator:
1949
2093
  count_metric = self._schema_resolve_count_metric(
1950
2094
  text_lower, table_context, schema
1951
2095
  )
2096
+ if multihop_unique_resolution is not None and count_metric is None:
2097
+ count_metric = ("count", None)
1952
2098
  unique_count_spans = self._schema_unique_count_spans(
1953
2099
  text_lower, count_metric
1954
2100
  )
@@ -1966,6 +2112,7 @@ class PipelineNL2SQLGenerator:
1966
2112
  table_context,
1967
2113
  schema,
1968
2114
  )
2115
+ ordinary_conditions = list(conditions)
1969
2116
  if whose_condition is not None:
1970
2117
  conditions = [*conditions, whose_condition]
1971
2118
  parsed = self._parse_text(text_lower, text)
@@ -1975,7 +2122,9 @@ class PipelineNL2SQLGenerator:
1975
2122
  metric_text, table_context, schema, count_metric
1976
2123
  )
1977
2124
  group_by = (
1978
- [label_group_column]
2125
+ []
2126
+ if multihop_unique_resolution is not None
2127
+ else [label_group_column]
1979
2128
  if label_resolution is not None
1980
2129
  else self._schema_resolve_group_by(
1981
2130
  self._schema_mask_clause_tail(text_lower)
@@ -1988,6 +2137,7 @@ class PipelineNL2SQLGenerator:
1988
2137
  )
1989
2138
  distinct = self._check_distinct(text_lower)
1990
2139
  distinct_count_plan = None
2140
+ path_distinct_count_plan = None
1991
2141
  if unique_count_intent:
1992
2142
  if len(unique_count_spans) != 1:
1993
2143
  raise SchemaValidationError(
@@ -2004,6 +2154,35 @@ class PipelineNL2SQLGenerator:
2004
2154
  raise SchemaValidationError(
2005
2155
  "unique count with relationships is unsupported"
2006
2156
  )
2157
+ if multihop_unique_resolution is not None:
2158
+ if whose_condition is not None:
2159
+ qualified = re.match(
2160
+ r"([A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)*)\."
2161
+ r"[A-Za-z_][A-Za-z0-9_$]*",
2162
+ whose_condition,
2163
+ )
2164
+ if qualified and qualified.group(1).casefold() != table_context.key:
2165
+ raise SchemaValidationError(
2166
+ "multi-hop unique count whose predicate is not subject-owned"
2167
+ )
2168
+ if ordinary_conditions:
2169
+ raise SchemaValidationError(
2170
+ "multi-hop unique count only supports subject whose predicates"
2171
+ )
2172
+ if self._schema_has_explicit_ordering(text_lower):
2173
+ raise SchemaValidationError(
2174
+ "multi-hop unique count ordering is unsupported"
2175
+ )
2176
+ subject, path_steps, _ = multihop_unique_resolution
2177
+ path_distinct_count_plan = _nl2sql_ir.PathDistinctCountPlan(
2178
+ subject_table=subject.name,
2179
+ path_steps=tuple(path_steps),
2180
+ group_identity=tuple(subject.primary_key),
2181
+ target_identity=tuple(
2182
+ schema.table_candidates(path_steps[-1].to_table)[0].primary_key
2183
+ ),
2184
+ exclude_null_identity=True,
2185
+ )
2007
2186
  if len(table_context.primary_key) == 0:
2008
2187
  raise SchemaValidationError(
2009
2188
  "unique count requires a declared primary key"
@@ -2015,7 +2194,9 @@ class PipelineNL2SQLGenerator:
2015
2194
  raise SchemaValidationError(
2016
2195
  "unique count cannot combine with non-COUNT aggregation"
2017
2196
  )
2018
- if len(table_context.primary_key) == 1:
2197
+ if path_distinct_count_plan is not None:
2198
+ aggregations = []
2199
+ elif len(table_context.primary_key) == 1:
2019
2200
  aggregations = [
2020
2201
  f"COUNT(DISTINCT {table_context.primary_key[0]}) AS count"
2021
2202
  ]
@@ -2073,6 +2254,7 @@ class PipelineNL2SQLGenerator:
2073
2254
  dialect,
2074
2255
  orderings=orderings,
2075
2256
  distinct_count_plan=distinct_count_plan,
2257
+ path_distinct_count_plan=path_distinct_count_plan,
2076
2258
  )
2077
2259
  result = self._apply_confidence_policy(NL2SQLResult(
2078
2260
  success=sql is not None,
@@ -2281,6 +2463,7 @@ class PipelineNL2SQLGenerator:
2281
2463
  dialect,
2282
2464
  orderings=None,
2283
2465
  distinct_count_plan=None,
2466
+ path_distinct_count_plan=None,
2284
2467
  ) -> tuple:
2285
2468
  """Build SQL statement from extracted components.
2286
2469
 
@@ -2293,6 +2476,7 @@ class PipelineNL2SQLGenerator:
2293
2476
  group_by, ordering, limit, joins, distinct, dialect,
2294
2477
  orderings=orderings,
2295
2478
  distinct_count_plan=distinct_count_plan,
2479
+ path_distinct_count_plan=path_distinct_count_plan,
2296
2480
  )
2297
2481
  return _render_sql_impl(ir)
2298
2482
 
@@ -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 not 1 <= len(plan.path_steps) <= 2:
262
+ return _render_plan_failure("one or 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.13.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.13.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.13.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)