QueryMind is a production-style Natural Language to SQL engine that transforms human language into secure, executable SQL queries using a locally hosted Large Language Model (Mistral via Ollama). Unlike basic NL-to-SQL demos, QueryMind is designed as a complete system with real-world architectural considerations including:
- Dynamic multi-database discovery
- Schema-grounded prompt engineering
- Secure query execution layer
- Self-healing SQL correction loop
- Modular backend design
- Real-time visualization
The application directly connects to the MySQL server and automatically detects all available databases. Any database present in MySQL Workbench will appear in the UI without hardcoding.
Users can:
โข Select any database
โข Explore available tables
โข View complete schema (columns + data types)
โข Ask questions in plain English
โข Generate SQL queries
โข Execute them safely
โข Automatically correct query errors
โข Visualize results instantly
This system simulates how AI-powered analytics tools would function in a real enterprise environment.
QueryMind is not just a UI wrapper around an LLM. It implements:
The selected database schema is injected into the LLM prompt before SQL generation. This:
- Reduces hallucinations
- Improves JOIN accuracy
- Enables multi-table reasoning
- Increases execution success rate
Before executing generated SQL:
- Only SELECT statements are allowed
- Destructive operations (DELETE, UPDATE, DROP) are blocked
- Query is cleaned and validated
This ensures database safety.
If a query fails:
- The database error message is captured
- Error + original query + schema are sent back to the LLM
- A corrected query is generated
- The system retries execution automatically
This creates a resilient AI-assisted query engine.
QueryMind follows a structured, multi-layer AI execution pipeline designed for safety, resilience, and schema grounding.
| Stage | Layer | Component | Responsibility | Key Output |
|---|---|---|---|---|
| 1 | User Interface Layer | Streamlit UI (app.py) |
Captures user natural language input and selected database | User query + selected DB |
| 2 | Metadata Layer | db.py |
Dynamically fetches databases, tables, and schema from MySQL | Structured schema metadata |
| 3 | Context Engineering Layer | prompt_builder.py |
Injects schema + user question into structured LLM prompt | Schema-grounded prompt |
| 4 | AI Reasoning Layer | llm.py (Ollama + Mistral) |
Converts natural language into SQL query | Generated SQL |
| 5 | Security Validation Layer | executor.py (Pre-check) |
Validates SQL (SELECT-only guard, sanitization) | Safe executable SQL |
| 6 | Execution Layer | MySQL Connector | Executes validated SQL against selected database | Query result / error |
| 7 | Resilience Layer | Auto-Correction Loop | If error occurs โ feeds error + schema back to LLM | Corrected SQL |
| 8 | Data Processing Layer | Pandas | Formats results into structured dataframe | Clean dataset |
| 9 | Visualization Layer | Streamlit Charts | Auto-detects numeric columns & generates visualization | Interactive chart |
| 10 | Presentation Layer | UI Rendering | Displays SQL, explanation (optional), result table, chart | Final user output |
When execution fails, QueryMind activates a secondary correction loop:
| Step | Action | Description |
|---|---|---|
| 1 | Capture Error | MySQL execution error message is extracted |
| 2 | Context Packaging | Error + Original SQL + Schema bundled |
| 3 | Regeneration | Mistral generates corrected SQL |
| 4 | Re-validation | SELECT-only guard re-applied |
| 5 | Re-execution | Corrected query executed |
| 6 | Final Response | Success result or final error displayed |
This creates a self-healing AI SQL engine.
QueryMind follows a multi-layer architecture:
| Architecture Layer | Purpose |
|---|---|
| Presentation Layer | User interaction & UI |
| Metadata Layer | Schema discovery & grounding |
| AI Reasoning Layer | Natural language โ SQL conversion |
| Security Layer | Query validation & safety |
| Execution Layer | Database interaction |
| Resilience Layer | Error correction loop |
| Analytics Layer | Result processing & visualization |
| Control | Implementation |
|---|---|
| Query Restriction | Only SELECT statements allowed |
| SQL Sanitization | Markdown & formatting cleaned before execution |
| Schema Grounding | Reduces hallucinated table references |
| Error Feedback Loop | Controlled retry mechanism |
| Local LLM Execution | No external API exposure |
| Input | Transformation | Output |
|---|---|---|
| Natural Language | Schema-Grounded Prompt | SQL Query |
| SQL Query | Validation & Execution | Data Result |
| Data Result | Pandas Formatting | Structured Table |
| Structured Table | Auto Visualization | Chart Output |
โ Modular separation of concerns
โ AI reasoning isolated from execution layer
โ Built-in safety constraints
โ Automatic retry resilience
โ Dynamic database discovery
โ Local LLM inference (privacy-safe)
QueryMind is designed as a layered AI system rather than a simple LLM wrapper.
It combines:
- Prompt Engineering
- Secure Systems Design
- Database Metadata Abstraction
- Error-Driven Regeneration
- Real-Time Data Visualization
into a cohesive pipeline.
Model Used: Mistral
Runtime: Ollama
Deployment: Local
Why Local LLM?
- No API cost
- Full data privacy
- Fast inference
- Offline capability
The project follows a clean modular design:
โข app.py โ UI & orchestration
โข db.py โ Database metadata retrieval
โข executor.py โ Secure query execution layer
โข prompt_builder.py โ Schema-aware prompt generation
โข llm.py โ Ollama (Mistral) integration
โข config.py โ Database configuration
This separation improves maintainability and scalability.
QueryMind can be extended into:
โข AI-powered BI dashboards
โข Conversational analytics tools
โข Enterprise SQL copilots
โข Internal data exploration assistants
โข Educational SQL tutors
Learn SQL interactively using natural language.
Accelerate query writing and aggregation.
Prototype complex joins quickly.
Enable non-technical teams to query databases conversationally.
โ Multi-database support
โ Schema-aware LLM grounding
โ Self-healing SQL retry mechanism
โ Secure execution layer
โ Modular architecture
โ Local AI inference
โ Automatic visualization
โ Production-style workflow
Most NL-to-SQL demos:
- Hardcode schema
- Lack safety guard
- Have no retry mechanism
- Do not handle real DB environments
QueryMind addresses these limitations and simulates a real-world AI SQL assistant system.
- PostgreSQL support
- Query optimization feedback
- Conversational memory
- Role-based access control
- Cloud deployment
- LLM fine-tuning on SQL datasets
QueryMind/
โ
โโโ app.py # Streamlit UI (Main Application)
โโโ db.py # Database connection & metadata retrieval
โโโ executor.py # Secure SQL execution layer
โโโ llm.py # Ollama (Mistral) integration
โโโ prompt_builder.py # Schema-grounded prompt logic
โโโ config.py # Database configuration
โโโ requirements.txt
โโโ SQL Generator App.bat
โโโ README.md
QueryMind dynamically fetches all databases from MySQL server.
Any database present in MySQL Workbench automatically appears in the UI.
Left-side panel shows:
- Database selector
- Table list
- Expandable schema
- Column names + data types
Improves query grounding and reduces hallucination.
Example:
Input:
Show total sales by country
Generated SQL:
SELECT c.country,
SUM(od.quantityOrdered * od.priceEach) AS total_sales
FROM customers c
JOIN orders o ON c.customerNumber = o.customerNumber
JOIN orderdetails od ON o.orderNumber = od.orderNumber
GROUP BY c.country;If execution fails:
- Database error captured
- Error sent back to Mistral
- Corrected query generated
- Query automatically retried
- Only SELECT queries allowed
- Blocks DELETE / UPDATE / DROP
- Prevents destructive operations
Optional toggle to understand:
- JOIN logic
- Aggregations
- Query structure
- Detects numeric columns
- Auto-generates charts
- Works for aggregation queries
ollama run mistralpip install -r requirements.txtstreamlit run app.pyOr double-click:
SQL Generator App.bat
For queries, contributions, or collaboration opportunities, feel free to reach out:
๐ง Email: prathamsoni1128@gmail.com
๐ LinkedIn: https://www.linkedin.com/in/pratham-soni-600787268/
๐ป GitHub: https://github.com/prathams0ni
QueryMind is more than a Natural Language to SQL tool โ
it represents a practical implementation of schema-aware AI reasoning, secure database interaction, and self-healing system design.
Turning databases into intelligent, conversational systems โ one query at a time.
โญ If you found this project interesting, consider giving it a star and connecting!