AI SQL Analyst is structured as a small production-style analytics application rather than a single chatbot script.
- The browser console sends a question,
workspace_id, andX-API-Key. - FastAPI validates the request with Pydantic models.
- The auth layer checks the API key.
- The query service generates SQL using an LLM when configured, otherwise deterministic fallback.
- SQL guardrails enforce read-only access, known-table access, statement limits, and row limits.
- Workspace scoping injects
workspace_idpredicates into the generated SQL. - The database adapter executes against SQLite or PostgreSQL.
- The API returns SQL, summary, rows, chart metadata, warnings, latency, and query ID.
- Query telemetry is written to JSONL for history and metrics.
ai_sql_analyst/main.py: FastAPI routes and app lifecycle.ai_sql_analyst/auth.py: API key auth dependency.ai_sql_analyst/models.py: Request and response contracts.ai_sql_analyst/services/query_service.py: SQL generation, summaries, chart hints, logging, and metrics.ai_sql_analyst/services/sql_guardrails.py: SQL validation and workspace scope injection.ai_sql_analyst/services/database.py: SQLite/PostgreSQL adapter, migrations, seeding, and query execution.ai_sql_analyst/services/evaluation.py: Text-to-SQL evaluation suite.ai_sql_analyst/db/migrations.py: SQLite and PostgreSQL schema definitions.ai_sql_analyst/db/seeds.py: Demo SaaS warehouse data.
The demo warehouse models a lightweight B2B SaaS business:
customersinvoicessupport_tickets
Each table includes workspace_id so generated SQL can be scoped for multi-tenant analytics.
- Only
SELECTstatements are allowed. - Write statements such as
INSERT,UPDATE,DELETE,DROP, andALTERare blocked. - Unknown tables are blocked.
- Multiple SQL statements are blocked.
- Complex nested SELECTs are limited.
- Missing
LIMITclauses are added automatically. - Workspace predicates are injected before
GROUP BY,ORDER BY, andLIMIT.
The project includes the pieces expected in a deployable service:
/healthendpoint for probes.- Docker image definition.
- Docker Compose stack with Postgres.
- Kubernetes Deployment, Service, StatefulSet, ConfigMap, Secret, HPA, probes, and ingress example.
- Terraform example for Kubernetes resources.
- GitHub Actions for unit/API tests, evals, and Postgres integration.