Skip to content

FreeAutomation-Tech/sqlgenie

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Python License PRs Welcome CI Stars

SQLGenie 🧞

Your AI-powered SQL genie — just ask in English.

Stop wrestling with SQL syntax. SQLGenie turns plain English into production-ready SQL queries using AI.
Works with OpenAI, Anthropic, and Ollama (local LLMs) — zero external SDKs, just pure Python and `urllib`.


✨ Features

Feature Description
🔮 Natural Language → SQL Ask in English, get SQL. sqlgenie "show me top 10 customers by revenue"
🤖 Multiple AI Providers OpenAI GPT-4o-mini, Anthropic Claude 3 Haiku, or local Ollama models
🎨 Pretty Formatted Output Auto-capitalized keywords, indented clauses, colorful terminal output
📋 EXPLAIN Support sqlgenie explain "SELECT * FROM users WHERE age > 18" — explains what the SQL does in plain English
🗄️ Schema-Aware Register your table schemas for more accurate, context-aware SQL generation
📤 Pipe-Friendly Outputs clean SQL when piped, ANSI colors in TTY — sqlgenie "count orders" | pbcopy
No External SDKs Uses urllib only — no openai package, no anthropic package, no heavy dependencies

🚀 Quick Start

# Install
pip install sqlgenie

# Set your API key
sqlgenie config set OPENAI_API_KEY sk-...

# Start generating SQL!
sqlgenie "show me all users who signed up in the last 30 days"

Output:

demo

  🧞 Generating SQL...

  Generated SQL:

    SELECT *
    FROM users
    WHERE signup_date >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);

📦 Installation

pip install sqlgenie

Or install from source:

git clone https://github.com/sqlgenie/sqlgenie.git
cd sqlgenie
pip install -e .

Requirements: Python 3.8+


🎯 Usage

Basic Question → SQL

sqlgenie "list customers with pending orders"
SELECT *
FROM customers
WHERE status = 'pending'
ORDER BY created_at DESC;

Complex Queries

sqlgenie "show monthly revenue for the last 6 months, grouped by product category"
SELECT   DATE_FORMAT(o.created_at, '%Y-%m') AS month,
         p.category,
         SUM(o.total) AS revenue
FROM     orders o
JOIN     products p ON o.product_id = p.id
WHERE    o.created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)
GROUP BY month, p.category
ORDER BY month DESC;

Explain SQL

sqlgenie explain "SELECT u.name, COUNT(o.id) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name HAVING COUNT(o.id) > 5"
  SQL Explanation:

  This query SELECTs u.name, COUNT(o.id) from 'users' joined with 'orders'.
  It groups results by u.name and filters groups where COUNT(o.id) > 5.

Pipe Output

# Copy SQL to clipboard (macOS)
sqlgenie "count orders by status" | pbcopy

# Save to file
sqlgenie "find all products with low stock" > query.sql

# Pipe into another command
sqlgenie "get user emails" | grep @

When piped, SQLGenie outputs raw SQL without colors — perfect for chaining.


⚙️ Configuration

Set API Keys

# OpenAI (default)
sqlgenie config set OPENAI_API_KEY sk-...

# Anthropic
sqlgenie config set ANTHROPIC_API_KEY sk-ant-...

# Local Ollama (no key needed)
sqlgenie config set PROVIDER ollama
sqlgenie config set OLLAMA_URL http://localhost:11434

Set Model

sqlgenie config set MODEL gpt-4o          # OpenAI
sqlgenie config set MODEL claude-3-opus    # Anthropic
sqlgenie config set MODEL llama3.2         # Ollama

View Configuration

sqlgenie config show

Config is stored in ~/.sqlgenie/config.json.


🗄️ Schema-Aware SQL Generation

Register your table schemas so SQLGenie knows your columns and generates accurate queries:

sqlgenie schema add users "id INT, name VARCHAR(100), email VARCHAR(255), signup_date DATE, status VARCHAR(20)"
sqlgenie schema add orders "id INT, user_id INT, product_id INT, total DECIMAL(10,2), created_at DATETIME, status VARCHAR(20)"
sqlgenie schema add products "id INT, name VARCHAR(200), category VARCHAR(100), price DECIMAL(10,2), stock INT"

Now when you ask:

sqlgenie "find users who spent more than $500 in the last month"

SQLGenie knows about users, orders, and products tables — and generates a correct JOIN query:

SELECT u.name, u.email, SUM(o.total) AS total_spent
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
GROUP BY u.id, u.name, u.email
HAVING total_spent > 500;

List Schemas

sqlgenie schema list

🏗️ Architecture

┌─────────────────────────────────────────────────────┐
│  Your Question (English)                            │
│  "show users who signed up last 30 days"            │
└────────────────────────┬────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────┐
│  sqlgenie CLI (cli.py)                              │
│  • argparse command routing                         │
│  • config & schema management                       │
│  • terminal colors / pipe detection                 │
└────────────────────────┬────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────┐
│  AI Provider (ai.py)                                │
│  • build_messages() — injects schemas into prompt   │
│  • _call_openai()    — urllib → api.openai.com      │
│  • _call_anthropic() — urllib → api.anthropic.com   │
│  • _call_ollama()    — urllib → localhost:11434     │
└────────────────────────┬────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────┐
│  Formatter (formatter.py)                           │
│  • format_sql()     — uppercase keywords, indent    │
│  • explain_sql()    — rule-based SQL explanation    │
│  • format_output()  — table / CSV / JSON renderer   │
└────────────────────────┬────────────────────────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │  SQL Output 🎉      │
              └──────────────────────┘

🔧 Provider Comparison

Provider API Key Needed Model Cost Speed Quality
OpenAI gpt-4o-mini (default), gpt-4o ~$0.15/1M tokens ⚡ Fast ⭐⭐⭐⭐⭐
Anthropic claude-3-haiku (default), claude-3-opus ~$0.25/1M tokens ⚡ Fast ⭐⭐⭐⭐⭐
Ollama llama3.2 (default), any local model 💰 Free 🐢 Depends on hardware ⭐⭐⭐

📚 Examples

Aggregation

sqlgenie "count how many orders each customer has placed"
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
ORDER BY order_count DESC;

Filtering

sqlgenie "find all products priced between $10 and $50 that are in stock"
SELECT *
FROM products
WHERE price BETWEEN 10 AND 50
  AND stock > 0;

Joins

sqlgenie "get the names of users who ordered products in the electronics category"
SELECT DISTINCT u.name
FROM users u
JOIN orders o ON u.id = o.user_id
JOIN products p ON o.product_id = p.id
WHERE p.category = 'electronics';

Date Queries

sqlgenie "show total sales by month for 2024"
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month,
       SUM(total) AS total_sales
FROM orders
WHERE YEAR(created_at) = 2024
GROUP BY month
ORDER BY month;

Subqueries

sqlgenie "find products that have never been ordered"
SELECT *
FROM products
WHERE id NOT IN (
  SELECT DISTINCT product_id
  FROM orders
);

With Clause (CTE)

sqlgenie "find the top 5% of customers by total spending"
WITH customer_spending AS (
  SELECT   customer_id, SUM(total) AS total_spent,
           NTILE(20) OVER (ORDER BY SUM(total) DESC) AS percentile
  FROM     orders
  GROUP BY customer_id
)
SELECT customer_id, total_spent
FROM customer_spending
WHERE percentile = 1;

🤝 Contributing

PRs are welcome! Here's how to get started:

# Clone the repo
git clone https://github.com/sqlgenie/sqlgenie.git
cd sqlgenie

# Install in editable mode
pip install -e .

# Make your changes, then test
python -m sqlgenie --help

Guidelines:

  • Keep external dependencies at zero — only use urllib, json, argparse, sys
  • Add tests for any new modules
  • Update the README if adding features

📄 License

MIT © 2026 SQLGenie. See LICENSE for details.


Made with 🧞 and Python
Because writing SQL from scratch is so 2000s.

--- *If you find this useful, please consider giving it a star ⭐ — it helps others discover it too!*

Thank you for your support! 🙏

About

Natural language to SQL using AI. Just ask in English, get SQL queries back.

Topics

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages