An enterprise-grade Text-to-SQL engine that translates natural language business queries into secure, syntactically verified, and performant SQL queries targeting PostgreSQL 16 and Oracle Database 23c.
Built by a Senior Database Engineer (5+ years in Oracle PL/SQL & PostgreSQL) to bridge core relational database rigor with modern AI Engineering (Schema-Pruned RAG, Local LLMs, and AST Security Guardrails).
| Pillar | Enterprise Implementation |
|---|---|
| 🛡️ Zero-Regex AST Firewall | Strict Abstract Syntax Tree traversal with sqlglot. Validates root SELECT/UNION, schema whitelists, CTEs, function denylists, and clamps row limits. 245+ adversarial attack payloads blocked. |
| 🗄️ Dual Enterprise Dialects | Native execution on both PostgreSQL 16 (with pgvector schema embeddings) and Oracle Database 23c Free (package-qualified calls, hints, FETCH FIRST, and read-only sandboxing). |
| ⚡ Resilient Fail-Fast | Reduced unreachable database latency from 138.5s (HTTP 500) down to 4.0s (HTTP 503); out-of-domain queries caught in 16ms (HTTP 422) before reaching LLMs. |
| 🔒 100% On-Premise Privacy | Local GPU inference via Ollama (sqlcoder / qwen2.5-coder). Sensitive corporate schema definitions and data never leave your infrastructure. |
flowchart TD
User(["👤 Business User / Client App<br/><i>'Which customers have overdue invoices?'</i>"]) --> API["⚡ FastAPI Endpoint<br/><code>POST /query</code>"]
subgraph Layer1 ["1. Semantic Schema-Pruned RAG (pgvector)"]
API --> Embed["Generate Query Embedding<br/><i>paraphrase-multilingual-MiniLM</i>"]
Embed --> CosineGate{"Cosine Distance Gate<br/><code>MAX_SCHEMA_DISTANCE=0.7</code>"}
CosineGate -- "Off-domain query (>0.7)" --> RejDomain["❌ HTTP 422 Unprocessable<br/><i>Rejects without LLM call in 16ms</i>"]
CosineGate -- "In-domain query" --> RetDDL["Retrieve Relevant DDLs<br/><i>Tables, Columns & Business Rules</i>"]
end
subgraph Layer2 ["2. Local LLM Generation (GPU CUDA)"]
RetDDL --> Prompt["Contextual Schema Prompt<br/><i>Dialect rules + Pruned DDLs + Question</i>"]
Prompt --> Ollama["Local Ollama Engine<br/><code>sqlcoder</code> | <code>qwen2.5-coder</code>"]
Ollama --> RawSQL["Generated SQL Candidate"]
end
subgraph Layer3 ["3. Enterprise AST Firewall (sqlglot)"]
RawSQL --> ASTParse["Parse Abstract Syntax Tree"]
ASTParse --> ASTCheck{"Semantic AST Validation<br/>• Root exp.Select / Union only<br/>• Table Whitelist (ALLOWED_SCHEMA)<br/>• Function Denylist (pg_sleep, utl_http)<br/>• Row Clamping (LIMIT 100)"}
ASTCheck -- "Malicious / Non-SELECT" --> RejSec["❌ HTTP 400 Bad Request<br/><code>UnsafeQueryError</code>"]
end
subgraph Layer4 ["4. Dual Execution Sandbox"]
ASTCheck -- "Sanitized SQL" --> Router{"TARGET_DIALECT<br/>Router"}
Router -- "postgres" --> PG[("🐘 PostgreSQL 16<br/>Read-only Transaction<br/><code>statement_timeout = 5000</code>")]
Router -- "oracle" --> ORA[("🔴 Oracle 23c Free<br/>Read-only Session<br/><code>call_timeout = 5s</code>")]
end
PG --> Response["✅ HTTP 200 OK<br/><code>{sql, rows, row_count}</code>"]
ORA --> Response
Response --> User
# 1. Safe business query translation & execution
$ curl -s -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "How many customers have overdue invoices?"}' | jq
{
"sql": "SELECT COUNT(DISTINCT customer_id) FROM invoices WHERE status = 'overdue' LIMIT 100;",
"rows": [{"count": 4}],
"row_count": 1
}
# 2. Adversarial attack attempt blocked by the AST Firewall
$ curl -s -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "Show customers; DROP TABLE customers; --"}' | jq
{
"detail": "UnsafeQueryError: Multiple statements or non-SELECT expressions are strictly prohibited by the AST firewall."
}sequenceDiagram
autonumber
actor Client as User / Client App
participant API as FastAPI (/query)
participant RAG as Retrieval Engine (pgvector)
participant LLM as Local LLM (Ollama / CUDA)
participant Guard as Safety Engine (sqlglot AST)
participant DB as PostgreSQL / Oracle Sandbox
Client->>API: POST /query {"question": "How many customers have overdue invoices?"}
API->>RAG: Embed query & search relevant schema
RAG-->>API: Returns relevant table DDLs & semantic column descriptions
API->>LLM: Augmented Prompt (Contextual Schema + Question + Dialect rules)
LLM-->>API: Generated SQL query candidate
API->>Guard: Parse Abstract Syntax Tree (AST) validation
alt Malicious or Non-SELECT query
Guard-->>API: Raises UnsafeQueryError (blocked)
API-->>Client: 400 Bad Request (Detailed safety rejection)
else Safe query
Guard-->>API: Sanitized SQL with enforced LIMIT and timeouts
API->>DB: Execute query in isolated read-only transaction
DB-->>API: Query result rows
API-->>Client: 200 OK {sql, rows, row_count}
end
One of the greatest challenges in deploying generative AI in enterprise environments is connecting LLMs to structured corporate databases without risking:
- Schema Hallucinations: Asking the LLM to write queries against a 50+ table schema often causes it to invent non-existent column names or faulty join conditions.
- Security Vulnerabilities: Naive regex filters fail against obfuscated SQL injections, multi-statement payloads (
SELECT ...; DROP TABLE), or comments disguised as DDL. - Runaway Queries: Slow full-table scans that exhaust production memory and database connection pools.
This project delivers a production-pattern solution:
- Schema-Pruned RAG: Embeds database entities (tables, columns, business definitions) into
pgvector. Only the top relevant schema slice is dynamically injected into the prompt. - Zero-Regex AST Validation (
sqlglot): Inspects the query's Abstract Syntax Tree to ensure by design that only a singleSELECTis executed, backed by 245 adversarial tests. - Privacy-First Local Inference: Fully runnable via Ollama (GPU CUDA-accelerated), ensuring sensitive company schema details never leave on-premise infrastructure.
Rather than fragile regex pattern matching, app/core/safety.py uses sqlglot to parse and validate incoming SQL against an enterprise Semantic AST Firewall:
- Strict Single Statement Check: Rejects multiple semicolons and stacked statements (e.g.,
SELECT 1; DROP TABLE users;). - Root Expression Verification: Confirms the root node is strictly
exp.Selectorexp.Union. AnyINSERT,UPDATE,DELETE,DROP,ALTER, orTRUNCATEoperations trigger an immediateNonSelectQueryError. - Table Whitelist Enforcement: Restricts execution strictly to authorized business domain tables (
customers,invoices,payments,collection_actions). Rejects attempts to access system catalogs (pg_shadow,pg_authid,information_schema) or internal RAG metadata (schema_embeddings) withTableNotAllowedError. The schema is validated too: unqualified table names pass, schema-qualified names (schema.table) pass only when the schema equalsALLOWED_SCHEMA(defaultpublic, case-insensitive), and three-part names (catalog.schema.table) are always rejected. - CTE Resolution: Accurately discounts Common Table Expression names (
WITH ... AS (...)) from physical table checks to allow advanced analytics without false positives. - Dangerous Function Blacklist: Blocks time-based blind SQLi (
pg_sleep), server-side exfiltration (pg_read_file,query_to_xml), and lateral movement (dblink) withDangerousFunctionError. - Row-Count Clamping: Inspects the AST for existing
LIMITclauses:- If omitted, injects a default
LIMIT 100. - If present but exceeds safety thresholds, clamps it to the maximum allowable limit.
- Safely handles non-integer or malformed limits (
LIMIT ALL, expressions) by falling back to safe limits.
- If omitted, injects a default
- Engine-Level Timeouts: Automatically sets
statement_timeout = 5000(5s) per session to eliminate unindexed full-table runaway queries. - Oracle dialect (
TARGET_DIALECT=oracle): the firewall applies Oracle-specific rules (package-qualified calls, sequences, information/XML functions, db links, table functions, hints,FETCH PERCENT/WITH TIES, bind variables) and safely executes validated queries against the target Oracle database in read-only transactions with enforcedcall_timeout. See docs/oracle-firewall.md.
Unit, adversarial, dialect compatibility, and caching tests ensure robust security and deterministic behavior before any query reaches the execution engine:
# Run tests inside the virtual environment
pytest -q================ 1085 passed, 89 skipped, 2 warnings in 18.95s ================
- 1,085 passing automated unit & functional tests in CI on every push and PR.
- 245 adversarial attack payloads specifically targeting the
sqlglotAST guardrails. - Dialect parity test suite verifying PostgreSQL vs Oracle semantic AST consistency.
- Zero external dependencies required for test execution (offline mock architecture).
Requirements: Docker and Ollama running on the host, with the sqlcoder model available:
ollama pull sqlcoder
docker compose upThe first startup downloads the embedding model. Once the API is ready, try a query:
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "Which customers have overdue invoices?"}'The first question after startup can take about 40 seconds while Ollama loads the model (measured on an RTX 4060); later questions usually respond in seconds. If the LLM is unavailable, the API returns 503.
Ollama from Docker: On Docker Desktop for Windows and macOS,
host.docker.internalreaches Ollama on the host. On native Linux, start host Ollama listening on all interfaces withOLLAMA_HOST=0.0.0.0 ollama serve, or use the optional Compose profile:docker compose --profile ollama up -danddocker compose exec ollama ollama pull sqlcoder; with that profile, setOLLAMA_HOST=http://ollama:11434. Docker Compose readsOLLAMA_HOSTfrom the environment.
To run the application with an Oracle Free 23.26.3 database as the target execution engine (while keeping PostgreSQL for RAG embeddings):
Resource requirement & License: The Oracle Free container image (
gvenzl/oracle-free:23.26.3-slim-faststart) requires approximately 4 GB of RAM and ~6.5 GB of disk space. Note that downloading the Oracle image is subject to Oracle's Free Use Terms and Conditions.
Start the stack with the Oracle Compose override:
docker compose -f docker-compose.yml -f docker-compose.oracle.yml up -dThis starts:
- PostgreSQL + pgvector for schema embeddings.
- Oracle Free 23.26.3 configured with the
SALESschema (owner) and an unprivilegedAPP_ROread-only user. - The schema indexer targeting Oracle schema documents.
- The FastAPI application with
TARGET_DIALECT=oracleandTARGET_DATABASE_URLpointing to Oracle.
git clone https://github.com/andresaragon/text-to-sql-rag.git
cd text-to-sql-rag
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txtdocker run --name pg-vector \
-e POSTGRES_PASSWORD=postgres \
-p 5432:5432 \
-d pgvector/pgvector:pg16psql -h localhost -U postgres -f db/schema.sql
psql -h localhost -U postgres -f db/seed.sqlpython -m scripts.index_schemauvicorn app.main:app --reload --port 8000The application is configured using environment variables (or a .env file):
| Variable | Default | Description |
|---|---|---|
DATABASE_URL |
postgresql://postgres:postgres@localhost:5432/postgres |
PostgreSQL connection string. |
DB_POOL_SIZE |
5 |
SQLAlchemy connection pool size. |
DB_MAX_OVERFLOW |
10 |
Maximum overflow connections allowed beyond pool size. |
DB_POOL_TIMEOUT_SECONDS |
10 |
Timeout in seconds to wait when retrieving a connection from the pool. |
DB_CONNECT_TIMEOUT_SECONDS |
3 |
Connection timeout in seconds passed to psycopg2 driver to fail fast if database is unreachable. |
MAX_QUESTION_CHARS |
500 |
Maximum character length allowed for user questions after whitespace normalization (rejects with 422 if exceeded). |
MAX_SCHEMA_DISTANCE |
0.7 |
Maximum cosine distance threshold for schema retrieval; off-domain queries exceeding this are rejected early with 422. |
WARMUP_ON_STARTUP |
True |
Pre-load the embedding model during application startup to avoid first-request latency ("false" or "0" to disable). |
OLLAMA_HOST |
http://localhost:11434 |
Ollama service endpoint URL. |
OLLAMA_MODEL |
sqlcoder |
LLM model name used for SQL generation. |
EMBEDDING_MODEL |
sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 |
SentenceTransformer model used for embeddings. |
MAX_ROWS_RETURNED |
100 |
Maximum rows allowed in SELECT queries (clamped by AST safety guardrails). |
ALLOWED_SCHEMA |
public |
Only schema allowed for schema-qualified table names (schema.table); unqualified names are not affected. Case-insensitive. |
TARGET_DIALECT |
postgres |
SQL dialect used by the firewall and execution engine: postgres or oracle (case-insensitive). When set to oracle, queries are validated with Oracle-specific AST rules and executed in read-only sessions with call_timeout against TARGET_DATABASE_URL. See docs/oracle-firewall.md. |
QUERY_TIMEOUT_SECONDS |
5 |
Query execution timeout in seconds (enforced via statement_timeout on PostgreSQL and call_timeout on Oracle). |
SCHEMA_CHECK_INTERVAL_SECONDS |
0 |
Opt-in. 0 = off. When > 0, /query checks at most once per interval whether schema_embeddings was reindexed (count(*) + max(id)) and, if so, clears the retrieval cache, so answers do not go stale until Uvicorn restarts. Never raises: if the check fails it does nothing. Each worker checks on its own. |
FUNCTION_POLICY |
denylist |
denylist (default, unchanged) or allowlist. With allowlist the firewall only accepts the functions in ALLOWED_FUNCTIONS (app/core/safety.py) plus ALLOWED_FUNCTIONS_EXTRA; the denylist still runs first. Any other value rejects every query (fail-closed). |
ALLOWED_FUNCTIONS_EXTRA |
(empty) | Comma-separated function names added to the allowlist when FUNCTION_POLICY=allowlist (e.g. Oracle-specific ones). It can never reopen a function the denylist blocks. |
Translates a natural language question into safe SQL and executes it:
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"question": "Which customers have overdue invoices older than 30 days?"}'Response (200 OK):
{
"sql": "SELECT COUNT(DISTINCT customer_id) FROM invoices WHERE due_date < NOW() - INTERVAL '30 days' AND status = 'overdue' LIMIT 100;",
"rows": [
{
"count": 4
}
],
"row_count": 1
}- Automated suite: 1,085 tests that need no external services (no Postgres, no Ollama). They run in CI on pushes to
mainand on every pull request. - Adversarial firewall suite: 245 adversarial tests against the
sqlglotAST guardrails. - Benchmark with real infrastructure: first run against real Postgres + pgvector and Ollama (
sqlcoder, RTX 4060). Full report:docs/benchmarks/2026-10-15.md. - A/B benchmark, Postgres vs Oracle vs transpiled SQL: 30 questions, two local models, identical data in both databases; the model matters far more than the dialect, and transpiling costs date questions. Report:
docs/benchmarks/2026-10-23-ab.md.
| Metric | Before | After |
|---|---|---|
| Unreachable database (IP that does not respond) | HTTP 500 in 138.5 s | HTTP 503 in 4.0 s |
| Out-of-domain questions (3) | 2 × 200 with invented SQL, 1 × 400; p50 1000 ms | 3 × 422 without calling the LLM; p50 16 ms |
| Valid in-domain question, cold (p50, 9 runs) | 1188 ms | 1122 ms — unchanged; about 98 % of the time is the LLM |
Measured on a laptop with an RTX 4060 (8 GB VRAM) under WSL2, not on a server. These numbers come from that single run; the report has the full environment and the rest of the results.
Full technical deliberations and trade-offs are documented in NOTES.md. When transitioning this architecture to 100+ table schemas:
- Foreign Key Graph Retrieval (Structural + Semantic Hybrid):
Pure semantic similarity fails when queries require multi-hop joins across tables with unrelated names. A production RAG system must query
information_schema.key_column_usageto traverse the foreign-key graph and inject the explicit join path (invoices.customer_id → customers.customer_id) into the prompt. EXPLAIN ANALYZECost Validation: LLMs generate plausible text, not optimal execution plans. Integrating an automatedEXPLAIN (FORMAT JSON)pre-flight step allows rejecting queries whose estimated cost exceeds a strict budget before actual execution.- FK Index Enforcement: PostgreSQL does not automatically index foreign keys. Automated schema audits ensure indexes exist on joined columns to prevent table locks and slow joins under LLM load.
Santiago Andrés Aragón Guzmán
Backend Developer (Oracle PL/SQL) transitioning to AI Engineering.
- 💼 LinkedIn: linkedin.com/in/santiagoaragonguzman
- 🐙 GitHub: @andresaragon
- 📧 Email: [email protected]