Transform natural language into SQL queries instantly. Interact with your database using plain English - no SQL expertise required!
Prompt2Query is an intelligent CLI tool that leverages AI to translate natural language commands into optimized SQL queries, making database querying accessible to everyone.
| Feature | Description |
|---|---|
| π£οΈ Natural Language Processing | Describe what you want in plain English, get precise SQL |
| π¨ Beautiful CLI Interface | Color-coded, intuitive command-line experience |
| π Smart Schema Analysis | Automatic detection of table relationships and join patterns |
| π Query Preview & Confirmation | Review and approve generated SQL before execution |
| π Export to CSV | Save query results to CSV files instantly |
| π Query History | Track all queries executed in your session |
| π Relationship Suggestions | Intelligent JOIN pattern recommendations |
| π‘οΈ Safe Execution | Always confirm before running queries |
prompt2query >> Show me all users who joined in the last 30 days
β Generating SQL query...
π Generated SQL Query:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SELECT *
FROM users
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
ORDER BY created_at DESC;
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Execute this query? [Y/n/e(dit)]: y
β Query executed successfully!
| id | username | email | created_at |
|-----|---------------|----------------------|---------------------|
| 142 | john_doe | [email protected] | 2024-10-15 14:23:01 |
| 143 | jane_smith | [email protected] | 2024-10-18 09:45:33 |
...Ensure you have the following installed:
- Python 3.7+ (Download)
- PostgreSQL (Download)
- OpenAI API Key (Get one here)
-
Clone the repository
git clone https://github.com/hipjim/prompt2query.git cd prompt2query -
Create a virtual environment (recommended)
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Configure environment variables
Create a
.envfile in the project root:# OpenAI Configuration OPENAI_API_KEY=sk-your-api-key-here OPENAI_MODEL=gpt-4 # or gpt-3.5-turbo for faster/cheaper queries # PostgreSQL Configuration DB_HOST=localhost DB_DATABASE=your_database_name DB_USER=your_username DB_PASSWORD=your_password DB_PORT=5432
-
Run the application
python main_cli.py
| Command | Description | Example |
|---|---|---|
help |
Display help information and usage examples | help |
tables |
List all tables in the database | tables |
schema |
Show complete database schema with relationships | schema |
describe <table> |
Show detailed schema for a specific table | describe users |
history |
View all queries executed in current session | history |
clear |
Clear the terminal screen | clear |
exit / quit |
Exit the application | exit |
>> Show me all products
>> List users registered today
>> Count total orders
>> Find users who joined last month
>> Show orders with status 'pending'
>> Get products with price greater than $100
>> What's the average order value?
>> Count orders by status
>> Sum total revenue for this year
>> Show top 10 customers by total spending
>> Find products that haven't been ordered in 6 months
>> List users who have made more than 5 purchases
>> Calculate monthly revenue for the last quarter
>> Show all orders with customer details
>> List products and their categories
>> Find users and their recent orders
prompt2query/
βββ main_cli.py # Main CLI application & user interface
βββ improved_cli.py # Enhanced version with advanced features
βββ db.py # Database connection & schema analysis
βββ openai_client.py # OpenAI API integration & prompt engineering
βββ query_executor.py # SQL query execution & result handling
βββ utils.py # Utility functions (formatting, CSV export)
βββ requirements.txt # Python dependencies
βββ .env # Configuration (not in repo)
βββ exports/ # Generated CSV exports
- User interface and interaction loop
- Command parsing and routing
- Visual feedback with spinners and progress indicators
- PostgreSQL connection management
- Schema introspection and analysis
- Foreign key relationship detection
- JOIN pattern suggestions
- OpenAI API communication
- Prompt engineering for SQL generation
- Context management with schema information
- Safe SQL query execution
- Result fetching and formatting
- Error handling and recovery
- Result formatting (tables, JSON)
- CSV export functionality
- Color-coded console output
The tool automatically analyzes your database structure:
- Detects all tables and their columns
- Identifies primary and foreign keys
- Suggests optimal JOIN patterns
- Provides relationship insights
Track your database exploration:
- View all queries from current session
- Review prompts and generated SQL
- Learn SQL patterns from examples
Safety features built-in:
- Preview SQL before execution
- Confirm sensitive operations
- Graceful error handling
- Transaction support (coming soon)
Save your results:
- Export to CSV format
- Organized in
exports/directory - Timestamp-based filenames
- Preserves data types
Choose the right model for your needs:
| Model | Speed | Cost | Quality | Best For |
|---|---|---|---|---|
gpt-4 |
Slower | Higher | Excellent | Complex queries, production |
gpt-3.5-turbo |
Fast | Lower | Good | Simple queries, development |
Supports various PostgreSQL setups:
- Local development databases
- Remote hosted databases (AWS RDS, etc.)
- Docker containers
- Cloud-managed instances
We welcome contributions! Here's how you can help:
-
Fork the repository
git clone https://github.com/hipjim/prompt2query.git
-
Create a feature branch
git checkout -b feature/amazing-feature
-
Make your changes
- Add new features
- Fix bugs
- Improve documentation
- Add tests
-
Commit with clear messages
git commit -m 'Add: Amazing new feature that does X' -
Push to your fork
git push origin feature/amazing-feature
-
Open a Pull Request
# Install development dependencies
pip install -r requirements-dev.txt
# Run tests
pytest tests/
# Run linter
flake8 .
# Format code
black .- Multi-database support (MySQL, SQLite, MongoDB)
- Query optimization suggestions
- Visual query builder
- Saved query templates
- Collaboration features (share queries)
- Data visualization (charts, graphs)
- Query performance metrics
- Natural language result descriptions
- Voice input support
- Web interface
API Key Error
Error: OpenAI API key not found
Solution: Ensure OPENAI_API_KEY is set in your .env file
Database Connection Failed
Error: Could not connect to database
Solution: Check DB credentials in .env and ensure PostgreSQL is running
Module Not Found
Error: No module named 'openai'
Solution: Run: pip install -r requirements.txt
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2024 Prompt2Query Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files...
- OpenAI - For powerful language models that make natural language SQL possible
- Rich - For beautiful terminal formatting and UI components
- Colorama - For cross-platform colored terminal output
- SQLParse - For SQL query formatting and parsing
- python-dotenv - For clean environment variable management
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Project: https://github.com/hipjim/prompt2query
Made with β€οΈ by the Prompt2Query team
If you find this project useful, please consider giving it a βοΈ