Skip to content

Transform natural language into SQL queries using AI. Prompt2Query lets you interact with your database in plain English - no SQL expertise required. Features live query previews, schema analysis, and CSV export in a friendly CLI interface.

License

Notifications You must be signed in to change notification settings

hipjim/prompt2query

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Prompt2Query: Natural Language to SQL Query CLI πŸš€

License: MIT Python 3.7+ OpenAI PostgreSQL

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.


✨ Key Features

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

🎬 Quick Demo

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 |
...

πŸš€ Getting Started

Prerequisites

Ensure you have the following installed:

Installation

  1. Clone the repository

    git clone https://github.com/hipjim/prompt2query.git
    cd prompt2query
  2. Create a virtual environment (recommended)

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Configure environment variables

    Create a .env file 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
  5. Run the application

    python main_cli.py

πŸ“– Usage Guide

Available Commands

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

Example Natural Language Queries

Basic Queries

>> Show me all products
>> List users registered today
>> Count total orders

Filtering & Conditions

>> Find users who joined last month
>> Show orders with status 'pending'
>> Get products with price greater than $100

Aggregations

>> What's the average order value?
>> Count orders by status
>> Sum total revenue for this year

Complex Queries

>> 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

Joins & Relationships

>> Show all orders with customer details
>> List products and their categories
>> Find users and their recent orders

πŸ—οΈ Architecture

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

Component Details

main_cli.py / improved_cli.py

  • User interface and interaction loop
  • Command parsing and routing
  • Visual feedback with spinners and progress indicators

db.py

  • PostgreSQL connection management
  • Schema introspection and analysis
  • Foreign key relationship detection
  • JOIN pattern suggestions

openai_client.py

  • OpenAI API communication
  • Prompt engineering for SQL generation
  • Context management with schema information

query_executor.py

  • Safe SQL query execution
  • Result fetching and formatting
  • Error handling and recovery

utils.py

  • Result formatting (tables, JSON)
  • CSV export functionality
  • Color-coded console output

🎨 Features in Detail

Smart Schema Analysis

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

Query History

Track your database exploration:

  • View all queries from current session
  • Review prompts and generated SQL
  • Learn SQL patterns from examples

Safe Execution

Safety features built-in:

  • Preview SQL before execution
  • Confirm sensitive operations
  • Graceful error handling
  • Transaction support (coming soon)

Export Capabilities

Save your results:

  • Export to CSV format
  • Organized in exports/ directory
  • Timestamp-based filenames
  • Preserves data types

πŸ”§ Configuration

OpenAI Models

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

Database Configuration

Supports various PostgreSQL setups:

  • Local development databases
  • Remote hosted databases (AWS RDS, etc.)
  • Docker containers
  • Cloud-managed instances

🀝 Contributing

We welcome contributions! Here's how you can help:

  1. Fork the repository

    git clone https://github.com/hipjim/prompt2query.git
  2. Create a feature branch

    git checkout -b feature/amazing-feature
  3. Make your changes

    • Add new features
    • Fix bugs
    • Improve documentation
    • Add tests
  4. Commit with clear messages

    git commit -m 'Add: Amazing new feature that does X'
  5. Push to your fork

    git push origin feature/amazing-feature
  6. Open a Pull Request

Development Setup

# Install development dependencies
pip install -r requirements-dev.txt

# Run tests
pytest tests/

# Run linter
flake8 .

# Format code
black .

πŸ—ΊοΈ Roadmap

  • 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

πŸ› Troubleshooting

Common Issues

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

πŸ“š Resources


πŸ“„ License

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...

πŸ™ Acknowledgments

  • 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

πŸ“ž Support & Contact


Made with ❀️ by the Prompt2Query team

If you find this project useful, please consider giving it a ⭐️

⬆ Back to Top

About

Transform natural language into SQL queries using AI. Prompt2Query lets you interact with your database in plain English - no SQL expertise required. Features live query previews, schema analysis, and CSV export in a friendly CLI interface.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages