sql-dialect-master 1.13.0__tar.gz → 1.14.1__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.
- {sql_dialect_master-1.13.0/sql_dialect_master.egg-info → sql_dialect_master-1.14.1}/PKG-INFO +15 -2
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/README.md +11 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/main.py +115 -74
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/metrics.py +18 -6
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/middleware.py +38 -18
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/rate_limit_store.py +4 -3
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/readiness.py +16 -6
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/workers.py +1 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/__init__.py +33 -33
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/cache.py +18 -14
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/column_hint_validation.py +2 -2
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/config.py +39 -37
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/constants.py +0 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/exceptions.py +13 -7
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/function_call_scanner.py +1 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/function_semantics.py +6 -8
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/functions_lookup.py +26 -27
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/metadata.py +5 -6
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql.py +3 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/__init__.py +12 -20
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/aggregations.py +11 -11
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/boolean_conditions.py +10 -12
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/core_extract.py +22 -20
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/evidence.py +10 -12
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/mappings.py +3 -6
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/relations.py +7 -9
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/templates.py +5 -5
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_components/tokenizer.py +7 -8
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_legacy.py +0 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_llm.py +8 -5
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/aggregations.py +2 -4
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/clause_extract.py +9 -8
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/dialect.py +1 -2
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/intent.py +15 -12
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/ir.py +54 -22
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/models.py +0 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/orchestrator.py +1119 -179
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/predicates.py +10 -13
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/renderer.py +349 -21
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/resolution.py +23 -16
- sql_dialect_master-1.14.1/backend/core/nl2sql_pipeline/scanner.py +26 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/suggestions.py +0 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/templates.py +42 -25
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/validation.py +3 -4
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_schema.py +5 -6
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/p1_sql_scanner.py +54 -9
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/parser.py +37 -30
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/post_processor.py +7 -8
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/rules.py +24 -17
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/semantic_diff.py +20 -21
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/transpiler.py +88 -79
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/type_mapping.py +69 -82
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/utils/__init__.py +0 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/utils/validators.py +9 -12
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/pyproject.toml +4 -1
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1/sql_dialect_master.egg-info}/PKG-INFO +15 -2
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/sql_dialect_master.egg-info/SOURCES.txt +1 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/sql_dialect_master.egg-info/requires.txt +3 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/LICENSE +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/__init__.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/__init__.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/auth.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/api/client_identity.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/functions_db.json +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/nl2sql_pipeline/__init__.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/p2_data_validation.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/sql_statements.py +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/backend/core/type_mapping.json +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/setup.cfg +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
- {sql_dialect_master-1.13.0 → sql_dialect_master-1.14.1}/sql_dialect_master.egg-info/top_level.txt +0 -0
{sql_dialect_master-1.13.0/sql_dialect_master.egg-info → sql_dialect_master-1.14.1}/PKG-INFO
RENAMED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sql-dialect-master
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.14.1
|
|
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
8
|
Requires-Dist: sqlglot<31.0.0,>=30.18.0
|
|
9
9
|
Requires-Dist: fastapi>=0.115.0
|
|
10
|
+
Requires-Dist: starlette<2.0.0,>=1.7.0
|
|
10
11
|
Requires-Dist: uvicorn>=0.30.0
|
|
11
12
|
Requires-Dist: pydantic>=2.9.0
|
|
12
13
|
Requires-Dist: pydantic-settings>=2.0.0
|
|
@@ -17,6 +18,7 @@ Requires-Dist: hypothesis>=6.112.0; extra == "dev"
|
|
|
17
18
|
Requires-Dist: pytest>=8.3.0; extra == "dev"
|
|
18
19
|
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
|
|
19
20
|
Requires-Dist: httpx>=0.27.0; extra == "dev"
|
|
21
|
+
Requires-Dist: httpx2<3.0.0,>=2.16.2; extra == "dev"
|
|
20
22
|
Requires-Dist: requests>=2.31.0; extra == "dev"
|
|
21
23
|
Provides-Extra: qa
|
|
22
24
|
Requires-Dist: mypy<2.0,>=1.11; extra == "qa"
|
|
@@ -30,6 +32,7 @@ Requires-Dist: wheel>=0.45; extra == "qa"
|
|
|
30
32
|
Provides-Extra: semantic
|
|
31
33
|
Requires-Dist: duckdb>=1.5.5; extra == "semantic"
|
|
32
34
|
Requires-Dist: psycopg[binary]>=3.3.5; extra == "semantic"
|
|
35
|
+
Requires-Dist: pytz>=2024.1; extra == "semantic"
|
|
33
36
|
Provides-Extra: redis
|
|
34
37
|
Requires-Dist: redis>=5.0.0; extra == "redis"
|
|
35
38
|
Dynamic: license-file
|
|
@@ -38,7 +41,7 @@ Dynamic: license-file
|
|
|
38
41
|
|
|
39
42
|
Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
|
|
40
43
|
|
|
41
|
-
Current release: 1.
|
|
44
|
+
Current release: 1.14.1
|
|
42
45
|
|
|
43
46
|
[](https://www.python.org/downloads/)
|
|
44
47
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -367,6 +370,16 @@ sql-dialect-master/
|
|
|
367
370
|
| `/health/deep` | GET | Deep health check |
|
|
368
371
|
| `/api/stats` | GET | Service and dataset statistics |
|
|
369
372
|
|
|
373
|
+
Request length limits are exposed in the OpenAPI schema. SQL fields for
|
|
374
|
+
conversion and batch items use `SDM_TRANSPILER_MAX_SQL_LENGTH` (default
|
|
375
|
+
100,000 characters); parsing and both semantic-diff SQL fields use
|
|
376
|
+
`SDM_PARSER_MAX_SQL_LENGTH` (defaulting to the same value); NL2SQL text uses
|
|
377
|
+
`SDM_NL2SQL_MAX_INPUT_LENGTH` (default 8,192). Exceeding an individual field
|
|
378
|
+
returns HTTP 422 with `VALIDATION_FAILED`. The aggregate request-body limit
|
|
379
|
+
remains 512 KiB and returns HTTP 413 with `PAYLOAD_TOO_LARGE`. A syntax error
|
|
380
|
+
within a permitted field keeps the endpoint's normal analysis response, such
|
|
381
|
+
as HTTP 200 `parse_error` from semantic diff.
|
|
382
|
+
|
|
370
383
|
For example, send this JSON body to `POST /api/convert/batch`:
|
|
371
384
|
|
|
372
385
|
```json
|
|
@@ -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.
|
|
5
|
+
Current release: 1.14.1
|
|
6
6
|
|
|
7
7
|
[](https://www.python.org/downloads/)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -331,6 +331,16 @@ sql-dialect-master/
|
|
|
331
331
|
| `/health/deep` | GET | Deep health check |
|
|
332
332
|
| `/api/stats` | GET | Service and dataset statistics |
|
|
333
333
|
|
|
334
|
+
Request length limits are exposed in the OpenAPI schema. SQL fields for
|
|
335
|
+
conversion and batch items use `SDM_TRANSPILER_MAX_SQL_LENGTH` (default
|
|
336
|
+
100,000 characters); parsing and both semantic-diff SQL fields use
|
|
337
|
+
`SDM_PARSER_MAX_SQL_LENGTH` (defaulting to the same value); NL2SQL text uses
|
|
338
|
+
`SDM_NL2SQL_MAX_INPUT_LENGTH` (default 8,192). Exceeding an individual field
|
|
339
|
+
returns HTTP 422 with `VALIDATION_FAILED`. The aggregate request-body limit
|
|
340
|
+
remains 512 KiB and returns HTTP 413 with `PAYLOAD_TOO_LARGE`. A syntax error
|
|
341
|
+
within a permitted field keeps the endpoint's normal analysis response, such
|
|
342
|
+
as HTTP 200 `parse_error` from semantic diff.
|
|
343
|
+
|
|
334
344
|
For example, send this JSON body to `POST /api/convert/batch`:
|
|
335
345
|
|
|
336
346
|
```json
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
1
|
"""FastAPI Backend for SQL Dialect Master.
|
|
3
2
|
|
|
4
3
|
Enterprise-grade multi-database SQL conversion API:
|
|
@@ -11,17 +10,17 @@ Enterprise-grade multi-database SQL conversion API:
|
|
|
11
10
|
Exact counts are derived from the canonical data files at runtime —
|
|
12
11
|
see backend.core.metadata — and must not be restated here.
|
|
13
12
|
"""
|
|
14
|
-
import asyncio
|
|
15
13
|
import atexit
|
|
16
14
|
import copy
|
|
17
15
|
import logging
|
|
18
16
|
import time
|
|
17
|
+
from collections.abc import Callable
|
|
19
18
|
from contextlib import asynccontextmanager
|
|
20
19
|
from dataclasses import asdict
|
|
21
|
-
from datetime import datetime
|
|
20
|
+
from datetime import UTC, datetime
|
|
22
21
|
from functools import lru_cache
|
|
23
22
|
from threading import Lock
|
|
24
|
-
from typing import Annotated, Any,
|
|
23
|
+
from typing import Annotated, Any, cast
|
|
25
24
|
|
|
26
25
|
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
|
27
26
|
from fastapi.exception_handlers import request_validation_exception_handler
|
|
@@ -53,11 +52,11 @@ from backend.core.functions_lookup import FunctionEncyclopedia
|
|
|
53
52
|
from backend.core.nl2sql import NL2SQLGenerator, NL2SQLResult
|
|
54
53
|
from backend.core.nl2sql_components.evidence import EvidenceItem, GenerationEvidence
|
|
55
54
|
from backend.core.nl2sql_llm import LLMError, LLMN2SQLClient, validate_llm_sql
|
|
55
|
+
from backend.core.nl2sql_pipeline.orchestrator import SAFE_TABLE_HINT
|
|
56
56
|
from backend.core.nl2sql_schema import (
|
|
57
57
|
MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS,
|
|
58
58
|
SchemaContext,
|
|
59
59
|
)
|
|
60
|
-
from backend.core.nl2sql_pipeline.orchestrator import SAFE_TABLE_HINT
|
|
61
60
|
from backend.core.parser import SUPPORTED_DIALECTS, SQLParser
|
|
62
61
|
from backend.core.semantic_diff import diff_sql_ast
|
|
63
62
|
from backend.core.transpiler import SQLTranspiler
|
|
@@ -67,11 +66,16 @@ from backend.core.type_mapping import TypeMapper
|
|
|
67
66
|
# Keep an INFO fallback for defensive compatibility with custom settings
|
|
68
67
|
# objects, while normal AppSettings values are resolved from SDM_LOG_LEVEL.
|
|
69
68
|
_log_level = getattr(logging, settings.log_level.upper(), logging.INFO)
|
|
70
|
-
logger = setup_logging(level=_log_level, log_file=settings.log_file or
|
|
69
|
+
logger = setup_logging(level=_log_level, log_file=settings.log_file or "")
|
|
71
70
|
api_logger = logging.getLogger(__name__)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _now_iso() -> str:
|
|
74
|
+
"""Return a UTC timestamp while preserving the existing naive ISO shape."""
|
|
75
|
+
return datetime.now(UTC).replace(tzinfo=None).isoformat()
|
|
72
76
|
_worker_pool: BoundedWorkerPool | None = None
|
|
73
77
|
_worker_pool_lock = Lock()
|
|
74
|
-
_worker_pool_exit_hook = None
|
|
78
|
+
_worker_pool_exit_hook: Callable[[], None] | None = None
|
|
75
79
|
|
|
76
80
|
|
|
77
81
|
def _get_worker_pool() -> BoundedWorkerPool:
|
|
@@ -161,7 +165,7 @@ async def _run_cpu_bound(func, *args):
|
|
|
161
165
|
detail=str(exc),
|
|
162
166
|
headers={"Retry-After": "1"},
|
|
163
167
|
) from exc
|
|
164
|
-
except
|
|
168
|
+
except TimeoutError as exc:
|
|
165
169
|
raise HTTPException(
|
|
166
170
|
status_code=504,
|
|
167
171
|
detail="Request processing timed out",
|
|
@@ -261,7 +265,7 @@ from backend.api.middleware import (
|
|
|
261
265
|
SecurityHeadersMiddleware,
|
|
262
266
|
StructuredLoggingMiddleware,
|
|
263
267
|
)
|
|
264
|
-
from backend.core.exceptions import SDMException, UnsupportedDialectError
|
|
268
|
+
from backend.core.exceptions import ErrorCode, SDMException, UnsupportedDialectError
|
|
265
269
|
|
|
266
270
|
# Configure CORS from the centralized Pydantic settings source.
|
|
267
271
|
ALLOWED_ORIGINS = [origin.strip() for origin in settings.allowed_origins.split(",") if origin.strip()]
|
|
@@ -367,9 +371,24 @@ def normalize_dialect(dialect: str, field_name: str = "dialect") -> str:
|
|
|
367
371
|
|
|
368
372
|
# === Request/Response Models with Enhanced Documentation ===
|
|
369
373
|
|
|
374
|
+
# Keep request-field limits explicit in the OpenAPI schema. The parser
|
|
375
|
+
# setting normally falls back to the transpiler limit during settings
|
|
376
|
+
# validation; the fallback also handles custom settings objects safely.
|
|
377
|
+
API_SQL_MAX_LENGTH = settings.transpiler_max_sql_length
|
|
378
|
+
API_PARSER_SQL_MAX_LENGTH = settings.parser_max_sql_length or API_SQL_MAX_LENGTH
|
|
379
|
+
API_NL2SQL_MAX_LENGTH = settings.nl2sql_max_input_length
|
|
380
|
+
BatchSQLStatement = Annotated[
|
|
381
|
+
StrictStr,
|
|
382
|
+
Field(max_length=API_SQL_MAX_LENGTH),
|
|
383
|
+
]
|
|
384
|
+
|
|
370
385
|
class ConvertRequest(BaseModel):
|
|
371
386
|
"""SQL conversion request model."""
|
|
372
|
-
sql: str = Field(
|
|
387
|
+
sql: str = Field(
|
|
388
|
+
...,
|
|
389
|
+
max_length=API_SQL_MAX_LENGTH,
|
|
390
|
+
description="Source SQL statement to convert",
|
|
391
|
+
)
|
|
373
392
|
source_dialect: str = Field(..., description="Source database dialect")
|
|
374
393
|
target_dialect: str = Field(..., description="Target database dialect")
|
|
375
394
|
pretty: bool = Field(
|
|
@@ -390,14 +409,14 @@ class ConvertResponse(BaseModel):
|
|
|
390
409
|
"""SQL conversion response model."""
|
|
391
410
|
success: bool = Field(..., description="Whether conversion was successful")
|
|
392
411
|
source_sql: str = Field(..., description="Original SQL statement")
|
|
393
|
-
target_sql:
|
|
412
|
+
target_sql: str | None = Field(None, description="Converted SQL statement")
|
|
394
413
|
source_dialect: str = Field(..., description="Source dialect")
|
|
395
414
|
target_dialect: str = Field(..., description="Target dialect")
|
|
396
|
-
error:
|
|
397
|
-
error_code:
|
|
398
|
-
compatibility_notes:
|
|
399
|
-
transformations:
|
|
400
|
-
warnings:
|
|
415
|
+
error: str | None = Field(None, description="Error message if conversion failed")
|
|
416
|
+
error_code: str | None = Field(None, description="Stable machine-readable error category")
|
|
417
|
+
compatibility_notes: list[str] = Field(default_factory=list, description="Compatibility notes")
|
|
418
|
+
transformations: list[str] = Field(default_factory=list, description="Applied transformations")
|
|
419
|
+
warnings: list[str] = Field(default_factory=list, description="Conversion warnings")
|
|
401
420
|
target_validation_state: str = Field(
|
|
402
421
|
"target_valid",
|
|
403
422
|
description=(
|
|
@@ -409,13 +428,13 @@ class ConvertResponse(BaseModel):
|
|
|
409
428
|
'"invalid": neither parser accepts the output.'
|
|
410
429
|
),
|
|
411
430
|
)
|
|
412
|
-
timestamp: str = Field(default_factory=lambda:
|
|
431
|
+
timestamp: str = Field(default_factory=lambda: _now_iso(), description="Response timestamp")
|
|
413
432
|
|
|
414
433
|
|
|
415
434
|
class BatchConvertRequest(BaseModel):
|
|
416
435
|
"""Convert an ordered, bounded list using one dialect pair."""
|
|
417
436
|
|
|
418
|
-
statements:
|
|
437
|
+
statements: list[BatchSQLStatement] = Field(
|
|
419
438
|
...,
|
|
420
439
|
min_length=1,
|
|
421
440
|
max_length=settings.max_batch_size,
|
|
@@ -436,11 +455,11 @@ class BatchConvertResponse(BaseModel):
|
|
|
436
455
|
"""Ordered conversion results, including ordinary per-item failures."""
|
|
437
456
|
|
|
438
457
|
success: bool
|
|
439
|
-
results:
|
|
458
|
+
results: list[BatchConvertItemResponse]
|
|
440
459
|
count: int
|
|
441
460
|
succeeded: int
|
|
442
461
|
failed: int
|
|
443
|
-
timestamp: str = Field(default_factory=lambda:
|
|
462
|
+
timestamp: str = Field(default_factory=lambda: _now_iso())
|
|
444
463
|
|
|
445
464
|
|
|
446
465
|
SchemaIdentifier = Annotated[
|
|
@@ -455,13 +474,13 @@ SchemaIdentifier = Annotated[
|
|
|
455
474
|
|
|
456
475
|
class SchemaColumn(BaseModel):
|
|
457
476
|
name: SchemaIdentifier
|
|
458
|
-
type:
|
|
477
|
+
type: str | None = None
|
|
459
478
|
|
|
460
479
|
|
|
461
480
|
class SchemaTable(BaseModel):
|
|
462
481
|
name: SchemaIdentifier
|
|
463
|
-
columns:
|
|
464
|
-
primary_key:
|
|
482
|
+
columns: list[SchemaColumn] = Field(default_factory=list, max_length=200)
|
|
483
|
+
primary_key: list[SchemaIdentifier] | None = Field(None, max_length=8)
|
|
465
484
|
|
|
466
485
|
@model_validator(mode="after")
|
|
467
486
|
def validate_primary_key(self):
|
|
@@ -480,10 +499,10 @@ class SchemaColumnPair(BaseModel):
|
|
|
480
499
|
|
|
481
500
|
class SchemaRelationship(BaseModel):
|
|
482
501
|
from_table: SchemaIdentifier
|
|
483
|
-
from_column:
|
|
502
|
+
from_column: SchemaIdentifier | None = None
|
|
484
503
|
to_table: SchemaIdentifier
|
|
485
|
-
to_column:
|
|
486
|
-
columns:
|
|
504
|
+
to_column: SchemaIdentifier | None = None
|
|
505
|
+
columns: list[SchemaColumnPair] | None = Field(None, max_length=8)
|
|
487
506
|
|
|
488
507
|
@model_validator(mode="after")
|
|
489
508
|
def validate_representation(self):
|
|
@@ -503,8 +522,8 @@ class SchemaRelationship(BaseModel):
|
|
|
503
522
|
|
|
504
523
|
|
|
505
524
|
class SchemaDefinition(BaseModel):
|
|
506
|
-
tables:
|
|
507
|
-
relationships:
|
|
525
|
+
tables: list[SchemaTable] = Field(default_factory=list, max_length=50)
|
|
526
|
+
relationships: list[SchemaRelationship] = Field(default_factory=list, max_length=200)
|
|
508
527
|
|
|
509
528
|
@model_validator(mode="after")
|
|
510
529
|
def validate_total_columns(self):
|
|
@@ -524,11 +543,14 @@ class SchemaDefinition(BaseModel):
|
|
|
524
543
|
or relationship.to_table.casefold() not in table_names
|
|
525
544
|
):
|
|
526
545
|
raise ValueError("invalid schema relationship")
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
546
|
+
if relationship.columns is None:
|
|
547
|
+
if relationship.from_column is None or relationship.to_column is None:
|
|
548
|
+
raise ValueError("invalid schema relationship")
|
|
549
|
+
pairs: list[tuple[str, str]] = [
|
|
550
|
+
(relationship.from_column, relationship.to_column)
|
|
551
|
+
]
|
|
552
|
+
else:
|
|
553
|
+
pairs = [(pair.from_column, pair.to_column) for pair in relationship.columns]
|
|
532
554
|
relationship_pair_count += len(pairs)
|
|
533
555
|
if relationship_pair_count > MAX_SCHEMA_RELATIONSHIP_COLUMN_PAIRS:
|
|
534
556
|
raise ValueError("invalid schema relationship")
|
|
@@ -549,15 +571,19 @@ class SchemaDefinition(BaseModel):
|
|
|
549
571
|
|
|
550
572
|
class NL2SQLRequest(BaseModel):
|
|
551
573
|
"""Natural language to SQL request model."""
|
|
552
|
-
text: str = Field(
|
|
574
|
+
text: str = Field(
|
|
575
|
+
...,
|
|
576
|
+
max_length=API_NL2SQL_MAX_LENGTH,
|
|
577
|
+
description="Natural language query (Chinese or English)",
|
|
578
|
+
)
|
|
553
579
|
dialect: str = Field("hive", description="Target SQL dialect")
|
|
554
|
-
table_hint:
|
|
555
|
-
column_hints:
|
|
580
|
+
table_hint: str | None = Field(None, description="Optional table name hint")
|
|
581
|
+
column_hints: list[str] | None = Field(
|
|
556
582
|
None,
|
|
557
583
|
description="Optional column identifier hints; accepts simple or dotted identifiers",
|
|
558
584
|
)
|
|
559
585
|
# Alias avoids shadowing Pydantic's legacy BaseModel.schema method.
|
|
560
|
-
schema_definition:
|
|
586
|
+
schema_definition: SchemaDefinition | None = Field(
|
|
561
587
|
None, alias="schema", description="Optional database schema for LLM generation and validation",
|
|
562
588
|
)
|
|
563
589
|
|
|
@@ -574,41 +600,53 @@ class NL2SQLResponse(BaseModel):
|
|
|
574
600
|
"""Natural language to SQL response model."""
|
|
575
601
|
success: bool = Field(..., description="Whether generation was successful")
|
|
576
602
|
input_text: str = Field(..., description="Original natural language input")
|
|
577
|
-
sql:
|
|
603
|
+
sql: str | None = Field(None, description="Generated SQL statement")
|
|
578
604
|
dialect: str = Field(..., description="Target dialect")
|
|
579
605
|
explanation: str = Field("", description="Explanation of generated SQL")
|
|
580
606
|
confidence: float = Field(0.0, description="Confidence score (0.0-1.0)")
|
|
581
|
-
suggestions:
|
|
582
|
-
parameter_style:
|
|
607
|
+
suggestions: list[str] = Field(default_factory=list, description="Improvement suggestions")
|
|
608
|
+
parameter_style: str | None = Field(
|
|
583
609
|
None,
|
|
584
610
|
description=(
|
|
585
611
|
"Placeholder style for generated DML: numeric ($1 in PostgreSQL/Redshift, "
|
|
586
612
|
":1 in Oracle), named (@p1 in T-SQL), format (%s in MySQL), or qmark (?)"
|
|
587
613
|
),
|
|
588
614
|
)
|
|
589
|
-
parameters:
|
|
615
|
+
parameters: list[str] = Field(
|
|
590
616
|
default_factory=list,
|
|
591
617
|
description="Ordered placeholders that callers must bind for generated DML",
|
|
592
618
|
)
|
|
593
|
-
evidence:
|
|
619
|
+
evidence: dict[str, Any] | None = Field(
|
|
594
620
|
None, description="Structured evidence supporting the confidence score",
|
|
595
621
|
)
|
|
596
622
|
provider: str = "deterministic"
|
|
597
|
-
model:
|
|
598
|
-
fallback_reason:
|
|
623
|
+
model: str | None = None
|
|
624
|
+
fallback_reason: str | None = None
|
|
599
625
|
schema_used: bool = False
|
|
600
626
|
|
|
601
627
|
class ParseRequest(BaseModel):
|
|
602
628
|
"""SQL parse request model."""
|
|
603
|
-
sql: str = Field(
|
|
629
|
+
sql: str = Field(
|
|
630
|
+
...,
|
|
631
|
+
max_length=API_PARSER_SQL_MAX_LENGTH,
|
|
632
|
+
description="SQL statement to parse",
|
|
633
|
+
)
|
|
604
634
|
dialect: str = Field("hive", description="SQL dialect")
|
|
605
635
|
|
|
606
636
|
|
|
607
637
|
class DiffRequest(BaseModel):
|
|
608
638
|
"""Semantic SQL comparison request."""
|
|
609
639
|
|
|
610
|
-
source_sql: str = Field(
|
|
611
|
-
|
|
640
|
+
source_sql: str = Field(
|
|
641
|
+
...,
|
|
642
|
+
max_length=API_PARSER_SQL_MAX_LENGTH,
|
|
643
|
+
description="Source SQL statement",
|
|
644
|
+
)
|
|
645
|
+
target_sql: str = Field(
|
|
646
|
+
...,
|
|
647
|
+
max_length=API_PARSER_SQL_MAX_LENGTH,
|
|
648
|
+
description="Target SQL statement",
|
|
649
|
+
)
|
|
612
650
|
source_dialect: str = Field(..., description="Source SQL dialect")
|
|
613
651
|
target_dialect: str = Field(..., description="Target SQL dialect")
|
|
614
652
|
|
|
@@ -629,9 +667,9 @@ class TypeMapRequest(BaseModel):
|
|
|
629
667
|
class APIResponse(BaseModel):
|
|
630
668
|
"""Standard API response wrapper."""
|
|
631
669
|
success: bool = Field(..., description="Operation success status")
|
|
632
|
-
data:
|
|
633
|
-
error:
|
|
634
|
-
timestamp: str = Field(default_factory=lambda:
|
|
670
|
+
data: dict[str, Any] | None = Field(None, description="Response data")
|
|
671
|
+
error: str | None = Field(None, description="Error message if failed")
|
|
672
|
+
timestamp: str = Field(default_factory=lambda: _now_iso())
|
|
635
673
|
|
|
636
674
|
# === API Endpoints ===
|
|
637
675
|
|
|
@@ -682,7 +720,7 @@ async def root():
|
|
|
682
720
|
}
|
|
683
721
|
}
|
|
684
722
|
},
|
|
685
|
-
"timestamp":
|
|
723
|
+
"timestamp": _now_iso()
|
|
686
724
|
}
|
|
687
725
|
|
|
688
726
|
@app.get("/api/dialects", tags=["system"])
|
|
@@ -696,7 +734,7 @@ async def get_dialects():
|
|
|
696
734
|
- Grouped by category for easy navigation
|
|
697
735
|
"""
|
|
698
736
|
# Group dialects by category
|
|
699
|
-
by_category = {}
|
|
737
|
+
by_category: dict[str, list[dict[str, str]]] = {}
|
|
700
738
|
for dialect, info in DIALECT_INFO.items():
|
|
701
739
|
cat = info["category"]
|
|
702
740
|
if cat not in by_category:
|
|
@@ -853,7 +891,7 @@ async def parse_sql(request: ParseRequest):
|
|
|
853
891
|
"success": True,
|
|
854
892
|
"dialect": dialect,
|
|
855
893
|
"elements": elements,
|
|
856
|
-
"timestamp":
|
|
894
|
+
"timestamp": _now_iso()
|
|
857
895
|
}
|
|
858
896
|
|
|
859
897
|
|
|
@@ -877,8 +915,8 @@ async def compare_semantic_diff(request: DiffRequest):
|
|
|
877
915
|
|
|
878
916
|
@app.get("/api/functions", tags=["functions"])
|
|
879
917
|
async def list_functions(
|
|
880
|
-
search:
|
|
881
|
-
category:
|
|
918
|
+
search: str | None = Query(None, description="Search term for function name"),
|
|
919
|
+
category: str | None = Query(None, description="Filter by category (string, date, math, etc.)"),
|
|
882
920
|
limit: int = Query(50, ge=1, le=500, description="Maximum number of results")
|
|
883
921
|
):
|
|
884
922
|
"""
|
|
@@ -892,20 +930,19 @@ async def list_functions(
|
|
|
892
930
|
- `/api/functions?limit=100` - Get first 100 functions
|
|
893
931
|
"""
|
|
894
932
|
normalized_category = category.strip().lower() if category is not None else None
|
|
895
|
-
if category is not None:
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
)
|
|
933
|
+
if category is not None and normalized_category not in func_encyclopedia.CATEGORIES:
|
|
934
|
+
raise HTTPException(
|
|
935
|
+
status_code=400,
|
|
936
|
+
detail=(f"Unknown function category: {category}. Available categories: "
|
|
937
|
+
+ ", ".join(func_encyclopedia.CATEGORIES)),
|
|
938
|
+
)
|
|
902
939
|
if search:
|
|
903
940
|
# The search cache applies the category predicate before ranking and
|
|
904
941
|
# the public limit, so category-filtered queries do not scan or copy
|
|
905
942
|
# unrelated function records.
|
|
906
|
-
functions = func_encyclopedia.search(search, limit, normalized_category)
|
|
943
|
+
functions = func_encyclopedia.search(search, limit, cast(str, normalized_category))
|
|
907
944
|
elif category:
|
|
908
|
-
functions = func_encyclopedia.list_by_category(normalized_category)[:limit]
|
|
945
|
+
functions = func_encyclopedia.list_by_category(cast(str, normalized_category))[:limit]
|
|
909
946
|
else:
|
|
910
947
|
functions = func_encyclopedia.functions[:limit]
|
|
911
948
|
|
|
@@ -954,8 +991,8 @@ async def get_function(name: str):
|
|
|
954
991
|
|
|
955
992
|
@app.get("/api/types", tags=["types"])
|
|
956
993
|
async def list_types(
|
|
957
|
-
source:
|
|
958
|
-
target:
|
|
994
|
+
source: str | None = Query(None, description="Filter by source dialect"),
|
|
995
|
+
target: str | None = Query(None, description="Filter by target dialect")
|
|
959
996
|
):
|
|
960
997
|
"""
|
|
961
998
|
Get type mapping matrix.
|
|
@@ -973,7 +1010,7 @@ async def list_types(
|
|
|
973
1010
|
source = normalize_dialect(source, "source dialect")
|
|
974
1011
|
if target is not None:
|
|
975
1012
|
target = normalize_dialect(target, "target dialect")
|
|
976
|
-
matrix = type_mapper.get_matrix(source, target)
|
|
1013
|
+
matrix = type_mapper.get_matrix(cast(str, source), cast(str, target))
|
|
977
1014
|
mappings = [
|
|
978
1015
|
{"type": type_name, **mapping}
|
|
979
1016
|
for type_name, mapping in matrix.items()
|
|
@@ -1022,7 +1059,7 @@ async def map_type(request: TypeMapRequest):
|
|
|
1022
1059
|
return {
|
|
1023
1060
|
"success": result.get("success", False),
|
|
1024
1061
|
**result,
|
|
1025
|
-
"timestamp":
|
|
1062
|
+
"timestamp": _now_iso()
|
|
1026
1063
|
}
|
|
1027
1064
|
|
|
1028
1065
|
@app.post("/api/nl2sql", response_model=NL2SQLResponse, tags=["nl2sql"])
|
|
@@ -1093,7 +1130,11 @@ async def generate_sql(request: NL2SQLRequest):
|
|
|
1093
1130
|
request.text, dialect, request.table_hint, request.column_hints,
|
|
1094
1131
|
**schema_options,
|
|
1095
1132
|
)
|
|
1096
|
-
sql =
|
|
1133
|
+
sql = (
|
|
1134
|
+
validate_llm_sql(generation.sql, dialect)
|
|
1135
|
+
if schema is None
|
|
1136
|
+
else validate_llm_sql(generation.sql, dialect, schema=schema)
|
|
1137
|
+
)
|
|
1097
1138
|
except LLMError as exc:
|
|
1098
1139
|
record_nl2sql_llm_request(exc.reason, time.perf_counter() - started)
|
|
1099
1140
|
if settings.nl2sql_llm_fallback:
|
|
@@ -1171,7 +1212,7 @@ async def health_check():
|
|
|
1171
1212
|
return {
|
|
1172
1213
|
"status": "alive",
|
|
1173
1214
|
"version": API_VERSION,
|
|
1174
|
-
"timestamp":
|
|
1215
|
+
"timestamp": _now_iso()
|
|
1175
1216
|
}
|
|
1176
1217
|
|
|
1177
1218
|
@app.get("/ready", tags=["system"])
|
|
@@ -1221,7 +1262,7 @@ async def get_stats():
|
|
|
1221
1262
|
"details": DIALECT_INFO
|
|
1222
1263
|
}
|
|
1223
1264
|
},
|
|
1224
|
-
"timestamp":
|
|
1265
|
+
"timestamp": _now_iso()
|
|
1225
1266
|
}
|
|
1226
1267
|
|
|
1227
1268
|
# Custom exception handler for better error responses
|
|
@@ -1257,7 +1298,7 @@ async def custom_http_exception_handler(request: Request, exc: HTTPException):
|
|
|
1257
1298
|
"message": exc.detail,
|
|
1258
1299
|
"type": "HTTPException"
|
|
1259
1300
|
},
|
|
1260
|
-
"timestamp":
|
|
1301
|
+
"timestamp": _now_iso()
|
|
1261
1302
|
}
|
|
1262
1303
|
)
|
|
1263
1304
|
|
|
@@ -1278,7 +1319,7 @@ async def sdm_exception_handler(request: Request, exc: SDMException):
|
|
|
1278
1319
|
content={
|
|
1279
1320
|
"success": False,
|
|
1280
1321
|
"error": error,
|
|
1281
|
-
"timestamp":
|
|
1322
|
+
"timestamp": _now_iso()
|
|
1282
1323
|
}
|
|
1283
1324
|
)
|
|
1284
1325
|
|
|
@@ -1294,7 +1335,7 @@ async def unhandled_exception_handler(request: Request, exc: Exception):
|
|
|
1294
1335
|
"code": ErrorCode.INTERNAL_ERROR.value,
|
|
1295
1336
|
"message": "Internal server error",
|
|
1296
1337
|
},
|
|
1297
|
-
"timestamp":
|
|
1338
|
+
"timestamp": _now_iso(),
|
|
1298
1339
|
}
|
|
1299
1340
|
if request_id:
|
|
1300
1341
|
content["request_id"] = request_id
|
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import logging
|
|
5
6
|
import secrets
|
|
6
7
|
from collections.abc import Callable
|
|
8
|
+
from typing import Any, Protocol
|
|
7
9
|
|
|
8
10
|
from fastapi import Request
|
|
9
11
|
from fastapi.responses import PlainTextResponse, Response
|
|
@@ -20,6 +22,8 @@ from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
|
|
|
20
22
|
from backend.core.config import settings
|
|
21
23
|
from backend.core.metadata import PROJECT_VERSION
|
|
22
24
|
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
23
27
|
REGISTRY = CollectorRegistry(auto_describe=True)
|
|
24
28
|
|
|
25
29
|
BUILD_INFO = Gauge("sdm_build_info", "SQL Dialect Master build information", ["version"], registry=REGISTRY)
|
|
@@ -83,9 +87,17 @@ NL2SQL_LLM_FALLBACKS = Counter(
|
|
|
83
87
|
registry=REGISTRY,
|
|
84
88
|
)
|
|
85
89
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
90
|
+
class _StatsProvider(Protocol):
|
|
91
|
+
def get_stats(self) -> dict[str, Any]: ...
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _WorkerStatsProvider(Protocol):
|
|
95
|
+
def stats(self) -> dict[str, int]: ...
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_transpiler_provider: Callable[[], _StatsProvider] | None = None
|
|
99
|
+
_worker_provider: Callable[[], _WorkerStatsProvider] | None = None
|
|
100
|
+
_limiter_provider: Callable[[], _StatsProvider] | None = None
|
|
89
101
|
|
|
90
102
|
|
|
91
103
|
def configure_runtime_metrics(*, transpiler_provider=None, worker_provider=None, limiter_provider=None) -> None:
|
|
@@ -110,7 +122,7 @@ class RuntimeCollector:
|
|
|
110
122
|
yield CounterMetricFamily("sdm_transpile_cache_evictions_total", "Transpiler cache evictions", value=cache.get("evictions", 0))
|
|
111
123
|
yield GaugeMetricFamily("sdm_transpile_cache_size", "Current transpiler cache size", value=cache.get("size", 0))
|
|
112
124
|
except Exception:
|
|
113
|
-
|
|
125
|
+
logger.debug("Failed to collect transpiler runtime metrics", exc_info=True)
|
|
114
126
|
|
|
115
127
|
if _worker_provider is not None:
|
|
116
128
|
try:
|
|
@@ -120,7 +132,7 @@ class RuntimeCollector:
|
|
|
120
132
|
yield CounterMetricFamily("sdm_api_worker_rejections_total", "API worker capacity rejections", value=stats["rejections"])
|
|
121
133
|
yield CounterMetricFamily("sdm_api_request_timeouts_total", "API request timeouts", value=stats["timeouts"])
|
|
122
134
|
except Exception:
|
|
123
|
-
|
|
135
|
+
logger.debug("Failed to collect worker runtime metrics", exc_info=True)
|
|
124
136
|
|
|
125
137
|
if _limiter_provider is not None:
|
|
126
138
|
try:
|
|
@@ -128,7 +140,7 @@ class RuntimeCollector:
|
|
|
128
140
|
if stats.get("backend") == "memory":
|
|
129
141
|
yield GaugeMetricFamily("sdm_rate_limit_active_clients", "Active in-memory rate-limit clients", value=stats.get("active_clients", 0))
|
|
130
142
|
except Exception:
|
|
131
|
-
|
|
143
|
+
logger.debug("Failed to collect rate-limit runtime metrics", exc_info=True)
|
|
132
144
|
|
|
133
145
|
|
|
134
146
|
REGISTRY.register(RuntimeCollector())
|