A secure, high-performance, asynchronous Text-to-SQL service using FastAPI, SQLAlchemy, sqlglot, and local LLM execution via Ollama (configured with the gemma4 model).
This service takes natural language queries from the user, retrieves the database schema via asynchronous reflection, prompts a local LLM to generate the corresponding SQL, validates the query against mutating operations using AST parsing (blocking non-SELECT commands), executes the safe query, and returns the results.
- Asynchronous Execution: Fully async workflow from API endpoints to database reflection and query execution.
- AST-Based SQL Guardrails: Employs programmatic Abstract Syntax Tree (AST) analysis via
sqlglotto inspect queries. This strictly permits read-onlySELECTstatements and blocks mutating actions (DROP,DELETE,UPDATE,INSERT,CREATE, etc.) at the AST level, avoiding fragile regex. - Local LLM Inference: Interacts asynchronously with local Ollama instances running the
gemma4model. - Database Schema Reflection: Introspects database metadata automatically to provide contextual schema definitions to the LLM.
text-to-sql-guardrails/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI endpoints & pipeline orchestration
│ ├── core/
│ │ ├── __init__.py
│ │ └── config.py # Settings management via Pydantic
│ └── services/
│ ├── __init__.py
│ ├── db_service.py # Async DB schema reflection & query execution
│ ├── guardrail_service.py # AST-based SQL query validation
│ └── sql_generator.py # Ollama integration logic
├── .env.example
├── .gitignore
├── devbox.json
├── requirements.txt
└── README.md
- Framework: FastAPI (Asynchronous ASGI application)
- Database ORM: SQLAlchemy 2.0 (Async extension)
- SQL Parser: sqlglot (AST parsing & inspection)
- LLM Client: Ollama Python SDK
- Database Engine: SQLite (via
aiosqlite)
- Install Ollama and ensure the service is running.
- Download the
gemma4model:ollama pull gemma4
-
Clone the repository:
git clone https://github.com/TimSorrow/Text-to-SQL-with-Guardrails-MVP.git cd Text-to-SQL-with-Guardrails-MVP -
Configure environment variables: Create a
.envfile from the example:cp .env.example .env
Adjust settings as necessary:
DATABASE_URL=sqlite+aiosqlite:///./test.db OLLAMA_HOST=http://localhost:11434 LLM_MODEL=gemma4
-
Install dependencies: Using a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: .\venv\Scripts\activate pip install -r requirements.txt
Start the FastAPI application using Uvicorn:
uvicorn app.main:app --reload --port 8000Access the interactive API documentation (Swagger UI) at:
Executes the Text-to-SQL pipeline.
user_query(query string): The natural language query.
curl -X 'POST' \
'http://localhost:8000/v1/query?user_query=show%20me%20all%20products%20costing%20more%20than%20600' \
-H 'accept: application/json'{
"user_query": "show me all products costing more than 600",
"generated_sql": "SELECT title, price FROM products WHERE price > 600",
"results": [
{
"title": "Laptop",
"price": 999
}
]
}If the LLM returns a mutating SQL query or if a malicious payload is supplied:
{
"detail": "Guardrail validation failed: Security Guardrail Violation: Mutating/Unsafe node type 'Drop' detected in query."
}The validation layer inside guardrail_service.py programmatically parses the generated SQL query into an Abstract Syntax Tree (AST) using sqlglot. It recursively traverses all nodes in the AST and raises an error if it detects any statement of the following types:
DROPDELETEALTERUPDATEINSERTCREATEMERGECOMMAND/ Transaction commands (COMMIT,ROLLBACK, etc.)
This mechanism prevents SQL injection and unintended data mutations, guaranteeing that only read-only queries are executed against the database.