sql-dialect-master 1.9.0__tar.gz → 1.11.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.9.0 → sql_dialect_master-1.11.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/README.md +1 -1
  3. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/main.py +15 -0
  4. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/metadata.py +2 -2
  5. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/ir.py +11 -0
  6. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/orchestrator.py +98 -2
  7. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/renderer.py +165 -1
  8. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_schema.py +41 -0
  9. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/pyproject.toml +1 -1
  10. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/sql_dialect_master.egg-info/PKG-INFO +2 -2
  11. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/LICENSE +0 -0
  12. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/__init__.py +0 -0
  13. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/__init__.py +0 -0
  14. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/auth.py +0 -0
  15. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/client_identity.py +0 -0
  16. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/metrics.py +0 -0
  17. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/middleware.py +0 -0
  18. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/rate_limit_store.py +0 -0
  19. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/readiness.py +0 -0
  20. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/api/workers.py +0 -0
  21. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/__init__.py +0 -0
  22. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/cache.py +0 -0
  23. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/column_hint_validation.py +0 -0
  24. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/config.py +0 -0
  25. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/constants.py +0 -0
  26. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/exceptions.py +0 -0
  27. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/function_call_scanner.py +0 -0
  28. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/function_semantics.py +0 -0
  29. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/functions_db.json +0 -0
  30. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/functions_lookup.py +0 -0
  31. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql.py +0 -0
  32. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/__init__.py +0 -0
  33. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  34. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  35. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  36. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/evidence.py +0 -0
  37. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/mappings.py +0 -0
  38. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/relations.py +0 -0
  39. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/templates.py +0 -0
  40. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  41. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_legacy.py +0 -0
  42. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_llm.py +0 -0
  43. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  44. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  45. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  46. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  47. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  48. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  49. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  50. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  51. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  52. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  53. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/nl2sql_pipeline/validation.py +0 -0
  54. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/setup.cfg +0 -0
  67. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  68. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  69. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  70. {sql_dialect_master-1.9.0 → sql_dialect_master-1.11.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.9.0
3
+ Version: 1.11.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.9.0
41
+ Current release: 1.11.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.9.0
5
+ Current release: 1.11.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)
@@ -461,6 +461,16 @@ class SchemaColumn(BaseModel):
461
461
  class SchemaTable(BaseModel):
462
462
  name: SchemaIdentifier
463
463
  columns: List[SchemaColumn] = Field(default_factory=list, max_length=200)
464
+ primary_key: Optional[List[SchemaIdentifier]] = Field(None, max_length=8)
465
+
466
+ @model_validator(mode="after")
467
+ def validate_primary_key(self):
468
+ if self.primary_key is None:
469
+ return self
470
+ keys = [column.casefold() for column in self.primary_key]
471
+ if not keys or len(keys) != len(set(keys)):
472
+ raise ValueError("invalid schema primary key")
473
+ return self
464
474
 
465
475
 
466
476
  class SchemaColumnPair(BaseModel):
@@ -500,6 +510,11 @@ class SchemaDefinition(BaseModel):
500
510
  def validate_total_columns(self):
501
511
  if sum(len(table.columns) for table in self.tables) > 1000:
502
512
  raise ValueError("Schema must contain at most 1000 columns in total")
513
+ for table in self.tables:
514
+ if table.primary_key and table.columns:
515
+ column_names = {column.name.casefold() for column in table.columns}
516
+ if any(column.casefold() not in column_names for column in table.primary_key):
517
+ raise ValueError("invalid schema primary key")
503
518
  table_names = {table.name.casefold() for table in self.tables}
504
519
  tables_by_key = {table.name.casefold(): table for table in self.tables}
505
520
  relationship_pair_count = 0
@@ -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.9.0"
21
- API_VERSION = "1.9.0"
20
+ PROJECT_VERSION = "1.11.0"
21
+ API_VERSION = "1.11.0"
22
22
  # Frontend v2 architecture — independent of the product release version.
23
23
  FRONTEND_ARCHITECTURE_VERSION = 2
24
24
 
@@ -13,6 +13,14 @@ 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
+
16
24
  @dataclass
17
25
  class QueryIR:
18
26
  """Structured intermediate representation for an NL2SQL query.
@@ -36,6 +44,7 @@ class QueryIR:
36
44
  dialect: str
37
45
  evidence: GenerationEvidence = field(default_factory=GenerationEvidence)
38
46
  orderings: Optional[List[Tuple[str, str]]] = None
47
+ distinct_count_plan: Optional[DistinctCountPlan] = None
39
48
 
40
49
 
41
50
  def build_ir(
@@ -51,6 +60,7 @@ def build_ir(
51
60
  distinct: bool,
52
61
  dialect: str,
53
62
  orderings: Optional[List[Tuple[str, str]]] = None,
63
+ distinct_count_plan: Optional[DistinctCountPlan] = None,
54
64
  ) -> QueryIR:
55
65
  """Thin positional-arg adapter mirroring the legacy call site.
56
66
 
@@ -70,4 +80,5 @@ def build_ir(
70
80
  distinct=distinct,
71
81
  dialect=dialect,
72
82
  orderings=orderings,
83
+ distinct_count_plan=distinct_count_plan,
73
84
  )
@@ -728,7 +728,18 @@ class PipelineNL2SQLGenerator:
728
728
  if match is None:
729
729
  return None
730
730
  label = match.group(1)
731
- if text[match.end():].strip(" \t\r\n,.;,。;"):
731
+ tail = text[match.end():].strip(" \t\r\n,.;,。;")
732
+ unique_count_phrase = bool(
733
+ self._schema_unique_count_spans(text, ("count", None))
734
+ )
735
+ if tail and not (
736
+ unique_count_phrase
737
+ and re.match(
738
+ r"^(?:where|whose|order(?:ed)?\s+by|sort(?:ed)?\s+by|limit)\b",
739
+ tail,
740
+ re.IGNORECASE,
741
+ )
742
+ ):
732
743
  raise SchemaValidationError("multiple schema group labels are unsupported")
733
744
  return self._schema_resolve_group_label(
734
745
  text, label, (match.start(), match.end()), schema
@@ -1066,6 +1077,40 @@ class PipelineNL2SQLGenerator:
1066
1077
  return "count", None
1067
1078
  return None
1068
1079
 
1080
+ @staticmethod
1081
+ def _schema_unique_count_spans(
1082
+ text: str, count_metric: tuple[str, str | None] | None
1083
+ ) -> list[tuple[int, int]]:
1084
+ """Return explicit unique-count modifiers consumed by schema COUNT."""
1085
+ if count_metric is None or count_metric[0] != "count":
1086
+ return []
1087
+ executable = mask_non_executable(text)
1088
+ english = re.compile(
1089
+ r"\b(?:count(?:\s+of)?|number\s+of)\s+(?:distinct|unique)\b|"
1090
+ r"\b(?:distinct|unique)\s+(?:count(?:\s+of)?|number\s+of)\b",
1091
+ re.IGNORECASE,
1092
+ )
1093
+ spans = [match.span() for match in english.finditer(executable)]
1094
+ chinese = re.compile(
1095
+ r"(?:不同|去重|唯一)\s*(?:的\s*)?"
1096
+ r"[\u4e00-\u9fffA-Za-z0-9_$]{0,12}?"
1097
+ r"(?:数量|计数|数)",
1098
+ )
1099
+ spans.extend(match.span() for match in chinese.finditer(executable))
1100
+ return spans
1101
+
1102
+ @staticmethod
1103
+ def _schema_mask_clause_tail(text: str) -> str:
1104
+ """Mask clauses following a group label while preserving offsets."""
1105
+ match = re.search(
1106
+ r"\b(?:where|whose|order(?:ed)?\s+by|sort(?:ed)?\s+by|limit)\b",
1107
+ text,
1108
+ re.IGNORECASE,
1109
+ )
1110
+ if match is None:
1111
+ return text
1112
+ return text[:match.start()] + " " * (len(text) - match.start())
1113
+
1069
1114
  def _schema_extract_aggregations(
1070
1115
  self,
1071
1116
  text: str,
@@ -1904,6 +1949,10 @@ class PipelineNL2SQLGenerator:
1904
1949
  count_metric = self._schema_resolve_count_metric(
1905
1950
  text_lower, table_context, schema
1906
1951
  )
1952
+ unique_count_spans = self._schema_unique_count_spans(
1953
+ text_lower, count_metric
1954
+ )
1955
+ unique_count_intent = bool(unique_count_spans)
1907
1956
  columns = self._schema_resolve_columns(
1908
1957
  metric_text,
1909
1958
  table_context,
@@ -1929,10 +1978,54 @@ class PipelineNL2SQLGenerator:
1929
1978
  [label_group_column]
1930
1979
  if label_resolution is not None
1931
1980
  else self._schema_resolve_group_by(
1932
- text_lower, table_context, schema, aggregations
1981
+ self._schema_mask_clause_tail(text_lower)
1982
+ if unique_count_intent
1983
+ else text_lower,
1984
+ table_context,
1985
+ schema,
1986
+ aggregations,
1933
1987
  )
1934
1988
  )
1935
1989
  distinct = self._check_distinct(text_lower)
1990
+ distinct_count_plan = None
1991
+ if unique_count_intent:
1992
+ if len(unique_count_spans) != 1:
1993
+ raise SchemaValidationError(
1994
+ "multiple unique count phrases are unsupported"
1995
+ )
1996
+ consumed = text_lower
1997
+ for span in unique_count_spans:
1998
+ consumed = self._schema_mask_span(consumed, span)
1999
+ if self._check_distinct(consumed):
2000
+ raise SchemaValidationError(
2001
+ "unique count cannot be combined with DISTINCT projection"
2002
+ )
2003
+ if joins:
2004
+ raise SchemaValidationError(
2005
+ "unique count with relationships is unsupported"
2006
+ )
2007
+ if len(table_context.primary_key) == 0:
2008
+ raise SchemaValidationError(
2009
+ "unique count requires a declared primary key"
2010
+ )
2011
+ if any(
2012
+ not aggregation.upper().startswith("COUNT(")
2013
+ for aggregation in aggregations
2014
+ ):
2015
+ raise SchemaValidationError(
2016
+ "unique count cannot combine with non-COUNT aggregation"
2017
+ )
2018
+ if len(table_context.primary_key) == 1:
2019
+ aggregations = [
2020
+ f"COUNT(DISTINCT {table_context.primary_key[0]}) AS count"
2021
+ ]
2022
+ else:
2023
+ aggregations = []
2024
+ distinct_count_plan = _nl2sql_ir.DistinctCountPlan(
2025
+ tuple(table_context.primary_key),
2026
+ exclude_null_identity=True,
2027
+ )
2028
+ distinct = False
1936
2029
  if any(join.get("path") for join in joins):
1937
2030
  if conditions or aggregations or group_by or label_resolution is not None or distinct:
1938
2031
  raise SchemaValidationError(
@@ -1979,6 +2072,7 @@ class PipelineNL2SQLGenerator:
1979
2072
  distinct,
1980
2073
  dialect,
1981
2074
  orderings=orderings,
2075
+ distinct_count_plan=distinct_count_plan,
1982
2076
  )
1983
2077
  result = self._apply_confidence_policy(NL2SQLResult(
1984
2078
  success=sql is not None,
@@ -2186,6 +2280,7 @@ class PipelineNL2SQLGenerator:
2186
2280
  distinct,
2187
2281
  dialect,
2188
2282
  orderings=None,
2283
+ distinct_count_plan=None,
2189
2284
  ) -> tuple:
2190
2285
  """Build SQL statement from extracted components.
2191
2286
 
@@ -2197,6 +2292,7 @@ class PipelineNL2SQLGenerator:
2197
2292
  operation, table, columns, conditions, aggregations,
2198
2293
  group_by, ordering, limit, joins, distinct, dialect,
2199
2294
  orderings=orderings,
2295
+ distinct_count_plan=distinct_count_plan,
2200
2296
  )
2201
2297
  return _render_sql_impl(ir)
2202
2298
 
@@ -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, QueryIR
28
28
  from .validation import validate_sql
29
29
 
30
30
 
@@ -78,6 +78,167 @@ 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
+
81
242
  # ── Renderer ────────────────────────────────────────────────────────────────
82
243
 
83
244
  def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEvidence]:
@@ -92,6 +253,9 @@ def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEviden
92
253
  Returns the same 4-tuple the legacy ``_build_sql_enhanced`` returns:
93
254
  ``(sql, explanation, confidence, evidence)``.
94
255
  """
256
+ if ir.distinct_count_plan is not None:
257
+ return _render_distinct_count_plan(ir)
258
+
95
259
  for join in ir.joins:
96
260
  if join.get("path"):
97
261
  continue
@@ -45,11 +45,17 @@ class SchemaTableContext:
45
45
  name: str
46
46
  columns: frozenset[str]
47
47
  has_column_metadata: bool
48
+ primary_key: tuple[str, ...] = ()
48
49
 
49
50
  @property
50
51
  def key(self) -> str:
51
52
  return _key(self.name)
52
53
 
54
+ @property
55
+ def identity_columns(self) -> tuple[str, ...]:
56
+ """Return the declared table identity without inferring one."""
57
+ return self.primary_key
58
+
53
59
 
54
60
  @dataclass(frozen=True)
55
61
  class SchemaRelationshipContext:
@@ -142,10 +148,45 @@ class SchemaContext:
142
148
  valid = False
143
149
  continue
144
150
  columns.add(column_name)
151
+ primary_key: tuple[str, ...] = ()
152
+ if "primary_key" in raw_table:
153
+ raw_primary_key = raw_table.get("primary_key")
154
+ if not isinstance(raw_primary_key, (list, tuple)) or not 1 <= len(
155
+ raw_primary_key
156
+ ) <= 8:
157
+ valid = False
158
+ else:
159
+ parsed_primary_key: list[str] = []
160
+ seen_primary_key: set[str] = set()
161
+ column_by_key = {_key(column): column for column in columns}
162
+ primary_key_valid = True
163
+ for raw_column in raw_primary_key:
164
+ try:
165
+ column_name = ".".join(_identifier_parts(raw_column))
166
+ except SchemaValidationError:
167
+ primary_key_valid = False
168
+ break
169
+ column_key = _key(column_name)
170
+ if column_key in seen_primary_key:
171
+ primary_key_valid = False
172
+ break
173
+ seen_primary_key.add(column_key)
174
+ if has_metadata:
175
+ canonical_column = column_by_key.get(column_key)
176
+ if canonical_column is None:
177
+ primary_key_valid = False
178
+ break
179
+ column_name = canonical_column
180
+ parsed_primary_key.append(column_name)
181
+ if primary_key_valid:
182
+ primary_key = tuple(parsed_primary_key)
183
+ else:
184
+ valid = False
145
185
  table = SchemaTableContext(
146
186
  name=canonical_name,
147
187
  columns=frozenset(columns),
148
188
  has_column_metadata=has_metadata,
189
+ primary_key=primary_key,
149
190
  )
150
191
  if table.key in tables_by_key:
151
192
  valid = False
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sql-dialect-master"
3
- version = "1.9.0"
3
+ version = "1.11.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.9.0
3
+ Version: 1.11.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.9.0
41
+ Current release: 1.11.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)