AI to DB is a comprehensive web application that enables users to query databases using natural language. The system leverages Large Language Models (LLMs) through LangChain to convert user questions into SQL queries, execute them safely, and return results in a user-friendly format.
Final Year Project | Built with professional-grade architecture and security best practices.
- ๐ Database Connection Manager: Support for multiple database types (PostgreSQL, MySQL, SQLite, etc.)
- ๐ง Natural Language Processing: Convert plain English questions to SQL using Google Gemini Pro (Free!)
- ๐ Schema Introspection: Automatic extraction and analysis of database structures
- ๐ Security First: Read-only query enforcement with SQL injection prevention
- โก Real-time Execution: Fast query processing with detailed result display
- ๐จ Modern UI: Clean, responsive React interface with intuitive design
- ๐ณ Docker Ready: One-command deployment with Docker Compose
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Frontend (React) โ
โ - Connection Form - Query Interface - Results Display โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HTTP/REST API
โโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Backend (FastAPI) โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โ Connection โ โ Schema โ โ SQL Agent โ โ
โ โ Manager โ โ Extractor โ โ (LangChain) โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โ Security โ โ Query โ โ
โ โ Validator โ โ Executor โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SQLAlchemy
โโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Target Database (User-provided) โ
โ PostgreSQL / MySQL / SQLite / Oracle / MSSQL โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Backend:
- FastAPI: High-performance Python web framework
- SQLAlchemy: Universal database toolkit
- LangChain: LLM orchestration framework
- Google Gemini Pro: Natural language to SQL conversion (Free tier!)
- sqlparse: SQL parsing and validation
Frontend:
- React 18: Modern UI framework
- Vite: Fast build tool and dev server
- Axios: HTTP client for API communication
- React Icons: Beautiful icon library
Infrastructure:
- Docker & Docker Compose: Containerization
- Nginx: Production web server
- PostgreSQL: Demo database (optional)
- Docker and Docker Compose installed
- Google API key (Get one FREE here)
- A database to query (or use the included demo database)
-
Clone the repository:
git clone <repository-url> cd aitodb
-
Configure environment variables:
cp .env.example .env nano .env # Edit and add your GOOGLE_API_KEY (get free key at https://makersuite.google.com/app/apikey) -
Start the application:
docker-compose up -d
-
Access the application:
- Frontend: http://localhost
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
The Docker Compose setup includes a demo PostgreSQL database with sample data:
Connection String:
postgresql://demo:demo123@postgres:5432/demo_db
Or from your host machine:
postgresql://demo:demo123@localhost:5432/demo_db
Sample Questions to Try:
- "Show me all users"
- "What are the top 5 products by price?"
- "How many orders has each user placed?"
- "List all electronics products with stock greater than 50"
- "Show me the total revenue from completed orders"
- Enter your database connection string in the connection form
- Connection string format:
dialect+driver://username:password@host:port/database - Click "Connect to Database"
- The system will validate the connection and extract the schema
- Type your question in natural language
- Click "Execute Query" or press Enter
- View the generated SQL and results
- Results are displayed in a formatted table
- Generated SQL: The AI-generated query is shown for transparency
- Results Table: Data displayed in a clean, sortable format
- Execution Time: Performance metrics for the query
- Row Count: Number of results returned
- All queries are validated to be read-only (SELECT only)
- SQL injection patterns are automatically detected and blocked
- Dangerous keywords (INSERT, UPDATE, DELETE, DROP) are prevented
- Connection strings are never stored
-
Create virtual environment:
cd backend python -m venv venv source venv/bin/activate # Linux/Mac # or venv\Scripts\activate # Windows
-
Install dependencies:
pip install -r requirements.txt
-
Configure environment:
cp .env.example .env # Edit .env with your settings -
Run development server:
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
-
Access API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
-
Install dependencies:
cd frontend npm install -
Run development server:
npm run dev
-
Build for production:
npm run build
aitodb/
โโโ backend/
โ โโโ app/
โ โ โโโ api/ # API route handlers
โ โ โ โโโ connection.py # Connection management endpoints
โ โ โ โโโ query.py # Query execution endpoints
โ โ โโโ core/ # Core configuration
โ โ โ โโโ config.py # Application settings
โ โ โโโ models/ # Pydantic models
โ โ โ โโโ schemas.py # Request/response schemas
โ โ โโโ services/ # Business logic
โ โ โ โโโ connection.py # Connection manager
โ โ โ โโโ schema_extractor.py # Schema introspection
โ โ โ โโโ security.py # SQL validation
โ โ โ โโโ sql_agent.py # NL to SQL conversion
โ โ โ โโโ executor.py # Query execution
โ โ โโโ main.py # FastAPI application
โ โโโ Dockerfile
โ โโโ requirements.txt
โโโ frontend/
โ โโโ src/
โ โ โโโ components/ # React components
โ โ โ โโโ Header.jsx
โ โ โ โโโ ConnectionForm.jsx
โ โ โ โโโ QueryInterface.jsx
โ โ โ โโโ ResultsDisplay.jsx
โ โ โโโ services/ # API client
โ โ โ โโโ api.js
โ โ โโโ App.jsx # Main app component
โ โ โโโ main.jsx # Entry point
โ โโโ Dockerfile
โ โโโ nginx.conf
โ โโโ package.json
โโโ demo/
โ โโโ init.sql # Demo database schema
โโโ docker-compose.yml # Container orchestration
โโโ .env.example # Environment template
โโโ README.md # This file
- Keyword Blacklist: Blocks dangerous SQL operations
- Pattern Detection: Identifies injection attempts
- Query Validation: Ensures only SELECT statements
- Parameterized Queries: Uses SQLAlchemy's safe execution
All queries are validated to ensure they:
- Start with SELECT or WITH (CTEs)
- Don't contain modification keywords
- Don't access system tables maliciously
- Don't use dangerous functions
- Connection strings are not persisted
- No database credentials stored
- Secure environment variable handling
- CORS protection enabled
Backend (.env):
GOOGLE_API_KEY=your_api_key_here # Required: Your Google API key (FREE at https://makersuite.google.com/app/apikey)
APP_NAME=AI to DB # Application name
APP_VERSION=1.0.0 # Version number
DEBUG=True # Debug mode (False in production)
ALLOWED_ORIGINS=http://localhost # CORS origins
SECRET_KEY=your-secret-key # Security key- PostgreSQL (9.6+)
- MySQL (5.7+)
- SQLite (3+)
- Oracle
- Microsoft SQL Server
- MariaDB
Connection String Examples:
# PostgreSQL
postgresql://user:password@host:5432/database
# MySQL
mysql+pymysql://user:password@host:3306/database
# SQLite
sqlite:///./database.db
# SQL Server
mssql+pyodbc://user:password@host:1433/database?driver=ODBC+Driver+17+for+SQL+ServerPOST /api/connection/test
Content-Type: application/json
{
"connection_string": "postgresql://user:pass@host:5432/db",
"alias": "My Database"
}POST /api/connection/schema
Content-Type: application/json
{
"connection_string": "postgresql://user:pass@host:5432/db"
}POST /api/query/execute
Content-Type: application/json
{
"connection_string": "postgresql://user:pass@host:5432/db",
"question": "Show me all users who signed up last month"
}POST /api/query/validate-sql?sql=SELECT * FROM users- Start the application with Docker Compose
- Connect using:
postgresql://demo:demo123@postgres:5432/demo_db - Try these queries:
- "How many users are there?"
- "Show me all products sorted by price"
- "What is the total revenue from completed orders?"
- "List users who have placed more than one order"
# Backend health check
curl http://localhost:8000/health
# Test connection
curl -X POST http://localhost:8000/api/connection/test \
-H "Content-Type: application/json" \
-d '{"connection_string": "sqlite:///./demo.db"}'Google API Error:
- Ensure your API key is valid (get free key at https://makersuite.google.com/app/apikey)
- Check the key is correctly set in
.env - Verify no extra spaces in the key
- Note: Free tier has 60 requests/minute, 1500/day limit
Database Connection Failed:
- Verify connection string format
- Check database is accessible from Docker container
- Use
host.docker.internalfor local databases on Mac/Windows - Use
172.17.0.1for local databases on Linux
Frontend Can't Connect to Backend:
- Ensure both containers are running:
docker-compose ps - Check backend logs:
docker-compose logs backend - Verify CORS settings in backend config
Port Already in Use:
- Change port mapping in docker-compose.yml
- Stop conflicting services:
sudo lsof -i :8000
# View all logs
docker-compose logs
# View specific service
docker-compose logs backend
docker-compose logs frontend
# Follow logs in real-time
docker-compose logs -f backendThis project serves as a Final Year Project demonstrating:
- Full-Stack Development: Complete web application with modern technologies
- AI Integration: Practical application of Large Language Models
- Software Architecture: Clean, modular, maintainable code structure
- Security Best Practices: Input validation, SQL injection prevention
- DevOps: Containerization and deployment automation
- Database Management: Multi-database support with SQLAlchemy
- API Design: RESTful API with comprehensive documentation
- Building production-ready web applications
- Integrating AI/ML models into software systems
- Implementing security measures in database applications
- Container orchestration with Docker
- Modern frontend development with React
- Backend API development with FastAPI
- Database abstraction with SQLAlchemy
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Commit your changes:
git commit -am 'Add feature' - Push to the branch:
git push origin feature-name - Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
Samuel - Final Year Computer Science Student
- Google for Gemini Pro API (Free tier!)
- FastAPI team for excellent documentation
- LangChain community
- React and Vite communities
- SQLAlchemy maintainers
For questions or issues:
- Check the Troubleshooting section
- Review API documentation at http://localhost:8000/docs
- Check application logs with
docker-compose logs
- Support for query history and favorites
- Export results to CSV/JSON/Excel
- Query performance optimization suggestions
- Multi-language support
- Voice input for queries
- Data visualization (charts and graphs)
- Collaborative query sharing
- Query result caching
- Support for more LLM providers
- Advanced analytics and insights
Built with โค๏ธ for database enthusiasts and AI practitioners