< Back to blog
Tutorial Velona Team ·26 July 2026 ·4 min read

Build a Natural Language-to-SQL Generator for SaaS Dashboards

Business intelligence (BI) teams and product managers frequently rely on data engineers to run custom database queries. Questions like "What was our monthly recurring revenue (MRR) by state last quarter?" or "Which 10 customers have the highest API token usage this week?" often require writing SQL queries manually.

In this guide, we will build an automated Text-to-SQL Query Generator using Python, FastAPI, and Velona's Unified AI Gateway. Non-technical team members can type questions in plain English or Hindi, and the AI translates them into valid, read-only SQL queries executed safely against PostgreSQL or MySQL databases.

Text-to-SQL Architecture & Security Guardrails

When translating natural language to SQL, safety and schema awareness are critical:

  1. Schema Injection: Provide the database table structures, column names, and data types in the system prompt so the AI understands table relationships.
  2. Read-Only Access: Execute generated queries using a restricted database user role that permits only SELECT statements—preventing accidental DELETE, DROP, or UPDATE commands.
  3. Query Sanitization: Validate the SQL output before execution to block multi-statement injection attacks.

Step 1: Set Up Your Velona Account & API Key

To access high-reasoning coding models on Velona:

  1. Register on the Velona Sign-Up Page[cite: 1].
  2. Navigate to your Prepaid Wallet Dashboard and top up ₹10 or more using GPay, PhonePe, or RuPay[cite: 1]. Velona charges in native Indian Rupees with zero foreign transaction markups[cite: 1].
  3. Go to API Key Management and create a new key tagged for bi-dashboard-sql[cite: 1].
  4. Set an optional monthly spending budget in paise on the key to prevent unexpected API costs[cite: 1].

Step 2: Build the FastAPI Text-to-SQL Endpoint

Create a Python file named text_to_sql.py. We will use Velona's standard REST API endpoint (/gateway/v1/inference/run) to convert plain text into structured SQL queries[cite: 1].

import re
import requests
from fastapi import FastAPI, HTTPException, BaseModel

app = FastAPI()

VELONA_API_KEY = "YOUR_VELONA_API_KEY"
VELONA_URL = "https://velona.in/gateway/v1/inference/run"

headers = {
    "Authorization": f"Bearer {VELONA_API_KEY}",
    "Content-Type": "application/json"
}

# Define Database Schema Context
DB_SCHEMA = """
Database: PostgreSQL
Table: users (id INT, email VARCHAR, created_at TIMESTAMP, plan_type VARCHAR)
Table: subscriptions (id INT, user_id INT, amount_paise INT, status VARCHAR, created_at TIMESTAMP)
Table: api_usage (id INT, user_id INT, model VARCHAR, prompt_tokens INT, completion_tokens INT, created_at TIMESTAMP)
"""

SYSTEM_PROMPT = f"""You are a strict PostgreSQL expert data analyst.
Translate the user's question into a valid SQL query based ONLY on the schema provided below.

Schema:
{DB_SCHEMA}

Rules:
1. Return ONLY the raw SQL query. Do not wrap it in markdown block quotes or explanations.
2. Only write SELECT queries. Never write INSERT, UPDATE, DELETE, or DROP.
3. Use proper PostgreSQL date functions where applicable.
"""

class QueryRequest(BaseModel):
    question: str

@app.post("/generate-sql")
async def generate_sql(req: QueryRequest):
    payload = {
        "model": "deepseek/deepseek-coder",
        "turns": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": req.question}
        ]
    }

    response = requests.post(VELONA_URL, json=payload, headers=headers)
    result = response.json()
    sql_query = result["choices"][0]["message"]["content"].strip()

    # Security Guardrail Check
    clean_sql = re.sub(r'```sql|```', '', sql_query).strip()
    if not clean_sql.upper().startswith("SELECT"):
        raise HTTPException(status_code=400, detail="Only SELECT queries are allowed for safety.")

    return {
        "user_question": req.question,
        "generated_sql": clean_sql
    }

Step 3: Choosing the Right Model for SQL Generation

Generating accurate SQL syntax requires strong logical reasoning and schema comprehension:

You can check real-time per-token prices in INR on the Velona Pricing Page[cite: 1] and monitor daily usage trends on the Usage Analytics Dashboard[cite: 1].

Developer Utilities & Testing Environment

When formatting complex database schemas or escaping string parameters for SQL queries, utilize Velona's 49 Life Time Free Developer Tools[cite: 1, 1]. Utilities like the SQL Beautifier, JSON Formatter, and Regex Evaluator operate completely free without using wallet credits[cite: 1].

To test different SQL prompt structures before deploying your backend, run queries in the Free Public Chat Playground[cite: 1] or compare model SQL accuracy side-by-side in the Model Evaluator[cite: 1]. You can also benchmark reasoning capabilities on the AI Benchmark Leaderboard[cite: 1].

Conclusion

Building a Text-to-SQL generator democratizes data access across your organization while saving engineering teams hours of manual reporting. With Velona's unified REST API gateway, Indian developers can build secure internal data tools funded easily via local UPI top-ups[cite: 1].

Ready to build your AI database tools? Sign up for a free Velona account and start generating queries today[cite: 1]!