sql-dialect-master 1.7.0__tar.gz → 1.9.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.7.0 → sql_dialect_master-1.9.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/README.md +1 -1
  3. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/main.py +51 -4
  4. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/metadata.py +2 -2
  5. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/ir.py +3 -0
  6. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/orchestrator.py +169 -47
  7. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/renderer.py +22 -4
  8. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_schema.py +68 -16
  9. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/pyproject.toml +1 -1
  10. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/sql_dialect_master.egg-info/PKG-INFO +2 -2
  11. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/LICENSE +0 -0
  12. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/__init__.py +0 -0
  13. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/__init__.py +0 -0
  14. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/auth.py +0 -0
  15. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/client_identity.py +0 -0
  16. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/metrics.py +0 -0
  17. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/middleware.py +0 -0
  18. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/rate_limit_store.py +0 -0
  19. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/readiness.py +0 -0
  20. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/api/workers.py +0 -0
  21. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/__init__.py +0 -0
  22. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/cache.py +0 -0
  23. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/column_hint_validation.py +0 -0
  24. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/config.py +0 -0
  25. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/constants.py +0 -0
  26. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/exceptions.py +0 -0
  27. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/function_call_scanner.py +0 -0
  28. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/function_semantics.py +0 -0
  29. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/functions_db.json +0 -0
  30. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/functions_lookup.py +0 -0
  31. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql.py +0 -0
  32. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/__init__.py +0 -0
  33. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  34. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  35. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  36. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/evidence.py +0 -0
  37. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/mappings.py +0 -0
  38. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/relations.py +0 -0
  39. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/templates.py +0 -0
  40. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  41. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_legacy.py +0 -0
  42. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_llm.py +0 -0
  43. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  44. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  45. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  46. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  47. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  48. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  49. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  50. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  51. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  52. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  53. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/nl2sql_pipeline/validation.py +0 -0
  54. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/setup.cfg +0 -0
  67. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  68. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  69. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  70. {sql_dialect_master-1.7.0 → sql_dialect_master-1.9.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.7.0
3
+ Version: 1.9.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.7.0
41
+ Current release: 1.9.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.7.0
5
+ Current release: 1.9.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
@@ -460,11 +463,33 @@ class SchemaTable(BaseModel):
460
463
  columns: List[SchemaColumn] = Field(default_factory=list, max_length=200)
461
464
 
462
465
 
466
+ class SchemaColumnPair(BaseModel):
467
+ from_column: SchemaIdentifier
468
+ to_column: SchemaIdentifier
469
+
470
+
463
471
  class SchemaRelationship(BaseModel):
464
472
  from_table: SchemaIdentifier
465
- from_column: SchemaIdentifier
473
+ from_column: Optional[SchemaIdentifier] = None
466
474
  to_table: SchemaIdentifier
467
- to_column: SchemaIdentifier
475
+ to_column: Optional[SchemaIdentifier] = None
476
+ columns: Optional[List[SchemaColumnPair]] = Field(None, max_length=8)
477
+
478
+ @model_validator(mode="after")
479
+ def validate_representation(self):
480
+ legacy = "from_column" in self.model_fields_set or "to_column" in self.model_fields_set
481
+ composite = "columns" in self.model_fields_set
482
+ if legacy == composite:
483
+ raise ValueError("invalid schema relationship")
484
+ if legacy and (self.from_column is None or self.to_column is None):
485
+ raise ValueError("invalid schema relationship")
486
+ if composite:
487
+ if not self.columns or len(self.columns) < 1:
488
+ raise ValueError("invalid schema relationship")
489
+ pairs = {(pair.from_column.casefold(), pair.to_column.casefold()) for pair in self.columns}
490
+ if len(pairs) != len(self.columns):
491
+ raise ValueError("invalid schema relationship")
492
+ return self
468
493
 
469
494
 
470
495
  class SchemaDefinition(BaseModel):
@@ -476,12 +501,34 @@ class SchemaDefinition(BaseModel):
476
501
  if sum(len(table.columns) for table in self.tables) > 1000:
477
502
  raise ValueError("Schema must contain at most 1000 columns in total")
478
503
  table_names = {table.name.casefold() for table in self.tables}
504
+ tables_by_key = {table.name.casefold(): table for table in self.tables}
505
+ relationship_pair_count = 0
479
506
  for relationship in self.relationships:
480
507
  if (
481
508
  relationship.from_table.casefold() not in table_names
482
509
  or relationship.to_table.casefold() not in table_names
483
510
  ):
484
- raise ValueError("Schema relationship references an unknown table")
511
+ raise ValueError("invalid schema relationship")
512
+ pairs = (
513
+ [(relationship.from_column, relationship.to_column)]
514
+ if relationship.columns is None
515
+ else [(pair.from_column, pair.to_column) for pair in relationship.columns]
516
+ )
517
+ relationship_pair_count += len(pairs)
518
+ if relationship_pair_count > MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS:
519
+ raise ValueError("invalid schema relationship")
520
+ from_context = tables_by_key[relationship.from_table.casefold()]
521
+ to_context = tables_by_key[relationship.to_table.casefold()]
522
+ if from_context.columns and any(
523
+ not any(column.name.casefold() == from_column.casefold() for column in from_context.columns)
524
+ for from_column, _ in pairs
525
+ ):
526
+ raise ValueError("invalid schema relationship")
527
+ if to_context.columns and any(
528
+ not any(column.name.casefold() == to_column.casefold() for column in to_context.columns)
529
+ for _, to_column in pairs
530
+ ):
531
+ raise ValueError("invalid schema relationship")
485
532
  return self
486
533
 
487
534
 
@@ -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.7.0"
21
- API_VERSION = "1.7.0"
20
+ PROJECT_VERSION = "1.9.0"
21
+ API_VERSION = "1.9.0"
22
22
  # Frontend v2 architecture — independent of the product release version.
23
23
  FRONTEND_ARCHITECTURE_VERSION = 2
24
24
 
@@ -35,6 +35,7 @@ class QueryIR:
35
35
  distinct: bool
36
36
  dialect: str
37
37
  evidence: GenerationEvidence = field(default_factory=GenerationEvidence)
38
+ orderings: Optional[List[Tuple[str, str]]] = None
38
39
 
39
40
 
40
41
  def build_ir(
@@ -49,6 +50,7 @@ def build_ir(
49
50
  joins: List[Dict],
50
51
  distinct: bool,
51
52
  dialect: str,
53
+ orderings: Optional[List[Tuple[str, str]]] = None,
52
54
  ) -> QueryIR:
53
55
  """Thin positional-arg adapter mirroring the legacy call site.
54
56
 
@@ -67,4 +69,5 @@ def build_ir(
67
69
  joins=joins,
68
70
  distinct=distinct,
69
71
  dialect=dialect,
72
+ orderings=orderings,
70
73
  )
@@ -820,7 +820,9 @@ class PipelineNL2SQLGenerator:
820
820
  f"{table_singular}_id".casefold(),
821
821
  f"{table_basename}_id".casefold(),
822
822
  }
823
- from_column = relationships[0].from_column
823
+ if len(relationships[0].column_pairs) != 1:
824
+ raise SchemaValidationError("composite group-label relationship is unsupported")
825
+ from_column = relationships[0].column_pairs[0][0]
824
826
  if from_column.casefold() not in allowed_foreign_keys:
825
827
  raise SchemaValidationError(
826
828
  "schema group label relationship has an unsupported foreign key"
@@ -983,39 +985,52 @@ class PipelineNL2SQLGenerator:
983
985
  text: str,
984
986
  table: SchemaTableContext,
985
987
  schema: SchemaContext,
986
- ) -> Optional[Tuple[str, str]]:
987
- """Resolve one explicit schema-aware ORDER BY target."""
988
+ ) -> list[tuple[str, str]]:
989
+ """Resolve schema-aware ORDER BY targets without changing no-schema extraction."""
988
990
  match = re.search(
989
- r"\b(?:order(?:ed)?|sort(?:ed)?)\s+by\s+"
990
- r"([A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)?)"
991
- r"(.*)$",
991
+ r"\b(?:order(?:ed)?|sort(?:ed)?)\s+by\s+",
992
992
  text,
993
993
  re.IGNORECASE,
994
994
  )
995
995
  if match is None:
996
- return self._extract_ordering(text)
997
- raw_column, tail = match.groups()
998
- direction = "ASC"
999
- direction_match = re.match(
1000
- r"\s+(ascending|descending|asc|desc|升序|降序)\b",
1001
- tail,
996
+ legacy = self._extract_ordering(text)
997
+ return [legacy] if legacy else []
998
+ tail = text[match.end():]
999
+ boundary = re.search(r"\b(?:where|whose|limit)\b", tail, re.IGNORECASE)
1000
+ clause = tail[:boundary.start()] if boundary else tail
1001
+ if re.search(r"\bor\b|[()\u4e00-\u9fff]", clause, re.IGNORECASE):
1002
+ raise SchemaValidationError("unsupported multi-column ordering syntax")
1003
+ items = re.split(r"\s*,\s*|\s+and\s+", clause, flags=re.IGNORECASE)
1004
+ if not items or any(not item.strip() for item in items) or len(items) > 5:
1005
+ raise SchemaValidationError("invalid or excessive ORDER BY columns")
1006
+ resolved: list[tuple[str, str]] = []
1007
+ seen: set[str] = set()
1008
+ identifier = r"[A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*){0,2}"
1009
+ item_pattern = re.compile(
1010
+ rf"^\s*({identifier})\s*(?:(ascending|descending|asc|desc)\s*)?$",
1002
1011
  re.IGNORECASE,
1003
1012
  )
1004
- if direction_match:
1005
- direction = "DESC" if direction_match.group(1).casefold() in {"descending", "desc", "降序"} else "ASC"
1006
- tail = tail[direction_match.end():]
1007
- if tail.strip(" \t\r\n,.;,。;"):
1008
- raise SchemaValidationError("multiple schema-aware ordering columns are unsupported")
1009
- parts = raw_column.split(".")
1010
- column_name = parts[-1]
1011
- if len(parts) > 1:
1012
- candidates = schema.table_candidates(".".join(parts[:-1]))
1013
- if len(candidates) != 1 or candidates[0].key != table.key:
1014
- raise SchemaValidationError("ordering column table is not the selected schema table")
1015
- canonical = schema.canonical_column(table, column_name)
1016
- if canonical is None:
1017
- raise SchemaValidationError("ordering column is outside the schema")
1018
- return canonical, direction
1013
+ for item in items:
1014
+ item_match = item_pattern.fullmatch(item)
1015
+ if item_match is None:
1016
+ raise SchemaValidationError("invalid ORDER BY column")
1017
+ raw_column, raw_direction = item_match.groups()
1018
+ parts = raw_column.split(".")
1019
+ column_name = parts[-1]
1020
+ if len(parts) > 1:
1021
+ candidates = schema.table_candidates(".".join(parts[:-1]))
1022
+ if len(candidates) != 1 or candidates[0].key != table.key:
1023
+ raise SchemaValidationError("ordering column table is not the selected schema table")
1024
+ canonical = schema.canonical_column(table, column_name)
1025
+ if canonical is None:
1026
+ raise SchemaValidationError("ordering column is outside the schema")
1027
+ key = canonical.casefold()
1028
+ if key in seen:
1029
+ raise SchemaValidationError("duplicate ORDER BY column")
1030
+ seen.add(key)
1031
+ direction = "DESC" if raw_direction and raw_direction.casefold() in {"descending", "desc"} else "ASC"
1032
+ resolved.append((canonical, direction))
1033
+ return resolved
1019
1034
 
1020
1035
  def _schema_resolve_count_metric(
1021
1036
  self,
@@ -1294,7 +1309,11 @@ class PipelineNL2SQLGenerator:
1294
1309
  if re.search(r"\bor\b|\bwhose\b|[()]", tail, re.IGNORECASE):
1295
1310
  raise SchemaValidationError("complex whose predicates are unsupported")
1296
1311
  stripped_tail = tail.strip()
1297
- if stripped_tail and not re.match(r"^and\b", stripped_tail, re.IGNORECASE):
1312
+ if stripped_tail and not re.match(
1313
+ r"^(?:and|order(?:ed)?\s+by|sort(?:ed)?\s+by)\b",
1314
+ stripped_tail,
1315
+ re.IGNORECASE,
1316
+ ):
1298
1317
  raise SchemaValidationError("unexpected text after whose predicate")
1299
1318
  span = (match.start(), value_end)
1300
1319
  return predicate, span
@@ -1352,7 +1371,11 @@ class PipelineNL2SQLGenerator:
1352
1371
 
1353
1372
  tail = executable[value_end:]
1354
1373
  stripped_tail = tail.strip()
1355
- if stripped_tail and not re.match(r"^(?:where|whose)\b", stripped_tail, re.IGNORECASE):
1374
+ if stripped_tail and not re.match(
1375
+ r"^(?:where|whose|order(?:ed)?\s+by|sort(?:ed)?\s+by)\b",
1376
+ stripped_tail,
1377
+ re.IGNORECASE,
1378
+ ):
1356
1379
  raise SchemaValidationError("unexpected text after joined-on equality")
1357
1380
 
1358
1381
  def resolve_endpoint(raw: str) -> tuple[SchemaTableContext, str]:
@@ -1390,9 +1413,12 @@ class PipelineNL2SQLGenerator:
1390
1413
  ]
1391
1414
  if raw_relationships:
1392
1415
  def matches_relationship(relationship) -> bool:
1416
+ if len(relationship.column_pairs) != 1:
1417
+ return False
1418
+ from_column, to_column = relationship.column_pairs[0]
1393
1419
  declared = {
1394
- (relationship.from_table.casefold(), relationship.from_column.casefold()),
1395
- (relationship.to_table.casefold(), relationship.to_column.casefold()),
1420
+ (relationship.from_table.casefold(), from_column.casefold()),
1421
+ (relationship.to_table.casefold(), to_column.casefold()),
1396
1422
  }
1397
1423
  supplied = {
1398
1424
  (left_table.key, left_column.casefold()),
@@ -1468,7 +1494,11 @@ class PipelineNL2SQLGenerator:
1468
1494
 
1469
1495
  tail = executable[match.end():]
1470
1496
  stripped_tail = tail.strip()
1471
- if stripped_tail and not re.match(r"^(?:where|whose)\b", stripped_tail, re.IGNORECASE):
1497
+ if stripped_tail and not re.match(
1498
+ r"^(?:where|whose|order(?:ed)?\s+by|sort(?:ed)?\s+by)\b",
1499
+ stripped_tail,
1500
+ re.IGNORECASE,
1501
+ ):
1472
1502
  raise SchemaValidationError("unexpected text after joined-with target")
1473
1503
  relationships = [
1474
1504
  relationship for relationship in schema.relationships
@@ -1479,9 +1509,9 @@ class PipelineNL2SQLGenerator:
1479
1509
  if len(relationships) != 1:
1480
1510
  raise SchemaValidationError("joined-with relationship is not unique")
1481
1511
  relationship = relationships[0]
1482
- condition = (
1483
- f"{relationship.from_table}.{relationship.from_column} = "
1484
- f"{relationship.to_table}.{relationship.to_column}"
1512
+ condition = " AND ".join(
1513
+ f"{relationship.from_table}.{from_column} = {relationship.to_table}.{to_column}"
1514
+ for from_column, to_column in relationship.column_pairs
1485
1515
  )
1486
1516
  span = (match.start(), match.end())
1487
1517
  return subject, [{
@@ -1650,6 +1680,56 @@ class PipelineNL2SQLGenerator:
1650
1680
  else:
1651
1681
  subject = mentions[0]
1652
1682
 
1683
+ def raw_edges_between(left: str, right: str) -> list:
1684
+ return [
1685
+ relationship for relationship in schema.relationships
1686
+ if {relationship.from_table.casefold(), relationship.to_table.casefold()}
1687
+ == {left.casefold(), right.casefold()}
1688
+ ]
1689
+
1690
+ def condition_for(relationship, left: str, right: str) -> str:
1691
+ if relationship.from_table.casefold() == left.casefold():
1692
+ pairs = relationship.column_pairs
1693
+ return " AND ".join(
1694
+ f"{relationship.from_table}.{from_column} = {relationship.to_table}.{to_column}"
1695
+ for from_column, to_column in pairs
1696
+ )
1697
+ return " AND ".join(
1698
+ f"{relationship.to_table}.{to_column} = {relationship.from_table}.{from_column}"
1699
+ for from_column, to_column in relationship.column_pairs
1700
+ )
1701
+
1702
+ def shortest_path(target: SchemaTableContext) -> list[tuple[SchemaTableContext, str]] | None:
1703
+ queue: list[tuple[SchemaTableContext, list[tuple[SchemaTableContext, str]]]] = [(subject, [])]
1704
+ candidates: list[list[tuple[SchemaTableContext, str]]] = []
1705
+ while queue:
1706
+ current, path = queue.pop(0)
1707
+ if len(path) >= 2:
1708
+ continue
1709
+ for edge in schema.relationships:
1710
+ endpoints = {edge.from_table.casefold(), edge.to_table.casefold()}
1711
+ if current.key not in endpoints:
1712
+ continue
1713
+ next_name = edge.to_table if edge.from_table.casefold() == current.key else edge.from_table
1714
+ next_candidates = schema.table_candidates(next_name)
1715
+ if len(next_candidates) != 1:
1716
+ continue
1717
+ next_table = next_candidates[0]
1718
+ if next_table.key in {table.key for table, _ in path} or next_table.key == subject.key:
1719
+ continue
1720
+ next_path = [*path, (next_table, condition_for(edge, current.name, next_table.name))]
1721
+ if next_table.key == target.key:
1722
+ candidates.append(next_path)
1723
+ else:
1724
+ queue.append((next_table, next_path))
1725
+ if not candidates:
1726
+ return None
1727
+ shortest = min(len(path) for path in candidates)
1728
+ shortest_paths = [path for path in candidates if len(path) == shortest]
1729
+ if len(shortest_paths) != 1:
1730
+ raise SchemaValidationError("schema relationship path is ambiguous")
1731
+ return shortest_paths[0]
1732
+
1653
1733
  relational = self._has_relational_keyword(text.lower())
1654
1734
  lowered = text.lower()
1655
1735
  unsupported_outer = (
@@ -1700,20 +1780,33 @@ class PipelineNL2SQLGenerator:
1700
1780
  for related in mentions:
1701
1781
  if related.key == subject.key:
1702
1782
  continue
1703
- candidates = schema.relationship_candidates(subject.name, related.name)
1783
+ raw_candidates = raw_edges_between(subject.name, related.name)
1704
1784
  condition = None
1705
- if len(candidates) == 1:
1706
- relationship = candidates[0]
1707
- condition = (
1708
- f"{relationship.from_table}.{relationship.from_column} = "
1709
- f"{relationship.to_table}.{relationship.to_column}"
1710
- )
1785
+ if len(raw_candidates) > 1:
1786
+ raise SchemaValidationError("schema relationship is ambiguous")
1787
+ if len(raw_candidates) == 1:
1788
+ condition = condition_for(raw_candidates[0], subject.name, related.name)
1789
+ joins.append({
1790
+ "type": join_type,
1791
+ "table": related.name,
1792
+ "subject": subject.name,
1793
+ "condition": condition,
1794
+ "relational": relational,
1795
+ "join_spec": join_spec,
1796
+ })
1797
+ continue
1798
+ if not relational:
1799
+ raise SchemaValidationError("multi-hop physical joins are unsupported")
1800
+ path = shortest_path(related)
1801
+ if path is None:
1802
+ raise SchemaValidationError("schema relationship path is missing")
1711
1803
  joins.append({
1712
1804
  "type": join_type,
1713
1805
  "table": related.name,
1714
1806
  "subject": subject.name,
1715
- "condition": condition,
1716
- "relational": relational,
1807
+ "condition": path[0][1],
1808
+ "path": [{"table": table.name, "condition": edge_condition} for table, edge_condition in path],
1809
+ "relational": True,
1717
1810
  "join_spec": join_spec,
1718
1811
  })
1719
1812
  return subject, joins
@@ -1839,13 +1932,39 @@ class PipelineNL2SQLGenerator:
1839
1932
  text_lower, table_context, schema, aggregations
1840
1933
  )
1841
1934
  )
1842
- ordering = (
1935
+ distinct = self._check_distinct(text_lower)
1936
+ if any(join.get("path") for join in joins):
1937
+ if conditions or aggregations or group_by or label_resolution is not None or distinct:
1938
+ raise SchemaValidationError(
1939
+ "multi-hop paths cannot be combined with filters or aggregation"
1940
+ )
1941
+ ordering_candidates = (
1843
1942
  self._schema_resolve_ordering(text_lower, table_context, schema)
1844
1943
  if self._schema_has_explicit_ordering(text_lower)
1845
- else None
1944
+ else []
1846
1945
  )
1946
+ if len(ordering_candidates) > 1 and (
1947
+ group_by or aggregations or label_resolution is not None
1948
+ ):
1949
+ raise SchemaValidationError(
1950
+ "multi-column ORDER BY combinations are unsupported"
1951
+ )
1952
+ if len(ordering_candidates) > 1 and distinct:
1953
+ if columns == ["*"]:
1954
+ raise SchemaValidationError(
1955
+ "DISTINCT * cannot be combined with multi-column ORDER BY"
1956
+ )
1957
+ projected = {
1958
+ column.rsplit(".", 1)[-1].casefold()
1959
+ for column in columns
1960
+ }
1961
+ if any(column.casefold() not in projected for column, _ in ordering_candidates):
1962
+ raise SchemaValidationError(
1963
+ "DISTINCT ORDER BY columns must be projected"
1964
+ )
1965
+ ordering = ordering_candidates[0] if len(ordering_candidates) == 1 else None
1966
+ orderings = ordering_candidates if len(ordering_candidates) > 1 else None
1847
1967
  limit = self._extract_limit(text_lower)
1848
- distinct = self._check_distinct(text_lower)
1849
1968
  render_columns = ["*"] if aggregations and not group_by else columns
1850
1969
  sql, explanation, confidence, evidence = self._build_sql_enhanced(
1851
1970
  operation,
@@ -1859,6 +1978,7 @@ class PipelineNL2SQLGenerator:
1859
1978
  joins,
1860
1979
  distinct,
1861
1980
  dialect,
1981
+ orderings=orderings,
1862
1982
  )
1863
1983
  result = self._apply_confidence_policy(NL2SQLResult(
1864
1984
  success=sql is not None,
@@ -2065,6 +2185,7 @@ class PipelineNL2SQLGenerator:
2065
2185
  joins,
2066
2186
  distinct,
2067
2187
  dialect,
2188
+ orderings=None,
2068
2189
  ) -> tuple:
2069
2190
  """Build SQL statement from extracted components.
2070
2191
 
@@ -2075,6 +2196,7 @@ class PipelineNL2SQLGenerator:
2075
2196
  ir = _nl2sql_ir.build_ir(
2076
2197
  operation, table, columns, conditions, aggregations,
2077
2198
  group_by, ordering, limit, joins, distinct, dialect,
2199
+ orderings=orderings,
2078
2200
  )
2079
2201
  return _render_sql_impl(ir)
2080
2202
 
@@ -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)
@@ -223,9 +237,13 @@ def render_sql(ir: QueryIR) -> Tuple[Optional[str], str, float, GenerationEviden
223
237
  group_cols = [c for c in columns if c != "*"]
224
238
  if group_cols:
225
239
  sql += f"\nGROUP BY {', '.join(group_cols)}"
226
- if ordering:
227
- sql += f"\nORDER BY {ordering[0]} {ordering[1]}"
228
- explanation_parts.append(f"排序: {ordering[0]} {ordering[1]}")
240
+ active_orderings = ir.orderings or ([ordering] if ordering else [])
241
+ if active_orderings:
242
+ ordering_sql = ", ".join(
243
+ f"{column} {direction}" for column, direction in active_orderings
244
+ )
245
+ sql += f"\nORDER BY {ordering_sql}"
246
+ explanation_parts.append(f"排序: {ordering_sql}")
229
247
  if limit is not None:
230
248
  sql = add_limit(sql, limit, dialect)
231
249
  explanation_parts.append(f"限制: {limit}条")
@@ -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")
@@ -53,9 +56,20 @@ class SchemaRelationshipContext:
53
56
  """One explicitly declared relationship between two schema tables."""
54
57
 
55
58
  from_table: str
56
- from_column: str
57
59
  to_table: str
58
- to_column: str
60
+ column_pairs: tuple[tuple[str, str], ...]
61
+
62
+ @property
63
+ def from_column(self) -> str:
64
+ if len(self.column_pairs) != 1:
65
+ raise SchemaValidationError("composite relationship has no single from_column")
66
+ return self.column_pairs[0][0]
67
+
68
+ @property
69
+ def to_column(self) -> str:
70
+ if len(self.column_pairs) != 1:
71
+ raise SchemaValidationError("composite relationship has no single to_column")
72
+ return self.column_pairs[0][1]
59
73
 
60
74
  @property
61
75
  def pair(self) -> tuple[str, str]:
@@ -144,6 +158,7 @@ class SchemaContext:
144
158
  column_candidates.setdefault(_key(column), []).append(table)
145
159
 
146
160
  relationships: list[SchemaRelationshipContext] = []
161
+ relationship_pair_count = 0
147
162
  relationships_by_pair: dict[
148
163
  tuple[str, str], list[SchemaRelationshipContext]
149
164
  ] = {}
@@ -153,37 +168,74 @@ class SchemaContext:
153
168
  continue
154
169
  try:
155
170
  from_table = ".".join(_identifier_parts(raw_relationship.get("from_table")))
156
- from_column = ".".join(_identifier_parts(raw_relationship.get("from_column")))
157
171
  to_table = ".".join(_identifier_parts(raw_relationship.get("to_table")))
158
- to_column = ".".join(_identifier_parts(raw_relationship.get("to_column")))
159
172
  except SchemaValidationError:
160
173
  valid = False
161
174
  continue
175
+ has_legacy = "from_column" in raw_relationship or "to_column" in raw_relationship
176
+ has_composite = "columns" in raw_relationship
177
+ if has_legacy == has_composite:
178
+ valid = False
179
+ continue
180
+ if has_legacy:
181
+ try:
182
+ from_column = ".".join(_identifier_parts(raw_relationship.get("from_column")))
183
+ to_column = ".".join(_identifier_parts(raw_relationship.get("to_column")))
184
+ column_pairs = ((from_column, to_column),)
185
+ except SchemaValidationError:
186
+ valid = False
187
+ continue
188
+ else:
189
+ raw_pairs = raw_relationship.get("columns")
190
+ if not isinstance(raw_pairs, (list, tuple)) or not 1 <= len(raw_pairs) <= 8:
191
+ valid = False
192
+ continue
193
+ parsed_pairs: list[tuple[str, str]] = []
194
+ seen_pairs: set[tuple[str, str]] = set()
195
+ for raw_pair in raw_pairs:
196
+ if not isinstance(raw_pair, Mapping):
197
+ valid = False
198
+ break
199
+ try:
200
+ pair = (
201
+ ".".join(_identifier_parts(raw_pair.get("from_column"))),
202
+ ".".join(_identifier_parts(raw_pair.get("to_column"))),
203
+ )
204
+ except SchemaValidationError:
205
+ valid = False
206
+ break
207
+ pair_key = (_key(pair[0]), _key(pair[1]))
208
+ if pair_key in seen_pairs:
209
+ valid = False
210
+ break
211
+ seen_pairs.add(pair_key)
212
+ parsed_pairs.append(pair)
213
+ if not valid or len(parsed_pairs) == 0:
214
+ continue
215
+ column_pairs = tuple(parsed_pairs)
216
+ relationship_pair_count += len(column_pairs)
217
+ if relationship_pair_count > MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS:
218
+ valid = False
219
+ continue
162
220
  relationship = SchemaRelationshipContext(
163
221
  from_table=from_table,
164
- from_column=from_column,
165
222
  to_table=to_table,
166
- to_column=to_column,
223
+ column_pairs=column_pairs,
167
224
  )
168
225
  from_context = tables_by_key.get(_key(from_table))
169
226
  to_context = tables_by_key.get(_key(to_table))
170
227
  if from_context is None or to_context is None:
171
228
  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
229
+ if from_context and from_context.has_column_metadata:
230
+ valid = valid and all(_key(pair[0]) in {_key(column) for column in from_context.columns} for pair in column_pairs)
231
+ if to_context and to_context.has_column_metadata:
232
+ valid = valid and all(_key(pair[1]) in {_key(column) for column in to_context.columns} for pair in column_pairs)
180
233
  relationships.append(relationship)
181
234
  relationships_by_pair.setdefault(relationship.pair, []).append(relationship)
182
235
  reverse = SchemaRelationshipContext(
183
236
  from_table=to_table,
184
- from_column=to_column,
185
237
  to_table=from_table,
186
- to_column=from_column,
238
+ column_pairs=tuple((to_column, from_column) for from_column, to_column in column_pairs),
187
239
  )
188
240
  relationships_by_pair.setdefault(reverse.pair, []).append(reverse)
189
241
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sql-dialect-master"
3
- version = "1.7.0"
3
+ version = "1.9.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.7.0
3
+ Version: 1.9.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.7.0
41
+ Current release: 1.9.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)