sql-dialect-master 1.8.0__tar.gz → 1.10.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.8.0 → sql_dialect_master-1.10.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/README.md +1 -1
  3. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/main.py +66 -4
  4. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/metadata.py +2 -2
  5. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/orchestrator.py +175 -17
  6. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/renderer.py +15 -1
  7. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_schema.py +109 -16
  8. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/pyproject.toml +1 -1
  9. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/sql_dialect_master.egg-info/PKG-INFO +2 -2
  10. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/LICENSE +0 -0
  11. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/__init__.py +0 -0
  12. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/__init__.py +0 -0
  13. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/auth.py +0 -0
  14. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/client_identity.py +0 -0
  15. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/metrics.py +0 -0
  16. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/middleware.py +0 -0
  17. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/rate_limit_store.py +0 -0
  18. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/readiness.py +0 -0
  19. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/api/workers.py +0 -0
  20. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/__init__.py +0 -0
  21. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/cache.py +0 -0
  22. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/column_hint_validation.py +0 -0
  23. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/config.py +0 -0
  24. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/constants.py +0 -0
  25. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/exceptions.py +0 -0
  26. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/function_call_scanner.py +0 -0
  27. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/function_semantics.py +0 -0
  28. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/functions_db.json +0 -0
  29. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/functions_lookup.py +0 -0
  30. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql.py +0 -0
  31. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/__init__.py +0 -0
  32. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  33. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  34. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  35. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/evidence.py +0 -0
  36. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/mappings.py +0 -0
  37. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/relations.py +0 -0
  38. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/templates.py +0 -0
  39. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  40. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_legacy.py +0 -0
  41. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_llm.py +0 -0
  42. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  43. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  44. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  45. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  46. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  47. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/ir.py +0 -0
  48. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  49. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  50. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  51. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  52. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  53. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/nl2sql_pipeline/validation.py +0 -0
  54. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/setup.cfg +0 -0
  67. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  68. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  69. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  70. {sql_dialect_master-1.8.0 → sql_dialect_master-1.10.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.8.0
3
+ Version: 1.10.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.8.0
41
+ Current release: 1.10.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.8.0
5
+ Current release: 1.10.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)
@@ -53,7 +53,10 @@ from backend.core.functions_lookup import FunctionEncyclopedia
53
53
  from backend.core.nl2sql import NL2SQLGenerator, NL2SQLResult
54
54
  from backend.core.nl2sql_components.evidence import EvidenceItem, GenerationEvidence
55
55
  from backend.core.nl2sql_llm import LLMError, LLMN2SQLClient, validate_llm_sql
56
- from backend.core.nl2sql_schema import SchemaContext
56
+ from backend.core.nl2sql_schema import (
57
+ MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS,
58
+ SchemaContext,
59
+ )
57
60
  from backend.core.nl2sql_pipeline.orchestrator import SAFE_TABLE_HINT
58
61
  from backend.core.parser import SUPPORTED_DIALECTS, SQLParser
59
62
  from backend.core.semantic_diff import diff_sql_ast
@@ -458,13 +461,45 @@ class SchemaColumn(BaseModel):
458
461
  class SchemaTable(BaseModel):
459
462
  name: SchemaIdentifier
460
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
474
+
475
+
476
+ class SchemaColumnPair(BaseModel):
477
+ from_column: SchemaIdentifier
478
+ to_column: SchemaIdentifier
461
479
 
462
480
 
463
481
  class SchemaRelationship(BaseModel):
464
482
  from_table: SchemaIdentifier
465
- from_column: SchemaIdentifier
483
+ from_column: Optional[SchemaIdentifier] = None
466
484
  to_table: SchemaIdentifier
467
- to_column: SchemaIdentifier
485
+ to_column: Optional[SchemaIdentifier] = None
486
+ columns: Optional[List[SchemaColumnPair]] = Field(None, max_length=8)
487
+
488
+ @model_validator(mode="after")
489
+ def validate_representation(self):
490
+ legacy = "from_column" in self.model_fields_set or "to_column" in self.model_fields_set
491
+ composite = "columns" in self.model_fields_set
492
+ if legacy == composite:
493
+ raise ValueError("invalid schema relationship")
494
+ if legacy and (self.from_column is None or self.to_column is None):
495
+ raise ValueError("invalid schema relationship")
496
+ if composite:
497
+ if not self.columns or len(self.columns) < 1:
498
+ raise ValueError("invalid schema relationship")
499
+ pairs = {(pair.from_column.casefold(), pair.to_column.casefold()) for pair in self.columns}
500
+ if len(pairs) != len(self.columns):
501
+ raise ValueError("invalid schema relationship")
502
+ return self
468
503
 
469
504
 
470
505
  class SchemaDefinition(BaseModel):
@@ -475,13 +510,40 @@ class SchemaDefinition(BaseModel):
475
510
  def validate_total_columns(self):
476
511
  if sum(len(table.columns) for table in self.tables) > 1000:
477
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")
478
518
  table_names = {table.name.casefold() for table in self.tables}
519
+ tables_by_key = {table.name.casefold(): table for table in self.tables}
520
+ relationship_pair_count = 0
479
521
  for relationship in self.relationships:
480
522
  if (
481
523
  relationship.from_table.casefold() not in table_names
482
524
  or relationship.to_table.casefold() not in table_names
483
525
  ):
484
- raise ValueError("Schema relationship references an unknown table")
526
+ raise ValueError("invalid schema relationship")
527
+ pairs = (
528
+ [(relationship.from_column, relationship.to_column)]
529
+ if relationship.columns is None
530
+ else [(pair.from_column, pair.to_column) for pair in relationship.columns]
531
+ )
532
+ relationship_pair_count += len(pairs)
533
+ if relationship_pair_count > MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS:
534
+ raise ValueError("invalid schema relationship")
535
+ from_context = tables_by_key[relationship.from_table.casefold()]
536
+ to_context = tables_by_key[relationship.to_table.casefold()]
537
+ if from_context.columns and any(
538
+ not any(column.name.casefold() == from_column.casefold() for column in from_context.columns)
539
+ for from_column, _ in pairs
540
+ ):
541
+ raise ValueError("invalid schema relationship")
542
+ if to_context.columns and any(
543
+ not any(column.name.casefold() == to_column.casefold() for column in to_context.columns)
544
+ for _, to_column in pairs
545
+ ):
546
+ raise ValueError("invalid schema relationship")
485
547
  return self
486
548
 
487
549
 
@@ -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.8.0"
21
- API_VERSION = "1.8.0"
20
+ PROJECT_VERSION = "1.10.0"
21
+ API_VERSION = "1.10.0"
22
22
  # Frontend v2 architecture — independent of the product release version.
23
23
  FRONTEND_ARCHITECTURE_VERSION = 2
24
24
 
@@ -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
@@ -820,7 +831,9 @@ class PipelineNL2SQLGenerator:
820
831
  f"{table_singular}_id".casefold(),
821
832
  f"{table_basename}_id".casefold(),
822
833
  }
823
- from_column = relationships[0].from_column
834
+ if len(relationships[0].column_pairs) != 1:
835
+ raise SchemaValidationError("composite group-label relationship is unsupported")
836
+ from_column = relationships[0].column_pairs[0][0]
824
837
  if from_column.casefold() not in allowed_foreign_keys:
825
838
  raise SchemaValidationError(
826
839
  "schema group label relationship has an unsupported foreign key"
@@ -1064,6 +1077,40 @@ class PipelineNL2SQLGenerator:
1064
1077
  return "count", None
1065
1078
  return None
1066
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
+
1067
1114
  def _schema_extract_aggregations(
1068
1115
  self,
1069
1116
  text: str,
@@ -1411,9 +1458,12 @@ class PipelineNL2SQLGenerator:
1411
1458
  ]
1412
1459
  if raw_relationships:
1413
1460
  def matches_relationship(relationship) -> bool:
1461
+ if len(relationship.column_pairs) != 1:
1462
+ return False
1463
+ from_column, to_column = relationship.column_pairs[0]
1414
1464
  declared = {
1415
- (relationship.from_table.casefold(), relationship.from_column.casefold()),
1416
- (relationship.to_table.casefold(), relationship.to_column.casefold()),
1465
+ (relationship.from_table.casefold(), from_column.casefold()),
1466
+ (relationship.to_table.casefold(), to_column.casefold()),
1417
1467
  }
1418
1468
  supplied = {
1419
1469
  (left_table.key, left_column.casefold()),
@@ -1504,9 +1554,9 @@ class PipelineNL2SQLGenerator:
1504
1554
  if len(relationships) != 1:
1505
1555
  raise SchemaValidationError("joined-with relationship is not unique")
1506
1556
  relationship = relationships[0]
1507
- condition = (
1508
- f"{relationship.from_table}.{relationship.from_column} = "
1509
- f"{relationship.to_table}.{relationship.to_column}"
1557
+ condition = " AND ".join(
1558
+ f"{relationship.from_table}.{from_column} = {relationship.to_table}.{to_column}"
1559
+ for from_column, to_column in relationship.column_pairs
1510
1560
  )
1511
1561
  span = (match.start(), match.end())
1512
1562
  return subject, [{
@@ -1675,6 +1725,56 @@ class PipelineNL2SQLGenerator:
1675
1725
  else:
1676
1726
  subject = mentions[0]
1677
1727
 
1728
+ def raw_edges_between(left: str, right: str) -> list:
1729
+ return [
1730
+ relationship for relationship in schema.relationships
1731
+ if {relationship.from_table.casefold(), relationship.to_table.casefold()}
1732
+ == {left.casefold(), right.casefold()}
1733
+ ]
1734
+
1735
+ def condition_for(relationship, left: str, right: str) -> str:
1736
+ if relationship.from_table.casefold() == left.casefold():
1737
+ pairs = relationship.column_pairs
1738
+ return " AND ".join(
1739
+ f"{relationship.from_table}.{from_column} = {relationship.to_table}.{to_column}"
1740
+ for from_column, to_column in pairs
1741
+ )
1742
+ return " AND ".join(
1743
+ f"{relationship.to_table}.{to_column} = {relationship.from_table}.{from_column}"
1744
+ for from_column, to_column in relationship.column_pairs
1745
+ )
1746
+
1747
+ def shortest_path(target: SchemaTableContext) -> list[tuple[SchemaTableContext, str]] | None:
1748
+ queue: list[tuple[SchemaTableContext, list[tuple[SchemaTableContext, str]]]] = [(subject, [])]
1749
+ candidates: list[list[tuple[SchemaTableContext, str]]] = []
1750
+ while queue:
1751
+ current, path = queue.pop(0)
1752
+ if len(path) >= 2:
1753
+ continue
1754
+ for edge in schema.relationships:
1755
+ endpoints = {edge.from_table.casefold(), edge.to_table.casefold()}
1756
+ if current.key not in endpoints:
1757
+ continue
1758
+ next_name = edge.to_table if edge.from_table.casefold() == current.key else edge.from_table
1759
+ next_candidates = schema.table_candidates(next_name)
1760
+ if len(next_candidates) != 1:
1761
+ continue
1762
+ next_table = next_candidates[0]
1763
+ if next_table.key in {table.key for table, _ in path} or next_table.key == subject.key:
1764
+ continue
1765
+ next_path = [*path, (next_table, condition_for(edge, current.name, next_table.name))]
1766
+ if next_table.key == target.key:
1767
+ candidates.append(next_path)
1768
+ else:
1769
+ queue.append((next_table, next_path))
1770
+ if not candidates:
1771
+ return None
1772
+ shortest = min(len(path) for path in candidates)
1773
+ shortest_paths = [path for path in candidates if len(path) == shortest]
1774
+ if len(shortest_paths) != 1:
1775
+ raise SchemaValidationError("schema relationship path is ambiguous")
1776
+ return shortest_paths[0]
1777
+
1678
1778
  relational = self._has_relational_keyword(text.lower())
1679
1779
  lowered = text.lower()
1680
1780
  unsupported_outer = (
@@ -1725,20 +1825,33 @@ class PipelineNL2SQLGenerator:
1725
1825
  for related in mentions:
1726
1826
  if related.key == subject.key:
1727
1827
  continue
1728
- candidates = schema.relationship_candidates(subject.name, related.name)
1828
+ raw_candidates = raw_edges_between(subject.name, related.name)
1729
1829
  condition = None
1730
- if len(candidates) == 1:
1731
- relationship = candidates[0]
1732
- condition = (
1733
- f"{relationship.from_table}.{relationship.from_column} = "
1734
- f"{relationship.to_table}.{relationship.to_column}"
1735
- )
1830
+ if len(raw_candidates) > 1:
1831
+ raise SchemaValidationError("schema relationship is ambiguous")
1832
+ if len(raw_candidates) == 1:
1833
+ condition = condition_for(raw_candidates[0], subject.name, related.name)
1834
+ joins.append({
1835
+ "type": join_type,
1836
+ "table": related.name,
1837
+ "subject": subject.name,
1838
+ "condition": condition,
1839
+ "relational": relational,
1840
+ "join_spec": join_spec,
1841
+ })
1842
+ continue
1843
+ if not relational:
1844
+ raise SchemaValidationError("multi-hop physical joins are unsupported")
1845
+ path = shortest_path(related)
1846
+ if path is None:
1847
+ raise SchemaValidationError("schema relationship path is missing")
1736
1848
  joins.append({
1737
1849
  "type": join_type,
1738
1850
  "table": related.name,
1739
1851
  "subject": subject.name,
1740
- "condition": condition,
1741
- "relational": relational,
1852
+ "condition": path[0][1],
1853
+ "path": [{"table": table.name, "condition": edge_condition} for table, edge_condition in path],
1854
+ "relational": True,
1742
1855
  "join_spec": join_spec,
1743
1856
  })
1744
1857
  return subject, joins
@@ -1836,6 +1949,10 @@ class PipelineNL2SQLGenerator:
1836
1949
  count_metric = self._schema_resolve_count_metric(
1837
1950
  text_lower, table_context, schema
1838
1951
  )
1952
+ unique_count_spans = self._schema_unique_count_spans(
1953
+ text_lower, count_metric
1954
+ )
1955
+ unique_count_intent = bool(unique_count_spans)
1839
1956
  columns = self._schema_resolve_columns(
1840
1957
  metric_text,
1841
1958
  table_context,
@@ -1861,10 +1978,51 @@ class PipelineNL2SQLGenerator:
1861
1978
  [label_group_column]
1862
1979
  if label_resolution is not None
1863
1980
  else self._schema_resolve_group_by(
1864
- 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,
1865
1987
  )
1866
1988
  )
1867
1989
  distinct = self._check_distinct(text_lower)
1990
+ if unique_count_intent:
1991
+ if len(unique_count_spans) != 1:
1992
+ raise SchemaValidationError(
1993
+ "multiple unique count phrases are unsupported"
1994
+ )
1995
+ consumed = text_lower
1996
+ for span in unique_count_spans:
1997
+ consumed = self._schema_mask_span(consumed, span)
1998
+ if self._check_distinct(consumed):
1999
+ raise SchemaValidationError(
2000
+ "unique count cannot be combined with DISTINCT projection"
2001
+ )
2002
+ if joins:
2003
+ raise SchemaValidationError(
2004
+ "unique count with relationships is unsupported"
2005
+ )
2006
+ if len(table_context.primary_key) != 1:
2007
+ raise SchemaValidationError(
2008
+ "unique count requires one declared primary key"
2009
+ )
2010
+ if any(
2011
+ not aggregation.upper().startswith("COUNT(")
2012
+ for aggregation in aggregations
2013
+ ):
2014
+ raise SchemaValidationError(
2015
+ "unique count cannot combine with non-COUNT aggregation"
2016
+ )
2017
+ aggregations = [
2018
+ f"COUNT(DISTINCT {table_context.primary_key[0]}) AS count"
2019
+ ]
2020
+ distinct = False
2021
+ if any(join.get("path") for join in joins):
2022
+ if conditions or aggregations or group_by or label_resolution is not None or distinct:
2023
+ raise SchemaValidationError(
2024
+ "multi-hop paths cannot be combined with filters or aggregation"
2025
+ )
1868
2026
  ordering_candidates = (
1869
2027
  self._schema_resolve_ordering(text_lower, table_context, schema)
1870
2028
  if self._schema_has_explicit_ordering(text_lower)
@@ -93,6 +93,8 @@ def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEviden
93
93
  ``(sql, explanation, confidence, evidence)``.
94
94
  """
95
95
  for join in ir.joins:
96
+ if join.get("path"):
97
+ continue
96
98
  if join.get("condition") is None:
97
99
  subject = join.get("subject") or ir.table
98
100
  pair_desc = f"{subject} ⟷ {join['table']}"
@@ -163,7 +165,19 @@ def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEviden
163
165
  # Multiple relational EXISTS clauses compose into ONE WHERE:
164
166
  # the first gets its own WHERE, the rest append with AND,
165
167
  # mirroring standard SQL 'WHERE EXISTS (...) AND EXISTS (...)'.
166
- subquery = f"SELECT 1\n FROM {join['table']}\n WHERE {join['condition']}"
168
+ if join.get("path"):
169
+ path = join["path"]
170
+ subquery = f"SELECT 1\n FROM {path[0]['table']}\n WHERE {path[0]['condition']}"
171
+ indent = " "
172
+ for step in path[1:]:
173
+ subquery += (
174
+ f"\n AND EXISTS (\n {indent}SELECT 1\n"
175
+ f" {indent}FROM {step['table']}\n"
176
+ f" {indent}WHERE {step['condition']}\n {indent})"
177
+ )
178
+ indent += " "
179
+ else:
180
+ subquery = f"SELECT 1\n FROM {join['table']}\n WHERE {join['condition']}"
167
181
  # Merge date conditions into subquery if present
168
182
  if conditions:
169
183
  cond_sql = conditions if isinstance(conditions, str) else " AND ".join(conditions)
@@ -22,6 +22,9 @@ class SchemaValidationError(ValueError):
22
22
  """Raised when generated SQL cannot be grounded in a schema."""
23
23
 
24
24
 
25
+ MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS = 1024
26
+
27
+
25
28
  def _identifier_parts(value: object) -> tuple[str, ...]:
26
29
  if not isinstance(value, str):
27
30
  raise SchemaValidationError("invalid schema identifier")
@@ -42,20 +45,37 @@ class SchemaTableContext:
42
45
  name: str
43
46
  columns: frozenset[str]
44
47
  has_column_metadata: bool
48
+ primary_key: tuple[str, ...] = ()
45
49
 
46
50
  @property
47
51
  def key(self) -> str:
48
52
  return _key(self.name)
49
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
+
50
59
 
51
60
  @dataclass(frozen=True)
52
61
  class SchemaRelationshipContext:
53
62
  """One explicitly declared relationship between two schema tables."""
54
63
 
55
64
  from_table: str
56
- from_column: str
57
65
  to_table: str
58
- to_column: str
66
+ column_pairs: tuple[tuple[str, str], ...]
67
+
68
+ @property
69
+ def from_column(self) -> str:
70
+ if len(self.column_pairs) != 1:
71
+ raise SchemaValidationError("composite relationship has no single from_column")
72
+ return self.column_pairs[0][0]
73
+
74
+ @property
75
+ def to_column(self) -> str:
76
+ if len(self.column_pairs) != 1:
77
+ raise SchemaValidationError("composite relationship has no single to_column")
78
+ return self.column_pairs[0][1]
59
79
 
60
80
  @property
61
81
  def pair(self) -> tuple[str, str]:
@@ -128,10 +148,45 @@ class SchemaContext:
128
148
  valid = False
129
149
  continue
130
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
131
185
  table = SchemaTableContext(
132
186
  name=canonical_name,
133
187
  columns=frozenset(columns),
134
188
  has_column_metadata=has_metadata,
189
+ primary_key=primary_key,
135
190
  )
136
191
  if table.key in tables_by_key:
137
192
  valid = False
@@ -144,6 +199,7 @@ class SchemaContext:
144
199
  column_candidates.setdefault(_key(column), []).append(table)
145
200
 
146
201
  relationships: list[SchemaRelationshipContext] = []
202
+ relationship_pair_count = 0
147
203
  relationships_by_pair: dict[
148
204
  tuple[str, str], list[SchemaRelationshipContext]
149
205
  ] = {}
@@ -153,37 +209,74 @@ class SchemaContext:
153
209
  continue
154
210
  try:
155
211
  from_table = ".".join(_identifier_parts(raw_relationship.get("from_table")))
156
- from_column = ".".join(_identifier_parts(raw_relationship.get("from_column")))
157
212
  to_table = ".".join(_identifier_parts(raw_relationship.get("to_table")))
158
- to_column = ".".join(_identifier_parts(raw_relationship.get("to_column")))
159
213
  except SchemaValidationError:
160
214
  valid = False
161
215
  continue
216
+ has_legacy = "from_column" in raw_relationship or "to_column" in raw_relationship
217
+ has_composite = "columns" in raw_relationship
218
+ if has_legacy == has_composite:
219
+ valid = False
220
+ continue
221
+ if has_legacy:
222
+ try:
223
+ from_column = ".".join(_identifier_parts(raw_relationship.get("from_column")))
224
+ to_column = ".".join(_identifier_parts(raw_relationship.get("to_column")))
225
+ column_pairs = ((from_column, to_column),)
226
+ except SchemaValidationError:
227
+ valid = False
228
+ continue
229
+ else:
230
+ raw_pairs = raw_relationship.get("columns")
231
+ if not isinstance(raw_pairs, (list, tuple)) or not 1 <= len(raw_pairs) <= 8:
232
+ valid = False
233
+ continue
234
+ parsed_pairs: list[tuple[str, str]] = []
235
+ seen_pairs: set[tuple[str, str]] = set()
236
+ for raw_pair in raw_pairs:
237
+ if not isinstance(raw_pair, Mapping):
238
+ valid = False
239
+ break
240
+ try:
241
+ pair = (
242
+ ".".join(_identifier_parts(raw_pair.get("from_column"))),
243
+ ".".join(_identifier_parts(raw_pair.get("to_column"))),
244
+ )
245
+ except SchemaValidationError:
246
+ valid = False
247
+ break
248
+ pair_key = (_key(pair[0]), _key(pair[1]))
249
+ if pair_key in seen_pairs:
250
+ valid = False
251
+ break
252
+ seen_pairs.add(pair_key)
253
+ parsed_pairs.append(pair)
254
+ if not valid or len(parsed_pairs) == 0:
255
+ continue
256
+ column_pairs = tuple(parsed_pairs)
257
+ relationship_pair_count += len(column_pairs)
258
+ if relationship_pair_count > MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS:
259
+ valid = False
260
+ continue
162
261
  relationship = SchemaRelationshipContext(
163
262
  from_table=from_table,
164
- from_column=from_column,
165
263
  to_table=to_table,
166
- to_column=to_column,
264
+ column_pairs=column_pairs,
167
265
  )
168
266
  from_context = tables_by_key.get(_key(from_table))
169
267
  to_context = tables_by_key.get(_key(to_table))
170
268
  if from_context is None or to_context is None:
171
269
  valid = False
172
- if from_context and from_context.has_column_metadata and _key(from_column) not in {
173
- _key(column) for column in from_context.columns
174
- }:
175
- valid = False
176
- if to_context and to_context.has_column_metadata and _key(to_column) not in {
177
- _key(column) for column in to_context.columns
178
- }:
179
- valid = False
270
+ if from_context and from_context.has_column_metadata:
271
+ valid = valid and all(_key(pair[0]) in {_key(column) for column in from_context.columns} for pair in column_pairs)
272
+ if to_context and to_context.has_column_metadata:
273
+ valid = valid and all(_key(pair[1]) in {_key(column) for column in to_context.columns} for pair in column_pairs)
180
274
  relationships.append(relationship)
181
275
  relationships_by_pair.setdefault(relationship.pair, []).append(relationship)
182
276
  reverse = SchemaRelationshipContext(
183
277
  from_table=to_table,
184
- from_column=to_column,
185
278
  to_table=from_table,
186
- to_column=from_column,
279
+ column_pairs=tuple((to_column, from_column) for from_column, to_column in column_pairs),
187
280
  )
188
281
  relationships_by_pair.setdefault(reverse.pair, []).append(reverse)
189
282
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sql-dialect-master"
3
- version = "1.8.0"
3
+ version = "1.10.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.8.0
3
+ Version: 1.10.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.8.0
41
+ Current release: 1.10.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)