sql-dialect-master 1.14.1__tar.gz → 1.15.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.15.0}/PKG-INFO +2 -2
  2. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/README.md +1 -1
  3. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/main.py +140 -36
  4. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/metrics.py +5 -3
  5. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/metadata.py +2 -2
  6. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/boolean_conditions.py +46 -4
  7. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_llm.py +7 -0
  8. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/ir.py +4 -0
  9. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/orchestrator.py +59 -34
  10. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/predicates.py +1 -1
  11. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/renderer.py +35 -20
  12. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/validation.py +2 -4
  13. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_schema.py +6 -0
  14. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/parser.py +17 -3
  15. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/rules.py +9 -1
  16. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/semantic_diff.py +161 -20
  17. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/transpiler.py +163 -114
  18. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/pyproject.toml +1 -1
  19. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0/sql_dialect_master.egg-info}/PKG-INFO +2 -2
  20. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/LICENSE +0 -0
  21. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/__init__.py +0 -0
  22. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/__init__.py +0 -0
  23. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/auth.py +0 -0
  24. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/client_identity.py +0 -0
  25. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/middleware.py +0 -0
  26. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/rate_limit_store.py +0 -0
  27. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/readiness.py +0 -0
  28. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/api/workers.py +0 -0
  29. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/__init__.py +0 -0
  30. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/cache.py +0 -0
  31. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/column_hint_validation.py +0 -0
  32. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/config.py +0 -0
  33. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/constants.py +0 -0
  34. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/exceptions.py +0 -0
  35. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/function_call_scanner.py +0 -0
  36. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/function_semantics.py +0 -0
  37. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/functions_db.json +0 -0
  38. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/functions_lookup.py +0 -0
  39. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql.py +0 -0
  40. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/__init__.py +0 -0
  41. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/aggregations.py +0 -0
  42. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/core_extract.py +0 -0
  43. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/evidence.py +0 -0
  44. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/mappings.py +0 -0
  45. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/relations.py +0 -0
  46. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/templates.py +0 -0
  47. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_components/tokenizer.py +0 -0
  48. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_legacy.py +0 -0
  49. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  50. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  51. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  52. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  53. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/intent.py +0 -0
  54. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/models.py +0 -0
  55. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  56. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/scanner.py +0 -0
  57. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  58. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/nl2sql_pipeline/templates.py +0 -0
  59. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/p1_sql_scanner.py +0 -0
  60. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/p2_data_validation.py +0 -0
  61. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/post_processor.py +0 -0
  62. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/sql_statements.py +0 -0
  63. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/type_mapping.json +0 -0
  64. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/core/type_mapping.py +0 -0
  65. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/utils/__init__.py +0 -0
  66. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/backend/utils/validators.py +0 -0
  67. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/setup.cfg +0 -0
  68. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/sql_dialect_master.egg-info/SOURCES.txt +0 -0
  69. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  70. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.0}/sql_dialect_master.egg-info/requires.txt +0 -0
  71. {sql_dialect_master-1.14.1 → sql_dialect_master-1.15.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.14.1
3
+ Version: 1.15.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
@@ -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.15.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.15.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; '
@@ -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=lambda: _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
 
@@ -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)
@@ -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.15.0"
20
+ API_VERSION = "1.15.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]+)?)|"
@@ -193,12 +206,34 @@ def _comparison_matches(text: str) -> list[tuple[int, int, str]]:
193
206
  matches: list[tuple[int, int, str]] = []
194
207
  executable = mask_nl2sql_non_executable(text)
195
208
 
209
+ for match in _QUOTED_COMPARISON_PATTERN.finditer(text):
210
+ raw = match.group(0)
211
+ quote = "'" if match.group(3) is not None else '"'
212
+ quote_offset = raw.find(quote)
213
+ quote_start = match.start() + quote_offset
214
+ if executable[match.start():quote_start] != text[match.start():quote_start]:
215
+ continue
216
+ value = match.group(3) if match.group(3) is not None else match.group(4)
217
+ if value is None:
218
+ continue
219
+ if quote == "'":
220
+ value = value.replace("''", "'")
221
+ else:
222
+ value = value.replace('""', '"')
223
+ literal = "'" + value.replace("'", "''") + "'"
224
+ column, operator = match.group(1), _normalize_operator(match.group(2))
225
+ matches.append((match.start(), match.end(), f"{column} {operator} {literal}"))
226
+
196
227
  for pattern in _COMPARISON_PATTERNS:
197
228
  for match in pattern.finditer(executable):
198
229
  first, raw_operator, value = match.groups()
199
230
  column = _CN_COLUMNS.get(first, first)
200
231
  matches.append((match.start(), match.end(), f"{column} {_normalize_operator(raw_operator)} {value}"))
201
232
 
233
+ for match in _GENERIC_COMPARISON_PATTERN.finditer(executable):
234
+ column, operator, value = match.groups()
235
+ matches.append((match.start(), match.end(), f"{column} {operator} {value}"))
236
+
202
237
  for pattern in (_RANGE_PATTERN, _CN_RANGE_PATTERN):
203
238
  for match in pattern.finditer(executable):
204
239
  groups = match.groups()
@@ -213,6 +248,8 @@ def _comparison_matches(text: str) -> list[tuple[int, int, str]]:
213
248
  for pattern in (_TEXT_PATTERN, _CN_TEXT_PATTERN):
214
249
  for match in pattern.finditer(text):
215
250
  first, value = match.groups()
251
+ if re.search(r"\s+(?:and|or)\b|[()]", value, re.IGNORECASE):
252
+ continue
216
253
  column = _CN_COLUMNS.get(first, first)
217
254
  matches.append((match.start(), match.end(), _text_sql(column, value)))
218
255
 
@@ -253,7 +290,11 @@ def _comparison_matches(text: str) -> list[tuple[int, int, str]]:
253
290
  operator = "NOT IN" if operator_text == "不在" else "IN"
254
291
  matches.append((match.start(), value_end, f"{_CN_SET_COLUMNS[column]} {operator} ({values})"))
255
292
 
256
- matches.extend(_status_matches(text))
293
+ occupied = [(start, end) for start, end, _ in matches]
294
+ matches.extend(
295
+ match for match in _status_matches(text)
296
+ if not any(start <= match[0] < end or match[0] <= start < match[1] for start, end in occupied)
297
+ )
257
298
 
258
299
  matches.sort(key=lambda item: (item[0], item[1]))
259
300
  deduped: list[tuple[int, int, str]] = []
@@ -350,18 +391,19 @@ def extract_boolean_conditions(text: str) -> list[str] | None:
350
391
  if len(matches) < 2:
351
392
  return None
352
393
 
394
+ executable = mask_nl2sql_non_executable(text)
353
395
  tokens: list[str] = []
354
- prefix = text[: matches[0][0]]
396
+ prefix = executable[: matches[0][0]]
355
397
  tokens.extend(char for char in prefix if char in "()")
356
398
 
357
399
  for index, current in enumerate(matches):
358
400
  tokens.append(f"({current[2]})")
359
401
  if index == len(matches) - 1:
360
- suffix = text[current[1] :]
402
+ suffix = executable[current[1] :]
361
403
  tokens.extend(char for char in suffix if char in "()")
362
404
  continue
363
405
 
364
- separator = text[current[1] : matches[index + 1][0]]
406
+ separator = executable[current[1] : matches[index + 1][0]]
365
407
  events = []
366
408
  for paren in re.finditer(r"[()]", separator):
367
409
  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"]
@@ -96,6 +96,8 @@ class QueryIR:
96
96
  distinct_count_plan: DistinctCountPlan | None = None
97
97
  path_distinct_count_plan: PathDistinctCountPlan | None = None
98
98
  aggregate_orderings: tuple[AggregateOrderingTerm, ...] | None = None
99
+ # Subject-owned predicates in relational queries are evaluated outside EXISTS.
100
+ subject_conditions: list[str] = field(default_factory=list)
99
101
 
100
102
 
101
103
  def build_ir(
@@ -114,6 +116,7 @@ def build_ir(
114
116
  distinct_count_plan: DistinctCountPlan | None = None,
115
117
  path_distinct_count_plan: PathDistinctCountPlan | None = None,
116
118
  aggregate_orderings: tuple[AggregateOrderingTerm, ...] | None = None,
119
+ subject_conditions: list[str] | None = None,
117
120
  ) -> QueryIR:
118
121
  """Thin positional-arg adapter mirroring the legacy call site.
119
122
 
@@ -136,4 +139,5 @@ def build_ir(
136
139
  distinct_count_plan=distinct_count_plan,
137
140
  path_distinct_count_plan=path_distinct_count_plan,
138
141
  aggregate_orderings=aggregate_orderings,
142
+ subject_conditions=subject_conditions if subject_conditions is not None else [],
139
143
  )