AI Application Engineer: Building Safe, Read-Only Text-to-SQL (NL2SQL) & Semantic Layer Business Intelligence Copilots
Executive and operations teams want to ask natural-language analytics questions—such as "Compare net revenue retention by cohort across APAC enterprise tenants in Q3"—and receive accurate SQL queries and interactive charts in seconds. However, letting an LLM generate raw SQL directly against a production database without a semantic layer or AST validation leads to hallucinated table joins, cross-tenant data leaks, and runaway full-table scans. As an AI Application Engineer and GCP Engineer, I build read-only, AST-validated Text-to-SQL (NL2SQL) copilots backed by PostgreSQL 16 and Google Cloud BigQuery.
1. AST SQL Validation (`sqlglot`), Read-Only Roles & Tenant Predicate Injection
Never execute LLM-generated SQL strings directly on a read-write database connection. First, we parse the candidate query into an Abstract Syntax Tree (AST) using sqlglot, reject any statement that is not a pure SELECT, verify that only allowlisted semantic views are referenced, and execute inside a read-only PostgreSQL transaction with a strict statement_timeout = '3000ms' and Row-Level Security (RLS) tenant context:
import sqlglot
from sqlglot import exp
ALLOWED_SEMANTIC_VIEWS = {"v_tenant_monthly_revenue", "v_cohort_retention", "v_order_summary"}
def validate_and_rewrite_nl2sql(raw_sql: str, max_rows: int = 500) -> str:
parsed = sqlglot.parse_one(raw_sql, read="postgres")
if not isinstance(parsed, exp.Select):
raise ValueError("Only read-only SELECT statements are permitted")
for table in parsed.find_all(exp.Table):
if table.name.lower() not in ALLOWED_SEMANTIC_VIEWS:
raise ValueError(f"Unauthorized table or view referenced: {table.name}")
# Enforce hard LIMIT ceiling to prevent memory exhaustion
parsed = parsed.limit(max_rows)
return parsed.sql(dialect="postgres")
2. Few-Shot Golden SQL Retrieval & Self-Healing Execution Loops
Instead of dumping 300 raw DDL table definitions into the prompt, we index curated Semantic Layer Views and verified "Golden Question-to-SQL" pairs in pgvector. When BigQuery or PostgreSQL returns a dry-run planner error, our Google ADK & Vertex AI agent loop feeds the exact database compiler diagnostic back for a single self-correction pass while enforcing PostgreSQL Row-Level Security (RLS) tenant isolation.
Need an AI Application Engineer to deploy a secure Text-to-SQL analytics copilot on PostgreSQL or BigQuery? Book a 1-Day Engineering Sprint.