Ask Your Database: Query PostgreSQL Using Plain English
Building a multi-project Natural Language → SQL backend with FastAPI
Ask Your Database is a backend system that allows users to query their own PostgreSQL databases using plain English instead of SQL. The system converts natural language into constrained SQL, executes it safely, and returns structured JSON results.
- “Show me all profiles created last 7 days”
- “Total expenses this month”
- “Count events in last 30 days”
Why I Built This
Most analytics dashboards assume fixed schemas and predefined SQL queries. That assumption breaks down when the backend must operate on unknown databases provided by users.
My goal was not to build a “smart” system, but a backend that is predictable, safe, and debuggable even when user input is ambiguous.
High-Level Architecture
Understanding the Core Risk
Natural-language-to-SQL systems fail in dangerous ways when they blindly trust user intent. Without constraints, a single query can trigger full-table scans, invalid SQL, or unintended data access.
How the Backend Learns the Database Shape
Before generating SQL, the backend inspects the connected database and builds an in-memory representation of tables and columns. This ensures that every query is grounded in the real schema.
insp = inspect(engine)
for table in insp.get_table_names():
cols = insp.get_columns(table)
This eliminates guesswork and ensures the system only queries tables and fields that actually exist.
Isolating Projects to Prevent Data Leaks
In multi-project systems, sharing database connections can silently route queries to the wrong database. This is one of the most dangerous failure modes in backend systems.
active_engines[project] = create_engine(url)
Each project gets its own database engine and schema state, enforcing isolation at the infrastructure level.
Why SQL Generation Is Intentionally Boring
The system avoids complex or “clever” SQL. Queries are deterministic, schema-constrained, and always limited by default.
SELECT * FROM profiles
WHERE created_at >= NOW() - INTERVAL '7 days'
LIMIT 100;
This trade-off favors safety and predictability over intelligence.
How a Query Becomes Safe SQL
Each step validates intent against schema, project isolation, and deterministic rules before executing any SQL.
Lessons Learned
- Schema awareness is mandatory for NL → SQL systems
- Isolation must be enforced in code, not conventions
- Predictable systems outperform “smart” but unsafe ones
Screenshots
A few snapshots showing the system in action.