sql-dialect-master 1.10.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.10.0 → sql_dialect_master-1.12.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/README.md +1 -1
  3. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/metadata.py +2 -2
  4. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/ir.py +34 -0
  5. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/orchestrator.py +199 -8
  6. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/renderer.py +311 -1
  7. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/pyproject.toml +1 -1
  8. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/PKG-INFO +2 -2
  9. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/LICENSE +0 -0
  10. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/__init__.py +0 -0
  11. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/__init__.py +0 -0
  12. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/auth.py +0 -0
  13. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/client_identity.py +0 -0
  14. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/main.py +0 -0
  15. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/metrics.py +0 -0
  16. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/middleware.py +0 -0
  17. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/rate_limit_store.py +0 -0
  18. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/readiness.py +0 -0
  19. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/api/workers.py +0 -0
  20. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/__init__.py +0 -0
  21. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/cache.py +0 -0
  22. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/column_hint_validation.py +0 -0
  23. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/config.py +0 -0
  24. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/constants.py +0 -0
  25. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/exceptions.py +0 -0
  26. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/function_call_scanner.py +0 -0
  27. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/function_semantics.py +0 -0
  28. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/functions_db.json +0 -0
  29. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/functions_lookup.py +0 -0
  30. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql.py +0 -0
  31. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/__init__.py +0 -0
  32. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  33. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  34. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  35. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/evidence.py +0 -0
  36. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/mappings.py +0 -0
  37. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/relations.py +0 -0
  38. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/templates.py +0 -0
  39. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  40. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_legacy.py +0 -0
  41. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_llm.py +0 -0
  42. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  43. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  44. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  45. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  46. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  47. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  48. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  49. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  50. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  51. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  52. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_pipeline/validation.py +0 -0
  53. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/nl2sql_schema.py +0 -0
  54. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/setup.cfg +0 -0
  67. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  68. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  69. {sql_dialect_master-1.10.0 → sql_dialect_master-1.12.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  70. {sql_dialect_master-1.10.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.10.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.10.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.10.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.10.0"
21
- API_VERSION = "1.10.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
 
@@ -13,6 +13,34 @@ from typing import Dict, List, Optional, Tuple, Union
13
13
  from ..nl2sql_components.evidence import GenerationEvidence
14
14
 
15
15
 
16
+ @dataclass(frozen=True)
17
+ class DistinctCountPlan:
18
+ """Validated identity columns for a derived distinct entity count."""
19
+
20
+ identity_columns: tuple[str, ...]
21
+ exclude_null_identity: bool = True
22
+
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
+
16
44
  @dataclass
17
45
  class QueryIR:
18
46
  """Structured intermediate representation for an NL2SQL query.
@@ -36,6 +64,8 @@ class QueryIR:
36
64
  dialect: str
37
65
  evidence: GenerationEvidence = field(default_factory=GenerationEvidence)
38
66
  orderings: Optional[List[Tuple[str, str]]] = None
67
+ distinct_count_plan: Optional[DistinctCountPlan] = None
68
+ path_distinct_count_plan: Optional[PathDistinctCountPlan] = None
39
69
 
40
70
 
41
71
  def build_ir(
@@ -51,6 +81,8 @@ def build_ir(
51
81
  distinct: bool,
52
82
  dialect: str,
53
83
  orderings: Optional[List[Tuple[str, str]]] = None,
84
+ distinct_count_plan: Optional[DistinctCountPlan] = None,
85
+ path_distinct_count_plan: Optional[PathDistinctCountPlan] = None,
54
86
  ) -> QueryIR:
55
87
  """Thin positional-arg adapter mirroring the legacy call site.
56
88
 
@@ -70,4 +102,6 @@ def build_ir(
70
102
  distinct=distinct,
71
103
  dialect=dialect,
72
104
  orderings=orderings,
105
+ distinct_count_plan=distinct_count_plan,
106
+ path_distinct_count_plan=path_distinct_count_plan,
73
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)
@@ -1987,6 +2132,8 @@ class PipelineNL2SQLGenerator:
1987
2132
  )
1988
2133
  )
1989
2134
  distinct = self._check_distinct(text_lower)
2135
+ distinct_count_plan = None
2136
+ path_distinct_count_plan = None
1990
2137
  if unique_count_intent:
1991
2138
  if len(unique_count_spans) != 1:
1992
2139
  raise SchemaValidationError(
@@ -2003,9 +2150,38 @@ class PipelineNL2SQLGenerator:
2003
2150
  raise SchemaValidationError(
2004
2151
  "unique count with relationships is unsupported"
2005
2152
  )
2006
- if len(table_context.primary_key) != 1:
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
+ )
2182
+ if len(table_context.primary_key) == 0:
2007
2183
  raise SchemaValidationError(
2008
- "unique count requires one declared primary key"
2184
+ "unique count requires a declared primary key"
2009
2185
  )
2010
2186
  if any(
2011
2187
  not aggregation.upper().startswith("COUNT(")
@@ -2014,9 +2190,18 @@ class PipelineNL2SQLGenerator:
2014
2190
  raise SchemaValidationError(
2015
2191
  "unique count cannot combine with non-COUNT aggregation"
2016
2192
  )
2017
- aggregations = [
2018
- f"COUNT(DISTINCT {table_context.primary_key[0]}) AS count"
2019
- ]
2193
+ if path_distinct_count_plan is not None:
2194
+ aggregations = []
2195
+ elif len(table_context.primary_key) == 1:
2196
+ aggregations = [
2197
+ f"COUNT(DISTINCT {table_context.primary_key[0]}) AS count"
2198
+ ]
2199
+ else:
2200
+ aggregations = []
2201
+ distinct_count_plan = _nl2sql_ir.DistinctCountPlan(
2202
+ tuple(table_context.primary_key),
2203
+ exclude_null_identity=True,
2204
+ )
2020
2205
  distinct = False
2021
2206
  if any(join.get("path") for join in joins):
2022
2207
  if conditions or aggregations or group_by or label_resolution is not None or distinct:
@@ -2064,6 +2249,8 @@ class PipelineNL2SQLGenerator:
2064
2249
  distinct,
2065
2250
  dialect,
2066
2251
  orderings=orderings,
2252
+ distinct_count_plan=distinct_count_plan,
2253
+ path_distinct_count_plan=path_distinct_count_plan,
2067
2254
  )
2068
2255
  result = self._apply_confidence_policy(NL2SQLResult(
2069
2256
  success=sql is not None,
@@ -2271,6 +2458,8 @@ class PipelineNL2SQLGenerator:
2271
2458
  distinct,
2272
2459
  dialect,
2273
2460
  orderings=None,
2461
+ distinct_count_plan=None,
2462
+ path_distinct_count_plan=None,
2274
2463
  ) -> tuple:
2275
2464
  """Build SQL statement from extracted components.
2276
2465
 
@@ -2282,6 +2471,8 @@ class PipelineNL2SQLGenerator:
2282
2471
  operation, table, columns, conditions, aggregations,
2283
2472
  group_by, ordering, limit, joins, distinct, dialect,
2284
2473
  orderings=orderings,
2474
+ distinct_count_plan=distinct_count_plan,
2475
+ path_distinct_count_plan=path_distinct_count_plan,
2285
2476
  )
2286
2477
  return _render_sql_impl(ir)
2287
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 QueryIR
27
+ from .ir import DistinctCountPlan, PathDistinctCountPlan, QueryIR
28
28
  from .validation import validate_sql
29
29
 
30
30
 
@@ -78,6 +78,309 @@ def parameter_placeholder(index: int, dialect: str) -> str:
78
78
  return "?"
79
79
 
80
80
 
81
+ _SAFE_IDENTIFIER = re.compile(
82
+ r"[A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)*"
83
+ )
84
+ _DERIVED_COUNT_ALIAS = "_distinct_targets"
85
+
86
+
87
+ def _safe_identifier(value: str) -> bool:
88
+ return isinstance(value, str) and _SAFE_IDENTIFIER.fullmatch(value) is not None
89
+
90
+
91
+ def _render_plan_failure(reason: str) -> Tuple[None, str, float, GenerationEvidence]:
92
+ return None, f"Derived distinct count plan rejected: {reason}", 0.0, GenerationEvidence()
93
+
94
+
95
+ def _render_distinct_count_plan(
96
+ ir: QueryIR,
97
+ ) -> Tuple[Optional[str], str, float, GenerationEvidence]:
98
+ """Render a validated composite-identity count through a derived table."""
99
+ plan: DistinctCountPlan = ir.distinct_count_plan # type: ignore[assignment]
100
+ if ir.operation != "SELECT":
101
+ return _render_plan_failure("only SELECT operations are supported")
102
+ if ir.joins:
103
+ return _render_plan_failure("joins are unsupported")
104
+ if ir.distinct:
105
+ return _render_plan_failure("DISTINCT projection is unsupported")
106
+ if ir.aggregations:
107
+ return _render_plan_failure("aggregations are unsupported")
108
+ if not plan.identity_columns or any(
109
+ not _safe_identifier(column) for column in plan.identity_columns
110
+ ):
111
+ return _render_plan_failure("identity columns are invalid")
112
+ if not _safe_identifier(ir.table):
113
+ return _render_plan_failure("source table is invalid")
114
+ if any(not _safe_identifier(column) for column in ir.group_by):
115
+ return _render_plan_failure("group columns are invalid")
116
+
117
+ projection: list[str] = []
118
+ seen: set[str] = set()
119
+ for column in [*ir.group_by, *plan.identity_columns]:
120
+ key = column.casefold()
121
+ if key not in seen:
122
+ seen.add(key)
123
+ projection.append(column)
124
+ if not projection:
125
+ return _render_plan_failure("derived projection is empty")
126
+
127
+ conditions = ir.conditions
128
+ inner_conditions = (
129
+ [condition for condition in conditions if condition.strip()]
130
+ if isinstance(conditions, list)
131
+ else ([conditions] if conditions.strip() else [])
132
+ )
133
+ if plan.exclude_null_identity:
134
+ inner_conditions.extend(
135
+ f"{column} IS NOT NULL" for column in plan.identity_columns
136
+ )
137
+ inner_sql = (
138
+ f"SELECT DISTINCT {', '.join(projection)}\nFROM {ir.table}"
139
+ )
140
+ if inner_conditions:
141
+ inner_sql += "\nWHERE " + " AND ".join(inner_conditions)
142
+ indented_inner = "\n".join(
143
+ f" {line}" for line in inner_sql.splitlines()
144
+ )
145
+
146
+ select_clause = (
147
+ ", ".join([*ir.group_by, "COUNT(*) AS count"])
148
+ if ir.group_by
149
+ else "COUNT(*) AS count"
150
+ )
151
+ sql = (
152
+ f"SELECT {select_clause}\n"
153
+ f"FROM (\n{indented_inner}\n) AS {_DERIVED_COUNT_ALIAS}"
154
+ )
155
+ explanation_parts = ["聚合: COUNT(*) AS count", f"表: {ir.table}"]
156
+ evidence = ir.evidence
157
+ evidence.items.append(EvidenceItem("base", "Base confidence for generated SQL", 0.5))
158
+ evidence.items.append(EvidenceItem(
159
+ EVIDENCE_AGGREGATION_PRESENT,
160
+ "Derived distinct entity count",
161
+ 0.15,
162
+ detail=", ".join(plan.identity_columns),
163
+ ))
164
+ if ir.table != "table_name":
165
+ evidence.items.append(EvidenceItem(
166
+ EVIDENCE_TABLE_KNOWN,
167
+ f"Table resolved to known name: {ir.table}",
168
+ 0.2,
169
+ detail=ir.table,
170
+ ))
171
+ if inner_conditions and isinstance(conditions, (list, str)) and conditions:
172
+ explanation_parts.append(
173
+ f"条件: {len(conditions) if isinstance(conditions, list) else 1}个"
174
+ )
175
+ evidence.items.append(EvidenceItem(
176
+ EVIDENCE_CONDITIONS_PRESENT,
177
+ "Explicit predicates in derived count input",
178
+ 0.1,
179
+ ))
180
+ if ir.group_by:
181
+ explanation_parts.append(f"分组: {', '.join(ir.group_by)}")
182
+ evidence.items.append(EvidenceItem(
183
+ EVIDENCE_GROUP_BY,
184
+ f"GROUP BY clause: {', '.join(ir.group_by)}",
185
+ 0.1,
186
+ ))
187
+
188
+ active_orderings = ir.orderings or ([ir.ordering] if ir.ordering else [])
189
+ ordering_sql = ""
190
+ if active_orderings:
191
+ group_keys = {column.casefold() for column in ir.group_by}
192
+ for column, direction in active_orderings:
193
+ if (
194
+ not _safe_identifier(column)
195
+ or direction not in {"ASC", "DESC"}
196
+ or column.casefold() == "count"
197
+ or column.casefold() not in group_keys
198
+ ):
199
+ return _render_plan_failure(
200
+ "derived count ordering must use a grouped schema column"
201
+ )
202
+ ordering_sql = ", ".join(
203
+ f"{column} {direction}" for column, direction in active_orderings
204
+ )
205
+ explanation_parts.append(f"排序: {ordering_sql}")
206
+ if ir.group_by:
207
+ sql += f"\nGROUP BY {', '.join(ir.group_by)}"
208
+ if ordering_sql:
209
+ sql += f"\nORDER BY {ordering_sql}"
210
+ if ir.limit is not None:
211
+ sql = add_limit(sql, ir.limit, ir.dialect)
212
+ explanation_parts.append(f"限制: {ir.limit}条")
213
+ evidence.items.append(EvidenceItem(
214
+ EVIDENCE_LIMIT,
215
+ f"Explicit limit: {ir.limit}",
216
+ 0.1,
217
+ detail=str(ir.limit),
218
+ ))
219
+
220
+ sql = f"-- Generated for {ir.dialect.upper()}\n{sql}"
221
+ sql = apply_dialect_adjustments(sql, ir.dialect)
222
+ parse_adjustment = validate_sql(sql, ir.dialect)
223
+ if parse_adjustment > 0:
224
+ evidence.items.append(EvidenceItem(
225
+ EVIDENCE_PARSE_OK,
226
+ "Target dialect parser accepted the generated SQL",
227
+ parse_adjustment,
228
+ ))
229
+ elif parse_adjustment < 0:
230
+ evidence.items.append(EvidenceItem(
231
+ EVIDENCE_PARSE_FAIL,
232
+ "Target dialect parser rejected the generated SQL",
233
+ parse_adjustment,
234
+ ))
235
+ return None, (
236
+ "Generated SQL failed target-dialect validation: "
237
+ + " | ".join(explanation_parts)
238
+ ), 0.0, evidence
239
+ return sql, " | ".join(explanation_parts), evidence.score, evidence
240
+
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
+
81
384
  # ── Renderer ────────────────────────────────────────────────────────────────
82
385
 
83
386
  def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEvidence]:
@@ -92,6 +395,13 @@ def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEviden
92
395
  Returns the same 4-tuple the legacy ``_build_sql_enhanced`` returns:
93
396
  ``(sql, explanation, confidence, evidence)``.
94
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)
402
+ if ir.distinct_count_plan is not None:
403
+ return _render_distinct_count_plan(ir)
404
+
95
405
  for join in ir.joins:
96
406
  if join.get("path"):
97
407
  continue
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sql-dialect-master"
3
- version = "1.10.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.10.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.10.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)