sql-dialect-master 1.14.1__tar.gz → 1.16.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 (71) hide show
  1. {sql_dialect_master-1.14.1/sql_dialect_master.egg-info → sql_dialect_master-1.16.0}/PKG-INFO +3 -3
  2. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/README.md +1 -1
  3. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/main.py +143 -39
  4. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/metrics.py +5 -3
  5. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/middleware.py +1 -0
  6. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/metadata.py +2 -2
  7. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/boolean_conditions.py +46 -31
  8. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_llm.py +7 -0
  9. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/ir.py +31 -0
  10. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/orchestrator.py +856 -132
  11. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/predicates.py +1 -1
  12. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/renderer.py +200 -22
  13. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/validation.py +2 -4
  14. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_schema.py +8 -2
  15. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/parser.py +17 -3
  16. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/rules.py +9 -1
  17. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/semantic_diff.py +161 -20
  18. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/transpiler.py +165 -115
  19. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/pyproject.toml +2 -2
  20. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0/sql_dialect_master.egg-info}/PKG-INFO +3 -3
  21. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/sql_dialect_master.egg-info/requires.txt +1 -1
  22. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/LICENSE +0 -0
  23. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/__init__.py +0 -0
  24. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/__init__.py +0 -0
  25. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/auth.py +0 -0
  26. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/client_identity.py +0 -0
  27. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/rate_limit_store.py +0 -0
  28. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/readiness.py +0 -0
  29. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/api/workers.py +0 -0
  30. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/__init__.py +0 -0
  31. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/cache.py +0 -0
  32. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/column_hint_validation.py +0 -0
  33. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/config.py +0 -0
  34. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/constants.py +0 -0
  35. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/exceptions.py +0 -0
  36. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/function_call_scanner.py +0 -0
  37. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/function_semantics.py +0 -0
  38. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/functions_db.json +0 -0
  39. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/functions_lookup.py +0 -0
  40. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql.py +0 -0
  41. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/__init__.py +0 -0
  42. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  43. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  44. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/evidence.py +0 -0
  45. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/mappings.py +0 -0
  46. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/relations.py +0 -0
  47. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/templates.py +0 -0
  48. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  49. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_legacy.py +0 -0
  50. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  51. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  52. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  53. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  54. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  55. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  56. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  57. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/scanner.py +0 -0
  58. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  59. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  60. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/p1_sql_scanner.py +0 -0
  61. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/p2_data_validation.py +0 -0
  62. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/post_processor.py +0 -0
  63. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/sql_statements.py +0 -0
  64. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/type_mapping.json +0 -0
  65. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/core/type_mapping.py +0 -0
  66. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/utils/__init__.py +0 -0
  67. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/backend/utils/validators.py +0 -0
  68. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/setup.cfg +0 -0
  69. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  70. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  71. {sql_dialect_master-1.14.1 → sql_dialect_master-1.16.0}/sql_dialect_master.egg-info/top_level.txt +0 -0
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sql-dialect-master
3
- Version: 1.14.1
3
+ Version: 1.16.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
7
7
  License-File: LICENSE
8
- Requires-Dist: sqlglot<31.0.0,>=30.18.0
8
+ Requires-Dist: sqlglot<31.0.0,>=30.33.0
9
9
  Requires-Dist: fastapi>=0.115.0
10
10
  Requires-Dist: starlette<2.0.0,>=1.7.0
11
11
  Requires-Dist: uvicorn>=0.30.0
@@ -41,7 +41,7 @@ Dynamic: license-file
41
41
 
42
42
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
43
43
 
44
- Current release: 1.14.1
44
+ Current release: 1.16.0
45
45
 
46
46
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
47
47
  [![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.14.1
5
+ Current release: 1.16.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)
@@ -10,6 +10,7 @@ Enterprise-grade multi-database SQL conversion API:
10
10
  Exact counts are derived from the canonical data files at runtime —
11
11
  see backend.core.metadata — and must not be restated here.
12
12
  """
13
+ import asyncio
13
14
  import atexit
14
15
  import copy
15
16
  import logging
@@ -271,28 +272,6 @@ from backend.core.exceptions import ErrorCode, SDMException, UnsupportedDialectE
271
272
  ALLOWED_ORIGINS = [origin.strip() for origin in settings.allowed_origins.split(",") if origin.strip()]
272
273
  TRUSTED_PROXY_NETWORKS = settings.trusted_proxy_networks
273
274
 
274
- app.add_middleware(
275
- CORSMiddleware,
276
- allow_origins=ALLOWED_ORIGINS,
277
- allow_credentials=True,
278
- allow_methods=["GET", "POST", "OPTIONS"], # Restrict to needed methods
279
- # Keep preflight explicit so browser clients can send the correlation and
280
- # API-key headers used by the React request layer. Expose operational
281
- # response headers as well: without this list browsers silently hide
282
- # Retry-After and request timing/correlation metadata from JavaScript even
283
- # though the server emits them correctly.
284
- allow_headers=["Accept", "Content-Type", "Authorization", "X-API-Key", "X-Request-ID"],
285
- expose_headers=[
286
- "Retry-After",
287
- "X-API-Version",
288
- "X-Process-Time",
289
- "X-RateLimit-Limit",
290
- "X-RateLimit-Remaining",
291
- "X-RateLimit-Reset",
292
- "X-Request-ID",
293
- ],
294
- )
295
-
296
275
  # Type/function matrices and conversion reports are often much larger than
297
276
  # the request itself. Compress them at the ASGI boundary so browser clients
298
277
  # spend less time waiting on the network without changing response schemas.
@@ -355,6 +334,26 @@ async def add_process_time_header(request: Request, call_next):
355
334
  # circuit responses returned by rate limiting and worker-capacity guards.
356
335
  app.add_middleware(MetricsMiddleware)
357
336
 
337
+ # Keep CORS outermost so browser clients receive CORS headers on every
338
+ # response, including body-size, validation, rate-limit, and internal errors
339
+ # returned by middleware before an endpoint runs.
340
+ app.add_middleware(
341
+ CORSMiddleware,
342
+ allow_origins=ALLOWED_ORIGINS,
343
+ allow_credentials=True,
344
+ allow_methods=["GET", "POST", "OPTIONS"],
345
+ allow_headers=["Accept", "Content-Type", "Authorization", "X-API-Key", "X-Request-ID"],
346
+ expose_headers=[
347
+ "Retry-After",
348
+ "X-API-Version",
349
+ "X-Process-Time",
350
+ "X-RateLimit-Limit",
351
+ "X-RateLimit-Remaining",
352
+ "X-RateLimit-Reset",
353
+ "X-Request-ID",
354
+ ],
355
+ )
356
+
358
357
  # Dialect info for enhanced responses (from centralized config)
359
358
  DIALECT_INFO = get_dialect_api_info()
360
359
 
@@ -418,7 +417,7 @@ class ConvertResponse(BaseModel):
418
417
  transformations: list[str] = Field(default_factory=list, description="Applied transformations")
419
418
  warnings: list[str] = Field(default_factory=list, description="Conversion warnings")
420
419
  target_validation_state: str = Field(
421
- "target_valid",
420
+ "not_checked",
422
421
  description=(
423
422
  "Target-dialect parse status of the produced output. "
424
423
  '"target_valid": target parser accepted the output; '
@@ -428,7 +427,7 @@ class ConvertResponse(BaseModel):
428
427
  '"invalid": neither parser accepts the output.'
429
428
  ),
430
429
  )
431
- timestamp: str = Field(default_factory=lambda: _now_iso(), description="Response timestamp")
430
+ timestamp: str = Field(default_factory=_now_iso, description="Response timestamp")
432
431
 
433
432
 
434
433
  class BatchConvertRequest(BaseModel):
@@ -459,7 +458,7 @@ class BatchConvertResponse(BaseModel):
459
458
  count: int
460
459
  succeeded: int
461
460
  failed: int
462
- timestamp: str = Field(default_factory=lambda: _now_iso())
461
+ timestamp: str = Field(default_factory=_now_iso)
463
462
 
464
463
 
465
464
  SchemaIdentifier = Annotated[
@@ -634,6 +633,102 @@ class ParseRequest(BaseModel):
634
633
  dialect: str = Field("hive", description="SQL dialect")
635
634
 
636
635
 
636
+ class ParseElementsResponse(BaseModel):
637
+ """Structured parser metadata returned by the analysis endpoint."""
638
+
639
+ query_type: str
640
+ tables: list[dict[str, Any]] = Field(default_factory=list)
641
+ columns: list[dict[str, Any]] = Field(default_factory=list)
642
+ functions: list[dict[str, Any]] = Field(default_factory=list)
643
+ joins: list[dict[str, Any]] = Field(default_factory=list)
644
+ has_subquery: bool = False
645
+ has_cte: bool = False
646
+ has_window: bool = False
647
+ has_aggregation: bool = False
648
+ has_distinct: bool = False
649
+ has_union: bool = False
650
+ has_order_by: bool = False
651
+ has_limit: bool = False
652
+
653
+
654
+ class ParseResponse(BaseModel):
655
+ """Response contract for SQL analysis metadata."""
656
+
657
+ success: bool
658
+ dialect: str
659
+ elements: ParseElementsResponse
660
+ timestamp: str = Field(default_factory=_now_iso)
661
+
662
+
663
+ class SemanticDiffResponse(BaseModel):
664
+ """Response contract for target-aware semantic comparison."""
665
+
666
+ success: bool
667
+ equivalent: bool
668
+ source_normalized: str | None = None
669
+ target_normalized: str | None = None
670
+ differences: list[str] = Field(default_factory=list)
671
+ parse_error: str | None = None
672
+ error: str | None = None
673
+ status: str
674
+ difference_categories: list[str] = Field(default_factory=list)
675
+ structured_differences: list[dict[str, Any]] = Field(default_factory=list)
676
+ semantic_classification: str
677
+ confidence: float
678
+ evidence: str | None = None
679
+
680
+
681
+ class FunctionListResponse(BaseModel):
682
+ success: bool
683
+ functions: list[dict[str, Any]] = Field(default_factory=list)
684
+ count: int
685
+ total: int
686
+ stats: dict[str, Any] = Field(default_factory=dict)
687
+
688
+
689
+ class FunctionCategoriesResponse(BaseModel):
690
+ success: bool
691
+ categories: list[dict[str, Any]] = Field(default_factory=list)
692
+ count: int
693
+
694
+
695
+ class FunctionDetailResponse(BaseModel):
696
+ success: bool
697
+ function: dict[str, Any]
698
+ comparison: dict[str, Any]
699
+
700
+
701
+ class TypeMappingsResponse(BaseModel):
702
+ success: bool
703
+ mappings: list[dict[str, Any]] = Field(default_factory=list)
704
+ dialects: list[str] = Field(default_factory=list)
705
+ type_count: int
706
+ precision_warnings: dict[str, str] = Field(default_factory=dict)
707
+
708
+
709
+ class TypeDetailResponse(BaseModel):
710
+ """Detailed type comparison returned by ``TypeMapper.compare_types``."""
711
+
712
+ success: bool
713
+ type: str
714
+ category: str | None = None
715
+ dialects: dict[str, str] = Field(default_factory=dict)
716
+ notes: str = ""
717
+ availability: dict[str, Any] = Field(default_factory=dict)
718
+ model_config = ConfigDict(extra="allow")
719
+
720
+
721
+ class TypeMapResponse(BaseModel):
722
+ success: bool
723
+ timestamp: str
724
+ type_name: str | None = None
725
+ target_type: str | None = None
726
+ mapping_status: str | None = None
727
+ warnings: list[str] = Field(default_factory=list)
728
+ error: str | None = None
729
+ model_config = ConfigDict(extra="allow")
730
+
731
+
637
732
  class DiffRequest(BaseModel):
638
733
  """Semantic SQL comparison request."""
639
734
 
@@ -669,7 +764,7 @@ class APIResponse(BaseModel):
669
764
  success: bool = Field(..., description="Operation success status")
670
765
  data: dict[str, Any] | None = Field(None, description="Response data")
671
766
  error: str | None = Field(None, description="Error message if failed")
672
- timestamp: str = Field(default_factory=lambda: _now_iso())
767
+ timestamp: str = Field(default_factory=_now_iso)
673
768
 
674
769
  # === API Endpoints ===
675
770
 
@@ -875,7 +970,7 @@ async def convert_sql_batch(request: BatchConvertRequest):
875
970
  return response
876
971
 
877
972
 
878
- @app.post("/api/parse", tags=["conversion"])
973
+ @app.post("/api/parse", response_model=ParseResponse, tags=["conversion"])
879
974
  async def parse_sql(request: ParseRequest):
880
975
  """
881
976
  Parse SQL and extract elements.
@@ -895,7 +990,7 @@ async def parse_sql(request: ParseRequest):
895
990
  }
896
991
 
897
992
 
898
- @app.post("/api/diff", tags=["conversion"])
993
+ @app.post("/api/diff", response_model=SemanticDiffResponse, tags=["conversion"])
899
994
  async def compare_semantic_diff(request: DiffRequest):
900
995
  """Compare source and target SQL without executing either statement."""
901
996
  source_dialect = normalize_dialect(request.source_dialect, "source dialect")
@@ -913,7 +1008,7 @@ async def compare_semantic_diff(request: DiffRequest):
913
1008
  payload["error"] = result.parse_error
914
1009
  return payload
915
1010
 
916
- @app.get("/api/functions", tags=["functions"])
1011
+ @app.get("/api/functions", response_model=FunctionListResponse, tags=["functions"])
917
1012
  async def list_functions(
918
1013
  search: str | None = Query(None, description="Search term for function name"),
919
1014
  category: str | None = Query(None, description="Filter by category (string, date, math, etc.)"),
@@ -954,7 +1049,7 @@ async def list_functions(
954
1049
  "stats": func_encyclopedia.get_stats()
955
1050
  }
956
1051
 
957
- @app.get("/api/functions/categories", tags=["functions"])
1052
+ @app.get("/api/functions/categories", response_model=FunctionCategoriesResponse, tags=["functions"])
958
1053
  async def get_function_categories():
959
1054
  """
960
1055
  Get all function categories with counts.
@@ -968,7 +1063,7 @@ async def get_function_categories():
968
1063
  "count": len(categories)
969
1064
  }
970
1065
 
971
- @app.get("/api/functions/{name}", tags=["functions"])
1066
+ @app.get("/api/functions/{name}", response_model=FunctionDetailResponse, tags=["functions"])
972
1067
  async def get_function(name: str):
973
1068
  """
974
1069
  Get detailed function information.
@@ -989,7 +1084,7 @@ async def get_function(name: str):
989
1084
  "comparison": comparison
990
1085
  }
991
1086
 
992
- @app.get("/api/types", tags=["types"])
1087
+ @app.get("/api/types", response_model=TypeMappingsResponse, tags=["types"])
993
1088
  async def list_types(
994
1089
  source: str | None = Query(None, description="Filter by source dialect"),
995
1090
  target: str | None = Query(None, description="Filter by target dialect")
@@ -1023,7 +1118,7 @@ async def list_types(
1023
1118
  "precision_warnings": type_mapper.get_precision_warnings()
1024
1119
  }
1025
1120
 
1026
- @app.get("/api/types/{type_name}", tags=["types"])
1121
+ @app.get("/api/types/{type_name}", response_model=TypeDetailResponse, tags=["types"])
1027
1122
  async def get_type(type_name: str):
1028
1123
  """
1029
1124
  Get type mapping details for a specific type.
@@ -1041,7 +1136,7 @@ async def get_type(type_name: str):
1041
1136
  **comparison
1042
1137
  }
1043
1138
 
1044
- @app.post("/api/types/map", tags=["types"])
1139
+ @app.post("/api/types/map", response_model=TypeMapResponse, tags=["types"])
1045
1140
  async def map_type(request: TypeMapRequest):
1046
1141
  """
1047
1142
  Map a type from source to target dialect.
@@ -1126,10 +1221,16 @@ async def generate_sql(request: NL2SQLRequest):
1126
1221
  # Keep the legacy no-schema client call compatible with direct
1127
1222
  # callers and providers that implement the existing signature.
1128
1223
  schema_options = {"schema": schema} if schema is not None else {}
1129
- generation = await LLMN2SQLClient().generate(
1130
- request.text, dialect, request.table_hint, request.column_hints,
1131
- **schema_options,
1132
- )
1224
+ try:
1225
+ generation = await asyncio.wait_for(
1226
+ LLMN2SQLClient().generate(
1227
+ request.text, dialect, request.table_hint, request.column_hints,
1228
+ **schema_options,
1229
+ ),
1230
+ timeout=settings.nl2sql_llm_timeout + 0.5,
1231
+ )
1232
+ except TimeoutError:
1233
+ raise LLMError("timeout") from None
1133
1234
  sql = (
1134
1235
  validate_llm_sql(generation.sql, dialect)
1135
1236
  if schema is None
@@ -1339,7 +1440,10 @@ async def unhandled_exception_handler(request: Request, exc: Exception):
1339
1440
  }
1340
1441
  if request_id:
1341
1442
  content["request_id"] = request_id
1342
- return JSONResponse(status_code=500, content=content)
1443
+ headers = {}
1444
+ if request_id:
1445
+ headers["X-Request-ID"] = request_id
1446
+ return JSONResponse(status_code=500, content=content, headers=headers)
1343
1447
 
1344
1448
  # Run with: uvicorn backend.api.main:app --reload
1345
1449
  if __name__ == "__main__":
@@ -236,6 +236,8 @@ class MetricsMiddleware:
236
236
  status_code = message.get("status", 500)
237
237
  await send(message)
238
238
 
239
- await self.app(scope, receive, send_wrapper)
240
- request = Request(scope)
241
- record_http_request(request, status_code, time.perf_counter() - started)
239
+ try:
240
+ await self.app(scope, receive, send_wrapper)
241
+ finally:
242
+ request = Request(scope)
243
+ record_http_request(request, status_code, time.perf_counter() - started)
@@ -226,6 +226,7 @@ class StructuredLoggingMiddleware(BaseHTTPMiddleware):
226
226
  if parsed.variant == uuid.RFC_4122:
227
227
  return candidate
228
228
  except (ValueError, AttributeError, TypeError):
229
+ # Invalid caller-supplied IDs are replaced with a fresh UUID.
229
230
  pass
230
231
  return str(uuid.uuid4())
231
232
 
@@ -16,8 +16,8 @@ Design rules:
16
16
  from __future__ import annotations
17
17
 
18
18
  # ── Release version facts (sole source of truth) ────────────────────────
19
- PROJECT_VERSION = "1.14.1"
20
- API_VERSION = "1.14.1"
19
+ PROJECT_VERSION = "1.16.0"
20
+ API_VERSION = "1.16.0"
21
21
  # Frontend v2 architecture — independent of the product release version.
22
22
  FRONTEND_ARCHITECTURE_VERSION = 2
23
23
 
@@ -28,6 +28,19 @@ _COMPARISON_PATTERNS = (
28
28
  ),
29
29
  )
30
30
 
31
+ _GENERIC_COMPARISON_PATTERN = re.compile(
32
+ r"(?<![A-Za-z0-9_$])([A-Za-z_][A-Za-z0-9_$]*)\s*"
33
+ r"(>=|<=|!=|<>|=|>|<)\s*(-?[0-9]+(?:\.[0-9]+)?)",
34
+ re.IGNORECASE,
35
+ )
36
+
37
+ _QUOTED_COMPARISON_PATTERN = re.compile(
38
+ r"(?<![A-Za-z0-9_$])([A-Za-z_][A-Za-z0-9_$]*)\s*"
39
+ r"(is\s+not|isn't|not|is|<>|!=|>=|<=|=|>|<)\s*"
40
+ r"(?:'((?:''|[^'])*)'|\"((?:\"\"|[^\"])*)\")",
41
+ re.IGNORECASE,
42
+ )
43
+
31
44
  _RANGE_PATTERN = re.compile(
32
45
  r"(?<![A-Za-z0-9_])(price|quantity|amount|age|score|rating|views|clicks)\s+"
33
46
  r"(?:between\s+(-?[0-9]+(?:\.[0-9]+)?)\s+and\s+(-?[0-9]+(?:\.[0-9]+)?)|"
@@ -74,33 +87,6 @@ _CN_SET_PREFIX_PATTERN = re.compile(
74
87
  r"(类别|类型|部门|地区|状态)\s*(不在|在)\s*"
75
88
  )
76
89
 
77
- _STATUS_PATTERN = re.compile(
78
- r"(?:\bstatus\s+|状态\s*(?:为|是|=)\s*)"
79
- r"(active|enabled|valid|inactive|disabled|invalid|completed|done|pending|paid|unpaid|"
80
- r"有效|无效|已完成|未完成|已支付|未支付)",
81
- re.IGNORECASE,
82
- )
83
-
84
- _STATUS_CONDITIONS = {
85
- "active": "status = 'active'",
86
- "enabled": "status = 'active'",
87
- "valid": "status = 'active'",
88
- "有效": "status = 'active'",
89
- "inactive": "status = 'inactive'",
90
- "disabled": "status = 'inactive'",
91
- "invalid": "status = 'inactive'",
92
- "无效": "status = 'inactive'",
93
- "completed": "status = 'completed'",
94
- "done": "status = 'completed'",
95
- "已完成": "status = 'completed'",
96
- "pending": "status = 'pending'",
97
- "未完成": "status = 'pending'",
98
- "paid": "status = 'paid'",
99
- "已支付": "status = 'paid'",
100
- "unpaid": "status = 'unpaid'",
101
- "未支付": "status = 'unpaid'",
102
- }
103
-
104
90
  _STATUS_VALUES = {
105
91
  "active": "active",
106
92
  "inactive": "inactive",
@@ -193,12 +179,34 @@ def _comparison_matches(text: str) -> list[tuple[int, int, str]]:
193
179
  matches: list[tuple[int, int, str]] = []
194
180
  executable = mask_nl2sql_non_executable(text)
195
181
 
182
+ for match in _QUOTED_COMPARISON_PATTERN.finditer(text):
183
+ raw = match.group(0)
184
+ quote = "'" if match.group(3) is not None else '"'
185
+ quote_offset = raw.find(quote)
186
+ quote_start = match.start() + quote_offset
187
+ if executable[match.start():quote_start] != text[match.start():quote_start]:
188
+ continue
189
+ value = match.group(3) if match.group(3) is not None else match.group(4)
190
+ if value is None:
191
+ continue
192
+ if quote == "'":
193
+ value = value.replace("''", "'")
194
+ else:
195
+ value = value.replace('""', '"')
196
+ literal = "'" + value.replace("'", "''") + "'"
197
+ column, operator = match.group(1), _normalize_operator(match.group(2))
198
+ matches.append((match.start(), match.end(), f"{column} {operator} {literal}"))
199
+
196
200
  for pattern in _COMPARISON_PATTERNS:
197
201
  for match in pattern.finditer(executable):
198
202
  first, raw_operator, value = match.groups()
199
203
  column = _CN_COLUMNS.get(first, first)
200
204
  matches.append((match.start(), match.end(), f"{column} {_normalize_operator(raw_operator)} {value}"))
201
205
 
206
+ for match in _GENERIC_COMPARISON_PATTERN.finditer(executable):
207
+ column, operator, value = match.groups()
208
+ matches.append((match.start(), match.end(), f"{column} {operator} {value}"))
209
+
202
210
  for pattern in (_RANGE_PATTERN, _CN_RANGE_PATTERN):
203
211
  for match in pattern.finditer(executable):
204
212
  groups = match.groups()
@@ -213,6 +221,8 @@ def _comparison_matches(text: str) -> list[tuple[int, int, str]]:
213
221
  for pattern in (_TEXT_PATTERN, _CN_TEXT_PATTERN):
214
222
  for match in pattern.finditer(text):
215
223
  first, value = match.groups()
224
+ if re.search(r"\s+(?:and|or)\b|[()]", value, re.IGNORECASE):
225
+ continue
216
226
  column = _CN_COLUMNS.get(first, first)
217
227
  matches.append((match.start(), match.end(), _text_sql(column, value)))
218
228
 
@@ -253,7 +263,11 @@ def _comparison_matches(text: str) -> list[tuple[int, int, str]]:
253
263
  operator = "NOT IN" if operator_text == "不在" else "IN"
254
264
  matches.append((match.start(), value_end, f"{_CN_SET_COLUMNS[column]} {operator} ({values})"))
255
265
 
256
- matches.extend(_status_matches(text))
266
+ occupied = [(start, end) for start, end, _ in matches]
267
+ matches.extend(
268
+ match for match in _status_matches(text)
269
+ if not any(start <= match[0] < end or match[0] <= start < match[1] for start, end in occupied)
270
+ )
257
271
 
258
272
  matches.sort(key=lambda item: (item[0], item[1]))
259
273
  deduped: list[tuple[int, int, str]] = []
@@ -350,18 +364,19 @@ def extract_boolean_conditions(text: str) -> list[str] | None:
350
364
  if len(matches) < 2:
351
365
  return None
352
366
 
367
+ executable = mask_nl2sql_non_executable(text)
353
368
  tokens: list[str] = []
354
- prefix = text[: matches[0][0]]
369
+ prefix = executable[: matches[0][0]]
355
370
  tokens.extend(char for char in prefix if char in "()")
356
371
 
357
372
  for index, current in enumerate(matches):
358
373
  tokens.append(f"({current[2]})")
359
374
  if index == len(matches) - 1:
360
- suffix = text[current[1] :]
375
+ suffix = executable[current[1] :]
361
376
  tokens.extend(char for char in suffix if char in "()")
362
377
  continue
363
378
 
364
- separator = text[current[1] : matches[index + 1][0]]
379
+ separator = executable[current[1] : matches[index + 1][0]]
365
380
  events = []
366
381
  for paren in re.finditer(r"[()]", separator):
367
382
  events.append((paren.start(), paren.group(0)))
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
  import json
5
5
  import logging
6
6
  import re
7
+ import time
7
8
  from contextvars import ContextVar
8
9
  from dataclasses import dataclass
9
10
 
@@ -22,6 +23,7 @@ _ERROR_REASONS = frozenset({
22
23
  _VALIDATING_LLM_SQL = ContextVar("validating_llm_sql", default=False)
23
24
  _SQLGLOT_LOGGER = logging.getLogger("sqlglot")
24
25
  _SQL_FENCE = re.compile(r"```(?:sql)?[ \t]*\r?\n(.*?)\r?\n?```", re.IGNORECASE | re.DOTALL)
26
+ MAX_LLM_RESPONSE_BYTES = 1_048_576
25
27
 
26
28
 
27
29
  class LLMError(Exception):
@@ -174,6 +176,7 @@ class LLMN2SQLClient:
174
176
  },
175
177
  ],
176
178
  }
179
+ started = time.monotonic()
177
180
  try:
178
181
  async with httpx.AsyncClient(
179
182
  timeout=configured.nl2sql_llm_timeout,
@@ -183,6 +186,8 @@ class LLMN2SQLClient:
183
186
  response = await client.post(
184
187
  f"{configured.nl2sql_llm_base_url}/chat/completions", headers=headers, json=payload,
185
188
  )
189
+ if time.monotonic() - started > configured.nl2sql_llm_timeout:
190
+ raise LLMError("timeout")
186
191
  except httpx.TimeoutException:
187
192
  raise LLMError("timeout") from None
188
193
  except (httpx.HTTPError, ValueError):
@@ -193,6 +198,8 @@ class LLMN2SQLClient:
193
198
  raise LLMError("http_5xx")
194
199
  if not 200 <= response.status_code < 300:
195
200
  raise LLMError("http_error")
201
+ if len(response.content) > MAX_LLM_RESPONSE_BYTES:
202
+ raise LLMError("invalid_response")
196
203
  try:
197
204
  body = response.json()
198
205
  choices = body["choices"]
@@ -38,6 +38,30 @@ class PathCondition:
38
38
  literal: str
39
39
 
40
40
 
41
+ @dataclass(frozen=True)
42
+ class AssociationCondition:
43
+ """One predicate owned by the subject or data side of an association."""
44
+
45
+ owner: str
46
+ table: str
47
+ column: str
48
+ operator: str
49
+ literal: str
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class AssociationCountPlan:
54
+ """Validated one-hop row association count."""
55
+
56
+ subject_table: str
57
+ data_table: str
58
+ relationship_pairs: tuple[tuple[str, str], ...]
59
+ subject_identity: tuple[str, ...]
60
+ subject_conditions: tuple[AssociationCondition, ...] = ()
61
+ data_conditions: tuple[AssociationCondition, ...] = ()
62
+ orderings: tuple["AggregateOrderingTerm", ...] = ()
63
+
64
+
41
65
  @dataclass(frozen=True)
42
66
  class PathOrderingTerm:
43
67
  """One typed aggregate or subject-group ordering for a path count."""
@@ -95,7 +119,10 @@ class QueryIR:
95
119
  orderings: list[tuple[str, str]] | None = None
96
120
  distinct_count_plan: DistinctCountPlan | None = None
97
121
  path_distinct_count_plan: PathDistinctCountPlan | None = None
122
+ association_count_plan: AssociationCountPlan | None = None
98
123
  aggregate_orderings: tuple[AggregateOrderingTerm, ...] | None = None
124
+ # Subject-owned predicates in relational queries are evaluated outside EXISTS.
125
+ subject_conditions: list[str] = field(default_factory=list)
99
126
 
100
127
 
101
128
  def build_ir(
@@ -113,7 +140,9 @@ def build_ir(
113
140
  orderings: list[tuple[str, str]] | None = None,
114
141
  distinct_count_plan: DistinctCountPlan | None = None,
115
142
  path_distinct_count_plan: PathDistinctCountPlan | None = None,
143
+ association_count_plan: AssociationCountPlan | None = None,
116
144
  aggregate_orderings: tuple[AggregateOrderingTerm, ...] | None = None,
145
+ subject_conditions: list[str] | None = None,
117
146
  ) -> QueryIR:
118
147
  """Thin positional-arg adapter mirroring the legacy call site.
119
148
 
@@ -135,5 +164,7 @@ def build_ir(
135
164
  orderings=orderings,
136
165
  distinct_count_plan=distinct_count_plan,
137
166
  path_distinct_count_plan=path_distinct_count_plan,
167
+ association_count_plan=association_count_plan,
138
168
  aggregate_orderings=aggregate_orderings,
169
+ subject_conditions=subject_conditions if subject_conditions is not None else [],
139
170
  )