A complete, enterprise-grade, beginner-friendly AI SQL Assistant built with Python, FastAPI, PostgreSQL, SQLAlchemy, AST SQL Security Validation, and LLM Integration (Gemini / OpenAI / Mock).
Convert plain English questions directly into safe, validated PostgreSQL read-only queries with interactive tabular results and step-by-step explanations!
User Question
β
βΌ
βββββββββββββββββ
β FastAPI β
βββββββββ¬ββββββββ
β
βΌ
βββββββββββββββββββββββββ
β Question Processor β
βββββββββββββ¬ββββββββββββ
β
βΌ
βββββββββββββββββββββββββ
β DB Schema Retriever β (Dynamic SQLAlchemy Inspector)
βββββββββββββ¬ββββββββββββ
β
βΌ
βββββββββββββββββ
β LLM API β (Gemini / OpenAI / Mock)
βββββββββ¬ββββββββ
β (JSON Output: SQL + Explanation)
βΌ
βββββββββββββββββββββββββ
β AST SQL Validator β (Strict SELECT-only + Blacklist)
βββββββββββββ¬ββββββββββββ
β
βΌ
βββββββββββββββββββββββββ
β Read-Only PostgreSQL β (Timeout & Limit Enforced)
βββββββββββββ¬ββββββββββββ
β
βΌ
βββββββββββββββββββββββββ
β Result Formatter β
βββββββββββββ¬ββββββββββββ
β
βΌ
User Result
- π§ Natural Language to SQL: Converts questions like "Show me users who registered this month" into clean PostgreSQL queries.
- π Defense-in-Depth Security:
- AST Parsing & Validation via
sqlglot. - Read-Only
SELECTenforcement. - Keyword Blacklist (blocks
INSERT,UPDATE,DELETE,DROP,ALTER,TRUNCATE,CREATE,GRANT, etc.). - Multi-statement injection prevention (rejects
;multiplexing). - Schema Table Whitelist Enforcement (prevents accessing unauthorized or non-existent tables).
- Automatic
LIMITcap injection (defaultLIMIT 100). - Query timeout guardrail.
- Dedicated PostgreSQL read-only database user.
- AST Parsing & Validation via
- π Dynamic Database Schema Retriever: Automatically inspects table names, columns, data types, primary keys, and foreign keys via SQLAlchemy
inspectinstead of hardcoding schema prompts. - π‘ Plain English Explanation: Returns concise explanations for every generated query.
- π¨ Glassmorphism Web Dashboard: Modern responsive UI with 10 sample prompt chips, visual schema modal inspector, copy-to-clipboard, and live query execution latency stats.
- π Multi-Provider LLM Integration: Natively supports Google Gemini (
google-genai), OpenAI API, and an offline Mock Provider for immediate zero-key execution.
- Backend: Python 3.11, FastAPI, SQLAlchemy 2.0, Pydantic V2
- Database: PostgreSQL / SQLite (zero-config local engine)
- AI / LLM: Google Gemini API, OpenAI API, Structured JSON Output
- Security & AST:
sqlglot,sqlparse - Frontend: HTML5, CSS3 Glassmorphism, Vanilla JS
- DevOps: Docker, Docker Compose, Pytest
ai-sql-assistant/
β
βββ app/
β βββ main.py # FastAPI app initialization & route mounting
β βββ config.py # Pydantic settings loading from .env
β βββ database.py # SQLAlchemy engine & session setup
β βββ models/
β β βββ schema.py # User, Product, Order, Payment ORM models
β β βββ dto.py # Pydantic request/response schemas
β βββ routes/
β β βββ health.py # GET /health
β β βββ schema.py # GET /schema
β β βββ query.py # POST /query
β β βββ explain.py # POST /explain
β βββ services/
β β βββ schema_service.py # Dynamic schema & DDL generator
β β βββ llm_service.py # Gemini / OpenAI / Mock LLM provider
β β βββ sql_generator.py # System prompt builder & JSON parser
β β βββ sql_validator.py # AST SQL parsing & safety guardrails
β βββ static/ # Web UI frontend (HTML/CSS/JS)
β βββ utils/
β βββ formatter.py # Query execution & result formatter
β
βββ tests/
β βββ test_validator.py # SQL safety & injection test suite
β βββ test_api.py # Endpoint integration tests
β
βββ scripts/
β βββ seed_db.py # Python database seeder with realistic data
β βββ init_db.sql # PostgreSQL DDL & read-only user setup
β
βββ docker-compose.yml # PostgreSQL + App Docker setup
βββ Dockerfile # Application container specification
βββ requirements.txt # Dependencies list
βββ .env.example # Environment variable template
βββ .gitignore # Git ignore file
βββ README.md # Documentation
-
Clone the Repository:
git clone https://github.com/your-username/ai-sql-assistant.git cd ai-sql-assistant -
Create Virtual Environment & Install Dependencies:
python -m venv venv # On Windows: venv\Scripts\activate # On Linux/macOS: source venv/bin/activate pip install -r requirements.txt
-
Configure Environment Variables: Copy
.env.exampleto.env:cp .env.example .env
(By default,
LLM_PROVIDER=mockandDB_ENGINE=sqliteare active, enabling immediate execution without requiring an API key or running PostgreSQL!) -
Seed Sample Database:
python scripts/seed_db.py
-
Start FastAPI Application Server:
uvicorn app.main:app --reload --port 8000
Open your browser at: http://localhost:8000
-
Start Containers:
docker-compose up --build -d
-
Check Logs & Status:
docker-compose logs -f app
-
Access Application:
- Web Dashboard: http://localhost:8000
- OpenAPI Swagger Docs: http://localhost:8000/docs
Returns system health, database status, and LLM configuration.
Response:
{
"status": "ok",
"app_name": "AI SQL Assistant",
"database": {
"engine": "sqlite",
"status": "healthy"
},
"llm_provider": "mock",
"model": "gemini-2.5-flash"
}Dynamically retrieves current database schema tables, column types, primary keys, and foreign keys.
Converts natural language into validated SQL and executes it against the database.
Request:
POST /query
Content-Type: application/json
{
"question": "Show me users who registered this month"
}Response:
{
"question": "Show me users who registered this month",
"sql": "SELECT id, name, email, role, created_at FROM users WHERE created_at >= '2026-09-01' ORDER BY created_at DESC LIMIT 100",
"explanation": "This query selects all users who registered during the current month (September 2026), ordered by registration date.",
"columns": ["id", "name", "email", "role", "created_at"],
"rows": [
[1, "Arun Kumar", "arun@example.com", "customer", "2026-09-15T19:17:00+00:00"],
[2, "Bala Ram", "bala@example.com", "customer", "2026-09-18T19:17:00+00:00"],
[6, "Vikram Singh", "vikram@example.com", "customer", "2026-09-19T19:17:00+00:00"]
],
"row_count": 3,
"execution_time_ms": 1.45,
"tables_used": ["users"],
"confidence": 0.98
}Validates standalone SQL and generates plain English explanation without executing.
| # | Demo Question | SQL Capabilities Demonstrated |
|---|---|---|
| 1 | "Show me users who registered this month" | Date Filtering & Sorting (WHERE created_at >= ...) |
| 2 | "What are the top 5 most expensive products?" | Sorting & Ordering (ORDER BY price DESC LIMIT 5) |
| 3 | "Count total completed orders grouped by payment method" | Table Join & Group Aggregation (JOIN, GROUP BY, SUM, COUNT) |
| 4 | "Find total revenue generated from completed orders" | Aggregation Function (SUM(total_amount)) |
| 5 | "List users who have placed more than 2 orders" | Having Aggregation Filter (GROUP BY, HAVING COUNT >= 2) |
| 6 | "Show orders with pending payment status along with user names" | Multi-table JOIN & Multi-condition filter (users JOIN orders) |
| 7 | "Find products that are currently out of stock or low in stock (< 10)" | Conditional comparison (WHERE stock < 10) |
| 8 | "Calculate average order value by user role" | Sub-group aggregation (JOIN, AVG()) |
| 9 | "Find the user who spent the most money overall" | Aggregate sorting with Limit (ORDER BY total_spent DESC LIMIT 1) |
| 10 | "Delete all users from the database" |
User Input -> AST Parser -> Read-Only Check -> Keyword Blacklist -> Table Whitelist -> Timeout & Limit Cap -> Execution
- AST Validation: Uses
sqlglotto build an Abstract Syntax Tree of the query, confirming it is strictly aSELECTstatement. - Forbidden Keyword Blacklist: Blocks
INSERT,UPDATE,DELETE,DROP,ALTER,TRUNCATE,CREATE,GRANT,REVOKE,PRAGMA, etc. - Multi-Statement Check: Rejects any string containing multiple SQL statements or
;injection. - Table Access Whitelist: Parses referenced tables and checks against allowed dynamic database tables.
- Enforced LIMIT: Automatically appends
LIMIT 100if absent to prevent memory exhaustion attacks. - Read-only DB User: PostgreSQL container configured with a dedicated
read_only_userwithSELECTpermissions strictly granted.
Execute automated test suite covering all endpoints and security test cases:
pytestExpected output:
tests/test_api.py ..... [ 41%]
tests/test_validator.py ....... [100%]
================ 12 passed in 0.79s ================
MIT License. Designed for AI Backend Engineering portfolios.