unknown commited on
Commit
7814c1f
·
0 Parent(s):

Initial commit: CodeFlow AI - NL to SQL Generator

Browse files
README.md ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CodeFlow AI - Natural Language to Production ETL
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.8.0
8
+ app_file: app.py
9
+ pinned: true
10
+ tags:
11
+ - mcp-in-action-track-enterprise
12
+ - etl
13
+ - sql
14
+ - llamaindex
15
+ - modal
16
+ - data-engineering
17
+ - natural-language-processing
18
+ license: mit
19
+ ---
20
+
21
+ # 🚀 CodeFlow AI - Advanced Natural Language to SQL Engine
22
+
23
+ Transform plain English into production-ready, optimized SQL queries using Claude AI!
24
+
25
+ ## 🏆 Hackathon Submission
26
+
27
+ **Track:** MCP in Action (Enterprise Category)
28
+ **Sponsors:**
29
+ - 🎯 **LlamaIndex** (PRIMARY) - RAG-powered template matching
30
+ - ⚡ **Modal** (SECONDARY) - Serverless SQL testing
31
+
32
+ **Built for:** MCP 1st Birthday Hackathon
33
+
34
+ ## ✨ Features
35
+
36
+ ### Core Capabilities
37
+ - 🧠 **Advanced NL Understanding**: Powered by Claude 3 Opus for superior natural language comprehension
38
+ - 🔍 **Schema-Aware Validation**: Never hallucinates tables or columns
39
+ - ✨ **Automatic Optimization**: Applies SQL best practices automatically
40
+ - 📊 **Complex Query Support**: CTEs, Window Functions, Subqueries, Analytics
41
+ - ⚠️ **Intelligent Warnings**: Identifies potential issues and suggests improvements
42
+ - 🎯 **Multi-Dialect Support**: PostgreSQL, MySQL, SQLite, SQL Server
43
+
44
+ ### 🎯 Sponsor Integrations
45
+
46
+ #### LlamaIndex RAG (PRIMARY SPONSOR)
47
+ - **Similar Pattern Suggestions**: Retrieves relevant SQL patterns from template library
48
+ - **15+ ETL Templates**: Pre-built patterns for common data transformations
49
+ - **Context-Aware Learning**: Vector similarity search for pattern matching
50
+ - **Production-Ready Examples**: Customer aggregations, window functions, cohort analysis, and more
51
+
52
+ #### Modal Serverless Testing (SECONDARY SPONSOR)
53
+ - **Sandboxed Execution**: Test SQL queries in isolated environments
54
+ - **DuckDB Integration**: Fast in-memory SQL execution
55
+ - **Result Preview**: See query results before production deployment
56
+ - **Error Detection**: Catch syntax and runtime errors early
57
+
58
+ ### Production Export
59
+ - **dbt Model Generation**: Export to production-ready dbt models
60
+ - **Automatic Documentation**: Schema.yml with column descriptions
61
+ - **Test Generation**: Basic data quality tests included
62
+ - **ZIP Download**: Complete dbt project structure
63
+
64
+ ### Advanced SQL Features
65
+ - **Common Table Expressions (CTEs)**: For complex, multi-step queries
66
+ - **Window Functions**: Rankings, running totals, moving averages
67
+ - **Analytical Queries**: Cohort analysis, trends, comparisons
68
+ - **Optimized Joins**: Proper JOIN syntax, EXISTS/NOT EXISTS
69
+ - **NULL Handling**: Correct IS NULL/IS NOT NULL usage
70
+ - **Date Range Optimization**: Efficient date filtering
71
+
72
+ ## 🎯 What Makes CodeFlow AI Unique?
73
+
74
+ Unlike generic ChatGPT prompts, CodeFlow AI provides:
75
+
76
+ 1. **Schema-Aware Generation** - Never hallucinates tables or columns
77
+ 2. **RAG-Powered Learning** (LlamaIndex) - Learns from organizational SQL patterns
78
+ 3. **Automated Testing** (Modal) - Serverless execution with result preview
79
+ 4. **Production Export** (dbt) - One-click export to production-ready dbt models
80
+ 5. **Advanced Validation** - Multi-layer validation with optimization suggestions
81
+ 6. **Template Library** - 15+ pre-built ETL patterns for common scenarios
82
+
83
+ This makes CodeFlow AI **significantly better** than just asking ChatGPT for SQL!
84
+
85
+ ## 🚀 Quick Start
86
+
87
+ ### Prerequisites
88
+ - Python 3.8+
89
+ - Anthropic API key
90
+ - OpenAI API key (for LlamaIndex embeddings)
91
+ - Modal account (optional, for serverless testing)
92
+
93
+ ### Installation
94
+
95
+ 1. Clone the repository:
96
+ ```bash
97
+ git clone <repository-url>
98
+ cd codeflow-ai
99
+ ```
100
+
101
+ 2. Install dependencies:
102
+ ```bash
103
+ pip install -r requirements.txt
104
+ ```
105
+
106
+ 3. Set up your API keys:
107
+ ```bash
108
+ # Create .env file
109
+ cat > .env << EOF
110
+ ANTHROPIC_API_KEY=your_anthropic_key_here
111
+ OPENAI_API_KEY=your_openai_key_here
112
+ EOF
113
+ ```
114
+
115
+ 4. Initialize the database (optional):
116
+ ```bash
117
+ python init_database.py
118
+ ```
119
+
120
+ 5. Run the application:
121
+ ```bash
122
+ python app.py
123
+ ```
124
+
125
+ 6. Open your browser to: `http://127.0.0.1:7860`
126
+
127
+ ## 📖 Usage Examples
128
+
129
+ ### Simple Queries
130
+ ```
131
+ "Show all customers"
132
+ → SELECT * FROM customers;
133
+ ```
134
+
135
+ ### Aggregations
136
+ ```
137
+ "Count orders by customer"
138
+ → SELECT customer_id, COUNT(*) as order_count
139
+ FROM orders
140
+ GROUP BY customer_id;
141
+ ```
142
+
143
+ ### Advanced Analytics
144
+ ```
145
+ "Find top 5 customers by revenue with running totals"
146
+ → WITH customer_revenue AS (
147
+ SELECT c.id, c.name, SUM(o.amount) as total_revenue
148
+ FROM customers c
149
+ JOIN orders o ON c.id = o.customer_id
150
+ GROUP BY c.id, c.name
151
+ )
152
+ SELECT
153
+ id, name, total_revenue,
154
+ ROW_NUMBER() OVER (ORDER BY total_revenue DESC) as rank,
155
+ SUM(total_revenue) OVER (ORDER BY total_revenue DESC) as running_total
156
+ FROM customer_revenue
157
+ ORDER BY total_revenue DESC
158
+ LIMIT 5;
159
+ ```
160
+
161
+ ### Complex Conditions
162
+ ```
163
+ "Customers who ordered in 2023 but not in 2024"
164
+ → SELECT c.*
165
+ FROM customers c
166
+ WHERE EXISTS (
167
+ SELECT 1 FROM orders o
168
+ WHERE o.customer_id = c.id
169
+ AND o.order_date >= '2023-01-01'
170
+ AND o.order_date < '2024-01-01'
171
+ )
172
+ AND NOT EXISTS (
173
+ SELECT 1 FROM orders o
174
+ WHERE o.customer_id = c.id
175
+ AND o.order_date >= '2024-01-01'
176
+ );
177
+ ```
178
+
179
+ ## 🏗️ Architecture
180
+
181
+ ### Core Components
182
+
183
+ 1. **nl_parser.py**: Advanced Natural Language to SQL Engine
184
+ - Claude 3 Opus integration
185
+ - Comprehensive prompt engineering
186
+ - JSON-structured output with metadata
187
+
188
+ 2. **schema_analyzer.py**: Database Schema Analysis
189
+ - Extracts table and column information
190
+ - Provides schema context to the AI
191
+
192
+ 3. **sql_validator.py**: SQL Validation and Optimization
193
+ - Schema validation
194
+ - Anti-pattern detection
195
+ - Optimization suggestions
196
+
197
+ 4. **app.py**: Gradio Web Interface
198
+ - User-friendly UI
199
+ - Real-time query generation
200
+ - Metadata and analysis display
201
+
202
+ ### Sponsor Integration Modules
203
+
204
+ 5. **rag/template_store.py**: LlamaIndex RAG (PRIMARY SPONSOR)
205
+ - Vector store with ChromaDB
206
+ - 15+ ETL template library
207
+ - Semantic similarity search
208
+ - Context-aware pattern matching
209
+
210
+ 6. **testing/test_runner.py**: Modal Testing (SECONDARY SPONSOR)
211
+ - Serverless SQL execution
212
+ - DuckDB integration
213
+ - Sandboxed query testing
214
+ - Result preview
215
+
216
+ 7. **export/dbt_exporter.py**: Production Export
217
+ - dbt model generation
218
+ - Schema documentation
219
+ - Test generation
220
+ - ZIP packaging
221
+
222
+ ## 🔧 Configuration
223
+
224
+ ### Environment Variables
225
+
226
+ Create a `.env` file in the project root:
227
+
228
+ ```env
229
+ ANTHROPIC_API_KEY=your_anthropic_api_key_here
230
+ ```
231
+
232
+ ### SQL Dialect Support
233
+
234
+ The system supports multiple SQL dialects:
235
+ - **PostgreSQL** (default)
236
+ - **MySQL**
237
+ - **SQLite**
238
+ - **SQL Server**
239
+
240
+ Select your dialect in the UI dropdown.
241
+
242
+ ## 📊 Query Types
243
+
244
+ The system automatically detects and optimizes different query types:
245
+
246
+ - **Simple**: Basic SELECT statements
247
+ - **Aggregate**: GROUP BY with aggregate functions
248
+ - **Join**: Multiple table queries
249
+ - **Window**: Analytical functions with OVER clause
250
+ - **CTE**: Common Table Expressions (WITH clause)
251
+ - **Analytical**: Complex multi-step analysis
252
+
253
+ ## ✅ SQL Best Practices
254
+
255
+ The engine automatically applies these best practices:
256
+
257
+ ### NULL Handling
258
+ ❌ Bad: `WHERE column = NULL`
259
+ ✅ Good: `WHERE column IS NULL`
260
+
261
+ ### Date Ranges
262
+ ❌ Bad: `WHERE date BETWEEN '2024-01-01' AND '2024-12-31'`
263
+ ✅ Good: `WHERE date >= '2024-01-01' AND date < '2025-01-01'`
264
+
265
+ ### Subqueries
266
+ ❌ Bad: `WHERE id NOT IN (SELECT ...)`
267
+ ✅ Good: `WHERE NOT EXISTS (SELECT 1 FROM ... WHERE ...)`
268
+
269
+ ### Joins
270
+ ❌ Bad: `FROM table1, table2 WHERE table1.id = table2.id`
271
+ ✅ Good: `FROM table1 JOIN table2 ON table1.id = table2.id`
272
+
273
+ ### CTEs for Readability
274
+ ❌ Bad: Nested subqueries
275
+ ✅ Good:
276
+ ```sql
277
+ WITH step1 AS (...),
278
+ step2 AS (...)
279
+ SELECT * FROM step2;
280
+ ```
281
+
282
+ ## 🧪 Testing
283
+
284
+ Test your API connection:
285
+ ```bash
286
+ python test_api.py
287
+ ```
288
+
289
+ This will:
290
+ - Verify your API key
291
+ - Test available models
292
+ - Confirm connectivity
293
+
294
+ ## 📝 Sample Database Schema
295
+
296
+ The default sample database includes:
297
+
298
+ ### Customers Table
299
+ - id (INTEGER, PRIMARY KEY)
300
+ - name (TEXT, NOT NULL)
301
+ - email (TEXT)
302
+ - country (TEXT)
303
+ - created_at (TIMESTAMP)
304
+
305
+ ### Orders Table
306
+ - id (INTEGER, PRIMARY KEY)
307
+ - customer_id (INTEGER)
308
+ - order_date (DATE)
309
+ - total_amount (DECIMAL)
310
+ - status (TEXT)
311
+
312
+ ### Products Table
313
+ - id (INTEGER, PRIMARY KEY)
314
+ - name (TEXT, NOT NULL)
315
+ - price (DECIMAL)
316
+ - category (TEXT)
317
+ - stock_quantity (INTEGER)
318
+
319
+ ## 🎓 Advanced Examples
320
+
321
+ ### 1. Moving Averages
322
+ ```
323
+ "Show daily order count with 7-day moving average"
324
+ ```
325
+
326
+ ### 2. Cohort Analysis
327
+ ```
328
+ "Calculate customer cohorts based on first purchase month"
329
+ ```
330
+
331
+ ### 3. Year-over-Year Comparison
332
+ ```
333
+ "Show monthly revenue trends with year-over-year comparison"
334
+ ```
335
+
336
+ ### 4. Top N per Group
337
+ ```
338
+ "Find the 3 most popular products in each category"
339
+ ```
340
+
341
+ ### 5. Missing Data Analysis
342
+ ```
343
+ "Get customers who have never placed an order"
344
+ ```
345
+
346
+ ## 🔒 Security
347
+
348
+ - Never exposes raw API keys in the UI
349
+ - Schema validation prevents SQL injection patterns
350
+ - All queries are generated, not concatenated from user input
351
+
352
+ ## 🐛 Troubleshooting
353
+
354
+ ### API Key Issues
355
+ If you see 404 model errors:
356
+ 1. Run `python test_api.py` to check available models
357
+ 2. Ensure your API key is valid
358
+ 3. Check if you have access to Claude 3 models
359
+
360
+ ### Schema Not Loading
361
+ 1. Verify `sample.db` exists
362
+ 2. Run `python init_database.py` to recreate it
363
+ 3. Check file permissions
364
+
365
+ ### Gradio Errors
366
+ 1. Ensure Gradio >= 4.44.1: `pip install gradio>=4.44.1`
367
+ 2. Clear browser cache
368
+ 3. Try a different browser
369
+
370
+ ## 📚 Resources
371
+
372
+ - [Anthropic Claude API Documentation](https://docs.anthropic.com/)
373
+ - [SQL Best Practices](https://www.sqlstyle.guide/)
374
+ - [Window Functions Guide](https://www.postgresql.org/docs/current/tutorial-window.html)
375
+
376
+ ## 🤝 Contributing
377
+
378
+ Contributions are welcome! Please ensure:
379
+ - Code follows Python PEP 8 style
380
+ - Add tests for new features
381
+ - Update documentation
382
+
383
+ ## 📄 License
384
+
385
+ MIT License
386
+
387
+ ## 🙏 Acknowledgments
388
+
389
+ - Built with [Anthropic Claude AI](https://www.anthropic.com/)
390
+ - RAG powered by [LlamaIndex](https://www.llamaindex.ai/) ⭐ PRIMARY SPONSOR
391
+ - Serverless testing with [Modal](https://modal.com/) ⚡ SECONDARY SPONSOR
392
+ - UI powered by [Gradio](https://gradio.app/)
393
+ - Database support via [SQLAlchemy](https://www.sqlalchemy.org/)
394
+
395
+ ## 🏆 Hackathon Success Criteria
396
+
397
+ ✅ **Natural language → SQL**: Complete
398
+ ✅ **LlamaIndex RAG with templates**: Complete (15 templates)
399
+ ✅ **Modal testing integration**: Complete (with DuckDB fallback)
400
+ ✅ **dbt export functionality**: Complete
401
+ ✅ **README with hackathon tags**: Complete
402
+ ✅ **Works on Hugging Face Space**: Ready to deploy
403
+
404
+ ## 📹 Demo & Social
405
+
406
+ - **Demo Video**: [Coming Soon - Will be added before submission]
407
+ - **LinkedIn Post**: [Coming Soon - Will be shared]
408
+ - **Twitter/X Post**: [Coming Soon - Will be shared]
409
+
410
+ ## 📞 Contact & Support
411
+
412
+ For questions about this hackathon submission:
413
+ - **Track**: MCP in Action (Enterprise Category)
414
+ - **Built for**: MCP 1st Birthday Hackathon
415
+ - **Sponsors**: LlamaIndex (PRIMARY), Modal (SECONDARY)
416
+
417
+ ---
418
+
419
+ **🏆 MCP 1st Birthday Hackathon Submission**
420
+ Made with ❤️ for the data engineering community
app.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from nl_parser import NaturalLanguageParser
5
+ from schema_analyzer import SchemaAnalyzer
6
+ from sql_validator import SQLValidator
7
+ from rag.template_store import get_template_store
8
+ from testing.test_runner import get_test_runner
9
+ from export.dbt_exporter import get_dbt_exporter
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+
14
+ # Initialize components
15
+ print("Initializing CodeFlow AI - Advanced NL-to-SQL Engine...")
16
+ try:
17
+ parser = NaturalLanguageParser()
18
+ print("✓ Natural Language Parser ready")
19
+ except Exception as e:
20
+ print(f"✗ Error initializing parser: {e}")
21
+ print("Make sure your ANTHROPIC_API_KEY is set in .env file!")
22
+ exit(1)
23
+
24
+ schema_analyzer = SchemaAnalyzer()
25
+ print("✓ Schema Analyzer ready")
26
+
27
+ # Get database schema
28
+ DB_SCHEMA = schema_analyzer.get_schema()
29
+ print(f"✓ Loaded schema with {len(DB_SCHEMA)} tables")
30
+
31
+ # Initialize SQL Validator
32
+ validator = SQLValidator(DB_SCHEMA)
33
+ print("✓ SQL Validator ready")
34
+
35
+ # Initialize RAG Template Store (PRIMARY SPONSOR - LlamaIndex)
36
+ try:
37
+ template_store = get_template_store()
38
+ print("✓ RAG Template Store ready (LlamaIndex)")
39
+ except Exception as e:
40
+ print(f"⚠️ Warning: RAG Template Store initialization failed: {e}")
41
+ template_store = None
42
+
43
+ # Initialize Test Runner (SECONDARY SPONSOR - Modal)
44
+ try:
45
+ test_runner = get_test_runner()
46
+ print("✓ SQL Test Runner ready (Modal/DuckDB)")
47
+ except Exception as e:
48
+ print(f"⚠️ Warning: Test Runner initialization failed: {e}")
49
+ test_runner = None
50
+
51
+ # Initialize dbt Exporter
52
+ try:
53
+ dbt_exporter = get_dbt_exporter()
54
+ print("✓ dbt Exporter ready")
55
+ except Exception as e:
56
+ print(f"⚠️ Warning: dbt Exporter initialization failed: {e}")
57
+ dbt_exporter = None
58
+
59
+ def generate_sql(description, dialect):
60
+ """Main function to generate SQL with advanced analysis"""
61
+
62
+ if not description.strip():
63
+ return "⚠️ Please enter a description of your query.", "", ""
64
+
65
+ try:
66
+ # Generate SQL using enhanced parser
67
+ result = parser.generate_sql(description, DB_SCHEMA, dialect)
68
+
69
+ # Extract components
70
+ sql = result.get("sql", "-- No SQL generated")
71
+ explanation = result.get("explanation", "")
72
+ query_type = result.get("query_type", "unknown")
73
+ warnings = result.get("warnings", [])
74
+ optimizations = result.get("optimizations", [])
75
+
76
+ # Validate SQL using sql_validator (NEW: Integration)
77
+ validation_result = validator.validate(sql)
78
+ validator_suggestions = validator.suggest_optimizations(sql)
79
+
80
+ # Find similar patterns using RAG (NEW: PRIMARY SPONSOR - LlamaIndex)
81
+ similar_patterns = []
82
+ if template_store and template_store.index is not None:
83
+ try:
84
+ similar_patterns = template_store.find_similar(description, top_k=3)
85
+ except Exception as e:
86
+ print(f"⚠️ RAG query failed: {e}")
87
+
88
+ # Build metadata display
89
+ metadata_parts = []
90
+
91
+ # Query type
92
+ metadata_parts.append(f"**Query Type:** {query_type.title()}")
93
+
94
+ # Explanation
95
+ if explanation:
96
+ metadata_parts.append(f"\n**Explanation:**\n{explanation}")
97
+
98
+ # Optimizations applied
99
+ if optimizations:
100
+ metadata_parts.append("\n**✨ Optimizations Applied:**")
101
+ for opt in optimizations:
102
+ metadata_parts.append(f" • {opt}")
103
+
104
+ # Validator suggestions (NEW)
105
+ if validator_suggestions:
106
+ metadata_parts.append("\n**💡 Additional Optimization Suggestions:**")
107
+ for suggestion in validator_suggestions:
108
+ metadata_parts.append(f" • {suggestion}")
109
+
110
+ # Validation errors (NEW)
111
+ if validation_result.get("errors"):
112
+ metadata_parts.append("\n**❌ Validation Errors:**")
113
+ for error in validation_result["errors"]:
114
+ metadata_parts.append(f" • {error}")
115
+
116
+ # Validation warnings (NEW)
117
+ if validation_result.get("warnings"):
118
+ metadata_parts.append("\n**⚠️ Validation Warnings:**")
119
+ for warn in validation_result["warnings"]:
120
+ metadata_parts.append(f" • {warn}")
121
+
122
+ # Original warnings from parser
123
+ if warnings:
124
+ metadata_parts.append("\n**⚠️ Parser Warnings:**")
125
+ for warn in warnings:
126
+ metadata_parts.append(f" • {warn}")
127
+
128
+ # Similar patterns from RAG (NEW: PRIMARY SPONSOR)
129
+ if similar_patterns:
130
+ metadata_parts.append("\n**🔍 Similar Patterns (LlamaIndex RAG):**")
131
+ for i, pattern in enumerate(similar_patterns, 1):
132
+ template_name = pattern.get("template_name", "Unknown")
133
+ metadata_parts.append(f" {i}. **{template_name}**")
134
+ if pattern.get("excerpt"):
135
+ # Show first 2 lines of excerpt
136
+ excerpt_lines = pattern["excerpt"].split('\n')[:2]
137
+ for line in excerpt_lines:
138
+ if line.strip():
139
+ metadata_parts.append(f" `{line.strip()}`")
140
+
141
+ metadata_text = "\n".join(metadata_parts)
142
+
143
+ # Format SQL with header
144
+ formatted_sql = f"""-- CodeFlow AI - Advanced NL-to-SQL Engine
145
+ -- Dialect: {dialect}
146
+ -- Query Type: {query_type.title()}
147
+
148
+ {sql}"""
149
+
150
+ return formatted_sql, metadata_text, ""
151
+
152
+ except Exception as e:
153
+ error_msg = f"-- Error generating SQL\n-- {str(e)}\n\n-- Please try rephrasing your request."
154
+ metadata_msg = f"**❌ Error:**\n{str(e)}"
155
+ return error_msg, metadata_msg, ""
156
+
157
+ def test_sql_query(sql_code):
158
+ """Test SQL query execution (SECONDARY SPONSOR - Modal)"""
159
+
160
+ if not sql_code or not sql_code.strip():
161
+ return "⚠️ No SQL to test. Generate SQL first."
162
+
163
+ # Extract just the SQL (remove comments)
164
+ sql_lines = []
165
+ for line in sql_code.split('\n'):
166
+ stripped = line.strip()
167
+ if stripped and not stripped.startswith('--'):
168
+ sql_lines.append(line)
169
+
170
+ clean_sql = '\n'.join(sql_lines).strip()
171
+
172
+ if not clean_sql:
173
+ return "⚠️ No executable SQL found."
174
+
175
+ if not test_runner:
176
+ return "⚠️ Test runner not available. Install Modal or DuckDB."
177
+
178
+ try:
179
+ # Test the SQL
180
+ result = test_runner.test_sql(clean_sql)
181
+
182
+ # Format results
183
+ if result["success"]:
184
+ output_parts = []
185
+ output_parts.append(f"**✅ Query Executed Successfully**")
186
+ output_parts.append(f"**Execution Method:** {result.get('execution_method', 'Unknown')}")
187
+ output_parts.append(f"**Rows Returned:** {result['row_count']}")
188
+
189
+ if result.get("columns"):
190
+ output_parts.append(f"\n**Columns:** {', '.join(result['columns'])}")
191
+
192
+ if result.get("rows"):
193
+ output_parts.append(f"\n**Sample Results (first 10 rows):**")
194
+ output_parts.append("```")
195
+ for i, row in enumerate(result['rows'][:10], 1):
196
+ output_parts.append(f"{i}. {row}")
197
+ output_parts.append("```")
198
+
199
+ if result['row_count'] > 10:
200
+ output_parts.append(f"\n_(Showing 10 of {result['row_count']} rows)_")
201
+
202
+ return "\n".join(output_parts)
203
+ else:
204
+ return f"**❌ Query Execution Failed**\n\n**Error:** {result.get('error', 'Unknown error')}"
205
+
206
+ except Exception as e:
207
+ return f"**❌ Test Error:**\n{str(e)}"
208
+
209
+ def export_to_dbt(sql_code, model_name, description):
210
+ """Export SQL as dbt model with downloadable files"""
211
+
212
+ if not sql_code or not sql_code.strip():
213
+ return "⚠️ No SQL to export. Generate SQL first.", None
214
+
215
+ if not model_name or not model_name.strip():
216
+ return "⚠️ Please provide a model name.", None
217
+
218
+ if not dbt_exporter:
219
+ return "⚠️ dbt Exporter not available.", None
220
+
221
+ try:
222
+ # Clean model name (replace spaces with underscores, lowercase)
223
+ clean_model_name = model_name.strip().lower().replace(' ', '_').replace('-', '_')
224
+ clean_model_name = ''.join(c for c in clean_model_name if c.isalnum() or c == '_')
225
+
226
+ if not clean_model_name:
227
+ return "⚠️ Invalid model name. Use letters, numbers, and underscores only.", None
228
+
229
+ # Export to dbt
230
+ files = dbt_exporter.export_model(
231
+ sql=sql_code,
232
+ model_name=clean_model_name,
233
+ description=description or f"Generated model: {clean_model_name}",
234
+ materialization="table",
235
+ schema="analytics",
236
+ tags="codeflow_generated"
237
+ )
238
+
239
+ # Create ZIP file
240
+ zip_bytes = dbt_exporter.create_zip(files, clean_model_name)
241
+
242
+ # Create success message
243
+ message = f"""**✅ dbt Model Exported Successfully!**
244
+
245
+ **Model Name:** `{clean_model_name}`
246
+ **Files Generated:**
247
+ - `models/{clean_model_name}.sql` - dbt model
248
+ - `models/schema.yml` - Documentation and tests
249
+ - `README.md` - Usage instructions
250
+
251
+ **Next Steps:**
252
+ 1. Download the ZIP file below
253
+ 2. Extract to your dbt project's `models/` directory
254
+ 3. Run: `dbt run --select {clean_model_name}`
255
+ 4. Test: `dbt test --select {clean_model_name}`
256
+
257
+ The model is configured as a table in the `analytics` schema.
258
+ You can modify the configuration at the top of the model file.
259
+ """
260
+
261
+ return message, zip_bytes
262
+
263
+ except Exception as e:
264
+ return f"**❌ Export Error:**\n{str(e)}", None
265
+
266
+ def create_app():
267
+ """Create Gradio interface"""
268
+
269
+ with gr.Blocks(title="CodeFlow AI - Advanced NL-to-SQL") as app:
270
+ gr.Markdown("""
271
+ # 🚀 CodeFlow AI - Advanced Natural Language to SQL Engine
272
+
273
+ Transform plain English into **production-ready, optimized SQL** instantly!
274
+
275
+ **Advanced Features:**
276
+ - ✨ Automatic query optimization
277
+ - 🔍 Schema-aware validation
278
+ - 📊 Support for CTEs, window functions, and complex analytics
279
+ - ⚠️ Intelligent warnings and suggestions
280
+ - 🎯 Multiple SQL dialect support
281
+ - 🔍 **RAG-powered similar patterns** (LlamaIndex)
282
+ - 💡 **Advanced optimization suggestions**
283
+ """)
284
+
285
+ with gr.Row():
286
+ with gr.Column(scale=1):
287
+ gr.Markdown("### 📝 Input")
288
+
289
+ description = gr.Textbox(
290
+ label="Describe your data transformation",
291
+ placeholder="Example: Find top 5 customers by total order value with running totals",
292
+ lines=6
293
+ )
294
+
295
+ dialect = gr.Dropdown(
296
+ choices=["PostgreSQL", "MySQL", "SQLite", "SQL Server"],
297
+ value="PostgreSQL",
298
+ label="SQL Dialect"
299
+ )
300
+
301
+ with gr.Row():
302
+ generate_btn = gr.Button("✨ Generate SQL", variant="primary", scale=2)
303
+ clear_btn = gr.Button("🗑️ Clear", scale=1)
304
+
305
+ with gr.Column(scale=2):
306
+ gr.Markdown("### 💻 Generated SQL")
307
+
308
+ output = gr.Code(
309
+ label="SQL Output",
310
+ language="sql",
311
+ lines=15
312
+ )
313
+
314
+ # Test Query button (SECONDARY SPONSOR - Modal)
315
+ with gr.Row():
316
+ test_btn = gr.Button("🧪 Test Query (Modal)", variant="secondary")
317
+
318
+ gr.Markdown("### 📊 Query Analysis")
319
+
320
+ metadata = gr.Markdown(
321
+ value="",
322
+ label="Analysis"
323
+ )
324
+
325
+ # Test results section
326
+ with gr.Accordion("🧪 Test Results", open=False):
327
+ test_results = gr.Markdown(
328
+ value="Click 'Test Query' to execute the SQL and see results.",
329
+ label="Test Output"
330
+ )
331
+
332
+ # dbt Export section
333
+ gr.Markdown("### 📦 Export to dbt")
334
+ with gr.Row():
335
+ with gr.Column(scale=2):
336
+ model_name_input = gr.Textbox(
337
+ label="Model Name",
338
+ placeholder="customer_analytics",
339
+ value="my_model"
340
+ )
341
+ with gr.Column(scale=3):
342
+ model_desc_input = gr.Textbox(
343
+ label="Model Description",
344
+ placeholder="Describe what this model does...",
345
+ value=""
346
+ )
347
+
348
+ export_btn = gr.Button("📦 Export to dbt", variant="secondary")
349
+
350
+ with gr.Accordion("📦 Export Status", open=False):
351
+ export_status = gr.Markdown(
352
+ value="Configure model details above and click 'Export to dbt' to generate production-ready dbt files.",
353
+ label="Export Output"
354
+ )
355
+ download_file = gr.File(label="Download dbt Model", visible=False)
356
+
357
+ # Example queries
358
+ gr.Markdown("### 💡 Try These Advanced Examples")
359
+ gr.Examples(
360
+ examples=[
361
+ ["Find top 10 customers by total order value with their rank"],
362
+ ["Show monthly revenue trends with year-over-year comparison"],
363
+ ["Get customers who have never placed an order"],
364
+ ["Calculate running total of sales by date for each product"],
365
+ ["Find the 3 most popular products in each category"],
366
+ ["Show customers with above-average order values"],
367
+ ["List orders with customer details, handling missing customers gracefully"],
368
+ ["Calculate customer cohorts based on first purchase month"],
369
+ ["Find products that were ordered in 2023 but not in 2024"],
370
+ ["Show daily order count with 7-day moving average"]
371
+ ],
372
+ inputs=[description]
373
+ )
374
+
375
+ # Event handlers
376
+ generate_btn.click(
377
+ fn=generate_sql,
378
+ inputs=[description, dialect],
379
+ outputs=[output, metadata, gr.Textbox(visible=False)]
380
+ )
381
+
382
+ test_btn.click(
383
+ fn=test_sql_query,
384
+ inputs=[output],
385
+ outputs=[test_results]
386
+ )
387
+
388
+ def handle_export(sql_code, model_name, description):
389
+ """Handle dbt export and show/hide download button"""
390
+ message, zip_bytes = export_to_dbt(sql_code, model_name, description)
391
+ if zip_bytes:
392
+ # Save to temp file for download
393
+ import tempfile
394
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.zip', mode='wb') as f:
395
+ f.write(zip_bytes)
396
+ temp_path = f.name
397
+ return message, gr.File(value=temp_path, visible=True)
398
+ else:
399
+ return message, gr.File(visible=False)
400
+
401
+ export_btn.click(
402
+ fn=handle_export,
403
+ inputs=[output, model_name_input, model_desc_input],
404
+ outputs=[export_status, download_file]
405
+ )
406
+
407
+ clear_btn.click(
408
+ fn=lambda: ("", "", "", "Click 'Test Query' to execute the SQL and see results.",
409
+ "Configure model details above and click 'Export to dbt' to generate production-ready dbt files.",
410
+ gr.File(visible=False)),
411
+ outputs=[description, output, metadata, test_results, export_status, download_file]
412
+ )
413
+
414
+ # Schema display
415
+ with gr.Accordion("📋 Database Schema", open=False):
416
+ schema_md = "## Available Tables and Columns\n\n"
417
+ for table, columns in DB_SCHEMA.items():
418
+ schema_md += f"### 📊 {table}\n\n"
419
+ schema_md += "| Column | Type | Constraints |\n"
420
+ schema_md += "|--------|------|-------------|\n"
421
+ for col in columns:
422
+ constraints = []
423
+ if col.get('primary_key'):
424
+ constraints.append("PRIMARY KEY")
425
+ if not col.get('nullable', True):
426
+ constraints.append("NOT NULL")
427
+ constraint_str = ", ".join(constraints) if constraints else "-"
428
+ schema_md += f"| {col['name']} | {col['type']} | {constraint_str} |\n"
429
+ schema_md += "\n"
430
+
431
+ gr.Markdown(schema_md)
432
+
433
+ gr.Markdown("---")
434
+ gr.Markdown("""
435
+ **🏆 CodeFlow AI - Advanced NL-to-SQL Engine**
436
+
437
+ **Core Features:**
438
+ - 🧠 Powered by Claude 3 Opus (Anthropic)
439
+ - 🔍 **LlamaIndex RAG** - Similar pattern suggestions from template library
440
+ - ✨ Automatic query optimization with validation
441
+ - 📊 Complex query support (CTEs, Window Functions, Subqueries)
442
+ - ⚠️ Intelligent error handling and warnings
443
+
444
+ **Sponsor Integrations:**
445
+ - 🎯 **LlamaIndex** - RAG-powered template matching (PRIMARY SPONSOR)
446
+ - ⚡ **Modal** - Serverless SQL testing (coming soon)
447
+
448
+ Built for: MCP 1st Birthday Hackathon
449
+ """)
450
+
451
+ return app
452
+
453
+ if __name__ == "__main__":
454
+ print("\n" + "="*50)
455
+ print("Starting CodeFlow AI - Advanced NL-to-SQL Engine...")
456
+ print("="*50 + "\n")
457
+
458
+ app = create_app()
459
+ app.launch(share=False)
export/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Export module for CodeFlow AI
3
+ Provides dbt model generation and other export formats
4
+ """
export/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (278 Bytes). View file
 
export/__pycache__/dbt_exporter.cpython-311.pyc ADDED
Binary file (8.87 kB). View file
 
export/dbt_exporter.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ dbt Exporter for CodeFlow AI
3
+ Generates production-ready dbt models from SQL queries
4
+ """
5
+
6
+ import io
7
+ import zipfile
8
+ from datetime import datetime
9
+ from typing import Dict, Optional
10
+ from jinja2 import Template
11
+
12
+
13
+ class DBTExporter:
14
+ """
15
+ Export SQL queries as dbt models
16
+ Generates model.sql and schema.yml files
17
+ """
18
+
19
+ def __init__(self):
20
+ # Use {0}, {1} placeholders instead of Jinja {{ }} to avoid conflict with dbt
21
+ self.model_template = """{{{{
22
+ config(
23
+ materialized='{materialization}',
24
+ schema='{schema}',
25
+ tags=['{tags}']
26
+ )
27
+ }}}}
28
+
29
+ /*
30
+ Model: {model_name}
31
+ Description: {description}
32
+ Generated: {generated_date}
33
+ Generated by: CodeFlow AI
34
+ */
35
+
36
+ {sql_query}
37
+ """
38
+
39
+ self.schema_template = """version: 2
40
+
41
+ models:
42
+ - name: {{ model_name }}
43
+ description: {{ description }}
44
+ columns:
45
+ {% for column in columns %}
46
+ - name: {{ column.name }}
47
+ description: {{ column.description }}
48
+ {% if column.tests %}
49
+ tests:
50
+ {% for test in column.tests %}
51
+ - {{ test }}
52
+ {% endfor %}
53
+ {% endif %}
54
+ {% endfor %}
55
+ """
56
+
57
+ def export_model(
58
+ self,
59
+ sql: str,
60
+ model_name: str,
61
+ description: str = "",
62
+ materialization: str = "table",
63
+ schema: str = "analytics",
64
+ tags: str = "codeflow_generated",
65
+ columns: Optional[list] = None
66
+ ) -> Dict[str, str]:
67
+ """
68
+ Export SQL as dbt model
69
+
70
+ Args:
71
+ sql: SQL query to export
72
+ model_name: Name for the dbt model
73
+ description: Model description
74
+ materialization: dbt materialization (table, view, incremental)
75
+ schema: Target schema name
76
+ tags: Model tags
77
+ columns: List of column definitions
78
+
79
+ Returns:
80
+ Dict with model.sql and schema.yml content
81
+ """
82
+
83
+ # Clean SQL (remove CodeFlow comments)
84
+ clean_sql = self._clean_sql(sql)
85
+
86
+ # Generate model.sql using format() instead of Jinja2 to avoid dbt {{ }} conflict
87
+ model_content = self.model_template.format(
88
+ materialization=materialization,
89
+ schema=schema,
90
+ tags=tags,
91
+ model_name=model_name,
92
+ description=description or f"Generated model: {model_name}",
93
+ generated_date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
94
+ sql_query=clean_sql
95
+ )
96
+
97
+ # Generate schema.yml
98
+ if not columns:
99
+ # Auto-detect columns from SQL (basic)
100
+ columns = self._detect_columns(clean_sql)
101
+
102
+ schema_template = Template(self.schema_template)
103
+ schema_content = schema_template.render(
104
+ model_name=model_name,
105
+ description=description or f"Generated model: {model_name}",
106
+ columns=columns
107
+ )
108
+
109
+ return {
110
+ "model.sql": model_content,
111
+ "schema.yml": schema_content
112
+ }
113
+
114
+ def _clean_sql(self, sql: str) -> str:
115
+ """Remove CodeFlow-specific comments from SQL"""
116
+ lines = []
117
+ for line in sql.split('\n'):
118
+ stripped = line.strip()
119
+ # Skip CodeFlow header comments
120
+ if stripped.startswith('-- CodeFlow'):
121
+ continue
122
+ if stripped.startswith('-- Dialect:'):
123
+ continue
124
+ if stripped.startswith('-- Query Type:'):
125
+ continue
126
+ lines.append(line)
127
+
128
+ return '\n'.join(lines).strip()
129
+
130
+ def _detect_columns(self, sql: str) -> list:
131
+ """
132
+ Basic column detection from SQL
133
+ Looks for SELECT clause columns
134
+ """
135
+ columns = []
136
+
137
+ # Find SELECT clause (very basic parser)
138
+ sql_upper = sql.upper()
139
+ if 'SELECT' not in sql_upper:
140
+ return columns
141
+
142
+ # Extract between SELECT and FROM
143
+ select_idx = sql_upper.find('SELECT')
144
+ from_idx = sql_upper.find('FROM', select_idx)
145
+
146
+ if from_idx == -1:
147
+ from_idx = len(sql)
148
+
149
+ select_clause = sql[select_idx + 6:from_idx].strip()
150
+
151
+ # Split by comma (basic - doesn't handle nested commas)
152
+ parts = select_clause.split(',')
153
+
154
+ for part in parts[:10]: # Limit to first 10 columns
155
+ part = part.strip()
156
+ if not part:
157
+ continue
158
+
159
+ # Extract column name (after AS if present)
160
+ if ' AS ' in part.upper():
161
+ col_name = part.upper().split(' AS ')[-1].strip()
162
+ elif ' ' in part:
163
+ # Take last word
164
+ col_name = part.split()[-1].strip()
165
+ else:
166
+ col_name = part
167
+
168
+ # Clean column name
169
+ col_name = col_name.replace('`', '').replace('"', '').replace("'", "")
170
+
171
+ if col_name and col_name != '*':
172
+ columns.append({
173
+ "name": col_name.lower(),
174
+ "description": f"Column: {col_name}",
175
+ "tests": ["not_null"] if "id" in col_name.lower() else []
176
+ })
177
+
178
+ return columns
179
+
180
+ def create_zip(self, files: Dict[str, str], model_name: str) -> bytes:
181
+ """
182
+ Create a ZIP file containing the dbt files
183
+
184
+ Args:
185
+ files: Dict of filename -> content
186
+ model_name: Model name for directory structure
187
+
188
+ Returns:
189
+ ZIP file as bytes
190
+ """
191
+ zip_buffer = io.BytesIO()
192
+
193
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
194
+ # Create models directory structure
195
+ for filename, content in files.items():
196
+ if filename.endswith('.sql'):
197
+ path = f"models/{model_name}.sql"
198
+ elif filename.endswith('.yml'):
199
+ path = f"models/schema.yml"
200
+ else:
201
+ path = f"models/{filename}"
202
+
203
+ zip_file.writestr(path, content)
204
+
205
+ # Add README
206
+ readme = f"""# dbt Model: {model_name}
207
+
208
+ Generated by CodeFlow AI on {datetime.now().strftime("%Y-%m-%d")}
209
+
210
+ ## Files Included
211
+
212
+ - `models/{model_name}.sql` - The dbt model
213
+ - `models/schema.yml` - Model and column documentation
214
+
215
+ ## Usage
216
+
217
+ 1. Copy these files to your dbt project's `models/` directory
218
+ 2. Run `dbt run --select {model_name}` to execute
219
+ 3. Run `dbt test --select {model_name}` to run tests
220
+
221
+ ## Configuration
222
+
223
+ You can modify the model configuration at the top of {model_name}.sql:
224
+ - materialization: table, view, or incremental
225
+ - schema: target schema name
226
+ - tags: for organizing models
227
+
228
+ For more information, visit: https://docs.getdbt.com/
229
+ """
230
+ zip_file.writestr("README.md", readme)
231
+
232
+ zip_buffer.seek(0)
233
+ return zip_buffer.getvalue()
234
+
235
+
236
+ # Singleton instance
237
+ _dbt_exporter = None
238
+
239
+ def get_dbt_exporter() -> DBTExporter:
240
+ """Get or create the global dbt exporter instance"""
241
+ global _dbt_exporter
242
+ if _dbt_exporter is None:
243
+ _dbt_exporter = DBTExporter()
244
+ return _dbt_exporter
nl_parser.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import anthropic
2
+ import json
3
+ import os
4
+ import re
5
+ from dotenv import load_dotenv
6
+
7
+ load_dotenv()
8
+
9
+ class NaturalLanguageParser:
10
+ """Advanced Natural Language to SQL Engine using Claude"""
11
+
12
+ def __init__(self):
13
+ api_key = os.getenv("ANTHROPIC_API_KEY")
14
+ if not api_key:
15
+ raise ValueError("ANTHROPIC_API_KEY not found in .env file!")
16
+ self.client = anthropic.Anthropic(api_key=api_key)
17
+
18
+ def generate_sql(self, description, schema, dialect="PostgreSQL"):
19
+ """
20
+ Generate complete, optimized SQL directly from natural language.
21
+ This is the main engine that handles all SQL generation logic.
22
+ """
23
+
24
+ schema_text = self._format_schema(schema)
25
+
26
+ prompt = f"""You are an advanced Natural-Language-to-SQL Engine.
27
+ Your job is to convert user instructions into correct, executable, efficient SQL queries, based solely on the provided database schema.
28
+
29
+ 🔥 Core Responsibilities
30
+
31
+ 1. NEVER hallucinate tables or columns. Only use what exists in the provided schema.
32
+ 2. Follow the SQL dialect: {dialect}
33
+ 3. Validate user intent and generate the best query, even if their natural language is unclear.
34
+ 4. Fix common SQL mistakes:
35
+ - Use IS NULL / IS NOT NULL (never = NULL)
36
+ - Use >= and < for date ranges instead of BETWEEN
37
+ - Proper JOIN syntax
38
+ - Correct aggregate/grouping logic
39
+ 5. Optimize the SQL:
40
+ - Use proper filters
41
+ - Use EXISTS/NOT EXISTS for subqueries
42
+ - Use CTEs for clarity in complex queries
43
+ - Avoid unnecessary computation
44
+ 6. For complex analysis (cohorts, trends, rankings, window functions):
45
+ - Use Common Table Expressions (CTEs)
46
+ - Use window functions when appropriate
47
+
48
+ 🗃️ Available Database Schema:
49
+ {schema_text}
50
+
51
+ 👤 User Request: {description}
52
+
53
+ 🎯 SQL Construction Rules:
54
+
55
+ WHERE clauses:
56
+ - Use IS NULL / IS NOT NULL, not = 'NULL'
57
+ - For date ranges use >= and < instead of BETWEEN
58
+
59
+ Aggregations:
60
+ - GROUP BY all non-aggregated fields
61
+ - Avoid GROUP BY unnecessary columns
62
+
63
+ Joins:
64
+ - Prefer explicit JOIN syntax
65
+ - Use LEFT JOIN for "missing data" queries
66
+ - Always specify join conditions clearly
67
+
68
+ Subqueries:
69
+ - Prefer EXISTS/NOT EXISTS for performance
70
+ - Use CTEs for readability in complex queries
71
+
72
+ Window Functions (use when user asks for):
73
+ - Top N per group
74
+ - Rankings
75
+ - Running totals
76
+ - Comparisons to averages
77
+ - Rolling windows
78
+
79
+ 📋 Output Format:
80
+
81
+ Return a JSON object with this exact structure:
82
+ {{
83
+ "sql": "the complete SQL query here",
84
+ "explanation": "brief explanation of what the query does",
85
+ "query_type": "simple|aggregate|join|window|cte|analytical",
86
+ "warnings": ["any warnings about schema limitations or assumptions"],
87
+ "optimizations": ["list of optimizations applied"]
88
+ }}
89
+
90
+ CRITICAL RULES FOR JSON OUTPUT:
91
+ - Return ONLY valid JSON (no markdown, no code blocks, no extra text)
92
+ - Escape ALL special characters in the SQL string:
93
+ * Newlines must be \\n
94
+ * Quotes must be \\"
95
+ * Backslashes must be \\\\
96
+ - The "sql" field must be a single-line string with \\n for line breaks
97
+ - Always end SQL with semicolon
98
+ - If the request is impossible with the given schema, set "sql" to "-- ERROR: <explanation>" and explain in "warnings"
99
+
100
+ Generate the SQL query now:"""
101
+
102
+ try:
103
+ response = self.client.messages.create(
104
+ model="claude-3-opus-20240229",
105
+ max_tokens=4000,
106
+ messages=[{"role": "user", "content": prompt}]
107
+ )
108
+
109
+ content = response.content[0].text.strip()
110
+
111
+ # Remove markdown code blocks if present
112
+ content = content.replace("```json", "").replace("```", "").strip()
113
+
114
+ # Try to parse JSON
115
+ try:
116
+ result = json.loads(content)
117
+
118
+ # Ensure all required fields exist
119
+ if "sql" not in result or not result["sql"]:
120
+ result["sql"] = "-- ERROR: No SQL generated"
121
+ if "explanation" not in result:
122
+ result["explanation"] = "SQL query generated"
123
+ if "query_type" not in result:
124
+ result["query_type"] = "select"
125
+ if "warnings" not in result:
126
+ result["warnings"] = []
127
+ if "optimizations" not in result:
128
+ result["optimizations"] = []
129
+
130
+ return result
131
+
132
+ except json.JSONDecodeError as e:
133
+ # If JSON parsing fails, try to extract components manually using regex
134
+ print(f"JSON parsing failed: {e}, attempting manual extraction...")
135
+
136
+ # Try to extract SQL between "sql": " and next quote
137
+ sql_match = re.search(r'"sql"\s*:\s*"((?:[^"\\]|\\.|\\n)*)"', content, re.DOTALL)
138
+ if sql_match:
139
+ sql = sql_match.group(1)
140
+ # Unescape the JSON string
141
+ sql = sql.replace('\\n', '\n').replace('\\"', '"').replace('\\\\', '\\')
142
+ else:
143
+ # Try alternative format or use entire content
144
+ sql = content
145
+
146
+ # Try to extract explanation
147
+ expl_match = re.search(r'"explanation"\s*:\s*"((?:[^"\\]|\\.)*)"', content, re.DOTALL)
148
+ explanation = expl_match.group(1) if expl_match else "SQL generated (with parsing issues)"
149
+
150
+ # Try to extract query type
151
+ type_match = re.search(r'"query_type"\s*:\s*"([^"]*)"', content)
152
+ query_type = type_match.group(1) if type_match else "select"
153
+
154
+ result = {
155
+ "sql": sql,
156
+ "explanation": explanation,
157
+ "query_type": query_type,
158
+ "warnings": ["JSON parsing issue - SQL may need review"],
159
+ "optimizations": []
160
+ }
161
+
162
+ return result
163
+
164
+ except Exception as e:
165
+ return {
166
+ "sql": f"-- ERROR: {str(e)}",
167
+ "explanation": "An error occurred during SQL generation",
168
+ "query_type": "error",
169
+ "warnings": [str(e)],
170
+ "optimizations": []
171
+ }
172
+
173
+ def _format_schema(self, schema):
174
+ """Format schema for prompt"""
175
+ lines = ["Tables and Columns:"]
176
+ for table, columns in schema.items():
177
+ lines.append(f"\n📊 {table}")
178
+ for col in columns:
179
+ nullable = "NULL" if col.get('nullable', True) else "NOT NULL"
180
+ pk = " (PRIMARY KEY)" if col.get('primary_key', False) else ""
181
+ lines.append(f" - {col['name']}: {col['type']} {nullable}{pk}")
182
+ return "\n".join(lines)
183
+
184
+ # Legacy method for backward compatibility
185
+ def parse(self, description, schema):
186
+ """Legacy method - redirects to generate_sql"""
187
+ result = self.generate_sql(description, schema)
188
+ # Return just the SQL for backward compatibility
189
+ return {"raw_sql": result.get("sql", ""), "metadata": result}
rag/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ RAG (Retrieval-Augmented Generation) module for CodeFlow AI
3
+ Uses LlamaIndex to provide similar ETL pattern suggestions
4
+ """
rag/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (309 Bytes). View file
 
rag/__pycache__/template_store.cpython-311.pyc ADDED
Binary file (10.2 kB). View file
 
rag/sample_templates/01_customer_aggregation.sql ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Customer Order Aggregation
2
+ -- Pattern: Aggregate metrics by customer dimension
3
+ -- Use Case: Calculate total order value, count, average per customer
4
+
5
+ SELECT
6
+ c.customer_id,
7
+ c.name,
8
+ c.email,
9
+ COUNT(o.order_id) as total_orders,
10
+ SUM(o.total_amount) as total_spent,
11
+ AVG(o.total_amount) as avg_order_value,
12
+ MIN(o.order_date) as first_order_date,
13
+ MAX(o.order_date) as last_order_date
14
+ FROM customers c
15
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
16
+ GROUP BY c.customer_id, c.name, c.email
17
+ ORDER BY total_spent DESC;
18
+
19
+ -- Key Concepts:
20
+ -- - LEFT JOIN to include customers with no orders
21
+ -- - Multiple aggregations (COUNT, SUM, AVG, MIN, MAX)
22
+ -- - GROUP BY all non-aggregated columns
23
+ -- - ORDER BY to rank results
rag/sample_templates/02_date_filtering.sql ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Date Range Filtering
2
+ -- Pattern: Filter records within specific date ranges
3
+ -- Use Case: Get orders for specific time periods
4
+
5
+ SELECT
6
+ order_id,
7
+ customer_id,
8
+ order_date,
9
+ total_amount,
10
+ status
11
+ FROM orders
12
+ WHERE order_date >= '2024-01-01'
13
+ AND order_date < '2024-04-01' -- Use < instead of <= for exclusive end
14
+ ORDER BY order_date DESC;
15
+
16
+ -- Key Concepts:
17
+ -- - Use >= and < for date ranges (more precise than BETWEEN)
18
+ -- - BETWEEN is inclusive on both ends, which can cause issues
19
+ -- - Always use ISO format YYYY-MM-DD for dates
20
+ -- - Consider timezone implications in production
21
+
22
+ -- Alternative with BETWEEN (less preferred):
23
+ -- WHERE order_date BETWEEN '2024-01-01' AND '2024-03-31'
rag/sample_templates/03_window_functions.sql ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Window Functions for Ranking
2
+ -- Pattern: Rank records within partitions
3
+ -- Use Case: Top N per category, rankings, row numbers
4
+
5
+ -- Example 1: Rank customers by total orders in each city
6
+ SELECT
7
+ customer_id,
8
+ name,
9
+ city,
10
+ total_orders,
11
+ ROW_NUMBER() OVER (PARTITION BY city ORDER BY total_orders DESC) as row_num,
12
+ RANK() OVER (PARTITION BY city ORDER BY total_orders DESC) as rank,
13
+ DENSE_RANK() OVER (PARTITION BY city ORDER BY total_orders DESC) as dense_rank
14
+ FROM (
15
+ SELECT
16
+ c.customer_id,
17
+ c.name,
18
+ c.city,
19
+ COUNT(o.order_id) as total_orders
20
+ FROM customers c
21
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
22
+ GROUP BY c.customer_id, c.name, c.city
23
+ ) customer_metrics;
24
+
25
+ -- Example 2: Top 3 customers per city
26
+ SELECT *
27
+ FROM (
28
+ SELECT
29
+ customer_id,
30
+ name,
31
+ city,
32
+ total_orders,
33
+ ROW_NUMBER() OVER (PARTITION BY city ORDER BY total_orders DESC) as rn
34
+ FROM customer_metrics
35
+ ) ranked
36
+ WHERE rn <= 3;
37
+
38
+ -- Key Concepts:
39
+ -- - ROW_NUMBER(): Unique sequential number (1,2,3,4...)
40
+ -- - RANK(): Same rank for ties, skips next rank (1,2,2,4...)
41
+ -- - DENSE_RANK(): Same rank for ties, no gaps (1,2,2,3...)
42
+ -- - PARTITION BY: Restart ranking within each group
43
+ -- - ORDER BY: Defines ranking order within partition
rag/sample_templates/04_running_totals.sql ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Running Totals and Cumulative Sums
2
+ -- Pattern: Calculate cumulative values over ordered records
3
+ -- Use Case: Running balance, cumulative revenue, YTD totals
4
+
5
+ SELECT
6
+ order_date,
7
+ customer_id,
8
+ total_amount,
9
+ SUM(total_amount) OVER (
10
+ ORDER BY order_date
11
+ ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
12
+ ) as running_total,
13
+ SUM(total_amount) OVER (
14
+ PARTITION BY customer_id
15
+ ORDER BY order_date
16
+ ) as customer_running_total,
17
+ AVG(total_amount) OVER (
18
+ ORDER BY order_date
19
+ ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
20
+ ) as moving_avg_7day
21
+ FROM orders
22
+ ORDER BY order_date;
23
+
24
+ -- Key Concepts:
25
+ -- - SUM() OVER (): Running total across all rows
26
+ -- - PARTITION BY: Separate running totals per customer
27
+ -- - ROWS BETWEEN: Define window frame
28
+ -- * UNBOUNDED PRECEDING: From start
29
+ -- * CURRENT ROW: Up to current row
30
+ -- * N PRECEDING: Previous N rows
31
+ -- - Useful for trends, YTD calculations, moving averages
rag/sample_templates/05_top_n_per_group.sql ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Top N Records Per Group
2
+ -- Pattern: Get top performers within each category/partition
3
+ -- Use Case: Best sellers per category, top customers per region
4
+
5
+ WITH ranked_products AS (
6
+ SELECT
7
+ p.product_id,
8
+ p.name,
9
+ p.category,
10
+ p.price,
11
+ COUNT(oi.order_id) as times_ordered,
12
+ SUM(oi.quantity) as total_quantity_sold,
13
+ SUM(oi.quantity * oi.unit_price) as total_revenue,
14
+ ROW_NUMBER() OVER (
15
+ PARTITION BY p.category
16
+ ORDER BY SUM(oi.quantity * oi.unit_price) DESC
17
+ ) as revenue_rank
18
+ FROM products p
19
+ LEFT JOIN order_items oi ON p.product_id = oi.product_id
20
+ GROUP BY p.product_id, p.name, p.category, p.price
21
+ )
22
+ SELECT
23
+ category,
24
+ product_id,
25
+ name,
26
+ total_revenue,
27
+ total_quantity_sold,
28
+ revenue_rank
29
+ FROM ranked_products
30
+ WHERE revenue_rank <= 3
31
+ ORDER BY category, revenue_rank;
32
+
33
+ -- Key Concepts:
34
+ -- - CTE for better readability
35
+ -- - PARTITION BY category to rank within each group
36
+ -- - Filter WHERE rank <= N to get top N
37
+ -- - Useful for identifying best performers in each segment
rag/sample_templates/06_left_join_missing.sql ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Finding Missing Data with LEFT JOIN
2
+ -- Pattern: Identify records that don't have matching records in related table
3
+ -- Use Case: Customers without orders, products never sold, orphaned records
4
+
5
+ -- Example 1: Customers who have never placed an order
6
+ SELECT
7
+ c.customer_id,
8
+ c.name,
9
+ c.email,
10
+ c.registration_date
11
+ FROM customers c
12
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
13
+ WHERE o.order_id IS NULL
14
+ ORDER BY c.registration_date DESC;
15
+
16
+ -- Example 2: Products that have never been ordered
17
+ SELECT
18
+ p.product_id,
19
+ p.name,
20
+ p.category,
21
+ p.price,
22
+ p.stock_quantity
23
+ FROM products p
24
+ LEFT JOIN order_items oi ON p.product_id = oi.product_id
25
+ WHERE oi.order_item_id IS NULL;
26
+
27
+ -- Key Concepts:
28
+ -- - LEFT JOIN keeps all records from left table
29
+ -- - WHERE column IS NULL finds unmatched records
30
+ -- - Must check a column from right table that cannot be NULL (like primary key)
31
+ -- - Alternative: NOT EXISTS (often faster for large datasets)
32
+
33
+ -- Alternative using NOT EXISTS:
34
+ SELECT
35
+ c.customer_id,
36
+ c.name,
37
+ c.email
38
+ FROM customers c
39
+ WHERE NOT EXISTS (
40
+ SELECT 1
41
+ FROM orders o
42
+ WHERE o.customer_id = c.customer_id
43
+ );
rag/sample_templates/07_exists_not_exists.sql ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: EXISTS and NOT EXISTS Set Operations
2
+ -- Pattern: Efficient subquery filtering for existence checks
3
+ -- Use Case: Find records that match/don't match conditions in other tables
4
+
5
+ -- Example 1: Customers who placed orders in 2024
6
+ SELECT
7
+ c.customer_id,
8
+ c.name,
9
+ c.email
10
+ FROM customers c
11
+ WHERE EXISTS (
12
+ SELECT 1
13
+ FROM orders o
14
+ WHERE o.customer_id = c.customer_id
15
+ AND o.order_date >= '2024-01-01'
16
+ AND o.order_date < '2025-01-01'
17
+ );
18
+
19
+ -- Example 2: Products ordered in 2023 but not in 2024
20
+ SELECT
21
+ p.product_id,
22
+ p.name,
23
+ p.category
24
+ FROM products p
25
+ WHERE EXISTS (
26
+ SELECT 1
27
+ FROM order_items oi
28
+ JOIN orders o ON oi.order_id = o.order_id
29
+ WHERE oi.product_id = p.product_id
30
+ AND o.order_date >= '2023-01-01'
31
+ AND o.order_date < '2024-01-01'
32
+ )
33
+ AND NOT EXISTS (
34
+ SELECT 1
35
+ FROM order_items oi
36
+ JOIN orders o ON oi.order_id = o.order_id
37
+ WHERE oi.product_id = p.product_id
38
+ AND o.order_date >= '2024-01-01'
39
+ AND o.order_date < '2025-01-01'
40
+ );
41
+
42
+ -- Key Concepts:
43
+ -- - EXISTS returns TRUE if subquery returns any rows
44
+ -- - More efficient than IN for large datasets
45
+ -- - Better NULL handling than IN/NOT IN
46
+ -- - Short-circuits: stops at first match
47
+ -- - Use SELECT 1 (constant) instead of SELECT * for efficiency
rag/sample_templates/08_cte_multi_step.sql ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Multi-Step CTEs for Complex Analysis
2
+ -- Pattern: Break complex queries into logical steps
3
+ -- Use Case: Complex calculations, data transformation pipelines
4
+
5
+ WITH
6
+ -- Step 1: Calculate customer metrics
7
+ customer_metrics AS (
8
+ SELECT
9
+ c.customer_id,
10
+ c.name,
11
+ COUNT(o.order_id) as total_orders,
12
+ SUM(o.total_amount) as total_spent,
13
+ MIN(o.order_date) as first_order_date,
14
+ MAX(o.order_date) as last_order_date
15
+ FROM customers c
16
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
17
+ GROUP BY c.customer_id, c.name
18
+ ),
19
+ -- Step 2: Calculate overall averages
20
+ overall_stats AS (
21
+ SELECT
22
+ AVG(total_spent) as avg_customer_value,
23
+ AVG(total_orders) as avg_orders_per_customer
24
+ FROM customer_metrics
25
+ ),
26
+ -- Step 3: Classify customers
27
+ customer_segments AS (
28
+ SELECT
29
+ cm.*,
30
+ os.avg_customer_value,
31
+ CASE
32
+ WHEN cm.total_spent > os.avg_customer_value * 2 THEN 'VIP'
33
+ WHEN cm.total_spent > os.avg_customer_value THEN 'High Value'
34
+ WHEN cm.total_spent > 0 THEN 'Regular'
35
+ ELSE 'Inactive'
36
+ END as segment
37
+ FROM customer_metrics cm
38
+ CROSS JOIN overall_stats os
39
+ )
40
+ -- Final output
41
+ SELECT
42
+ segment,
43
+ COUNT(*) as customer_count,
44
+ AVG(total_spent) as avg_spent,
45
+ AVG(total_orders) as avg_orders
46
+ FROM customer_segments
47
+ GROUP BY segment
48
+ ORDER BY avg_spent DESC;
49
+
50
+ -- Key Concepts:
51
+ -- - WITH clause defines multiple CTEs (Common Table Expressions)
52
+ -- - Each CTE builds on previous ones
53
+ -- - Better readability than nested subqueries
54
+ -- - Can reference previous CTEs in later ones
55
+ -- - Improves maintainability and debugging
rag/sample_templates/09_cohort_analysis.sql ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Cohort Analysis
2
+ -- Pattern: Group customers by acquisition period and track behavior
3
+ -- Use Case: First purchase cohorts, retention analysis, lifetime value
4
+
5
+ WITH first_purchases AS (
6
+ SELECT
7
+ customer_id,
8
+ MIN(order_date) as cohort_month,
9
+ DATE_TRUNC('month', MIN(order_date)) as cohort_date
10
+ FROM orders
11
+ GROUP BY customer_id
12
+ ),
13
+ customer_cohorts AS (
14
+ SELECT
15
+ o.customer_id,
16
+ o.order_date,
17
+ o.total_amount,
18
+ fp.cohort_date,
19
+ DATE_TRUNC('month', o.order_date) as order_month,
20
+ EXTRACT(YEAR FROM AGE(o.order_date, fp.cohort_date)) * 12 +
21
+ EXTRACT(MONTH FROM AGE(o.order_date, fp.cohort_date)) as months_since_first
22
+ FROM orders o
23
+ JOIN first_purchases fp ON o.customer_id = fp.customer_id
24
+ )
25
+ SELECT
26
+ cohort_date,
27
+ months_since_first,
28
+ COUNT(DISTINCT customer_id) as active_customers,
29
+ SUM(total_amount) as cohort_revenue,
30
+ AVG(total_amount) as avg_order_value
31
+ FROM customer_cohorts
32
+ GROUP BY cohort_date, months_since_first
33
+ ORDER BY cohort_date, months_since_first;
34
+
35
+ -- Key Concepts:
36
+ -- - Cohorts: Groups defined by shared characteristic (e.g., signup month)
37
+ -- - Track behavior over time relative to cohort start
38
+ -- - DATE_TRUNC for period grouping
39
+ -- - AGE function for time calculations
40
+ -- - Useful for retention and LTV analysis
rag/sample_templates/10_yoy_comparison.sql ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Year-over-Year Comparison
2
+ -- Pattern: Compare metrics across time periods
3
+ -- Use Case: Revenue growth, seasonal trends, period comparisons
4
+
5
+ WITH monthly_revenue AS (
6
+ SELECT
7
+ DATE_TRUNC('month', order_date) as month,
8
+ EXTRACT(YEAR FROM order_date) as year,
9
+ EXTRACT(MONTH FROM order_date) as month_num,
10
+ SUM(total_amount) as revenue,
11
+ COUNT(DISTINCT customer_id) as unique_customers
12
+ FROM orders
13
+ GROUP BY DATE_TRUNC('month', order_date),
14
+ EXTRACT(YEAR FROM order_date),
15
+ EXTRACT(MONTH FROM order_date)
16
+ )
17
+ SELECT
18
+ curr.month as current_month,
19
+ curr.revenue as current_revenue,
20
+ prev.revenue as previous_year_revenue,
21
+ curr.revenue - prev.revenue as revenue_change,
22
+ ROUND(((curr.revenue - prev.revenue) / prev.revenue * 100), 2) as growth_pct,
23
+ curr.unique_customers as current_customers,
24
+ prev.unique_customers as previous_year_customers
25
+ FROM monthly_revenue curr
26
+ LEFT JOIN monthly_revenue prev
27
+ ON curr.month_num = prev.month_num
28
+ AND curr.year = prev.year + 1
29
+ WHERE prev.revenue IS NOT NULL
30
+ ORDER BY curr.month DESC;
31
+
32
+ -- Key Concepts:
33
+ -- - DATE_TRUNC for period aggregation
34
+ -- - Self-join to compare same periods across years
35
+ -- - Percentage change calculation
36
+ -- - EXTRACT for getting year/month components
37
+ -- - Useful for trend analysis and forecasting
rag/sample_templates/11_moving_average.sql ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Moving Average (Rolling Average)
2
+ -- Pattern: Calculate average over sliding time window
3
+ -- Use Case: Smooth out fluctuations, identify trends, 7-day MA, 30-day MA
4
+
5
+ SELECT
6
+ order_date,
7
+ daily_revenue,
8
+ AVG(daily_revenue) OVER (
9
+ ORDER BY order_date
10
+ ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
11
+ ) as moving_avg_7day,
12
+ AVG(daily_revenue) OVER (
13
+ ORDER BY order_date
14
+ ROWS BETWEEN 29 PRECEDING AND CURRENT ROW
15
+ ) as moving_avg_30day,
16
+ daily_order_count,
17
+ AVG(daily_order_count) OVER (
18
+ ORDER BY order_date
19
+ ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
20
+ ) as avg_orders_7day
21
+ FROM (
22
+ SELECT
23
+ DATE(order_date) as order_date,
24
+ SUM(total_amount) as daily_revenue,
25
+ COUNT(*) as daily_order_count
26
+ FROM orders
27
+ GROUP BY DATE(order_date)
28
+ ) daily_stats
29
+ ORDER BY order_date;
30
+
31
+ -- Key Concepts:
32
+ -- - Window function with ROWS BETWEEN for sliding window
33
+ -- - N PRECEDING means previous N rows
34
+ -- - CURRENT ROW includes the current row
35
+ -- - For 7-day MA: use 6 PRECEDING (includes current = 7 total)
36
+ -- - Useful for smoothing volatile metrics
rag/sample_templates/12_self_join.sql ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Self-Join for Hierarchical or Sequential Data
2
+ -- Pattern: Join table to itself to find relationships within same table
3
+ -- Use Case: Manager-employee, sequential orders, referrals, product recommendations
4
+
5
+ -- Example 1: Find customers who ordered same product
6
+ SELECT DISTINCT
7
+ c1.customer_id as customer1,
8
+ c1.name as customer1_name,
9
+ c2.customer_id as customer2,
10
+ c2.name as customer2_name,
11
+ oi1.product_id,
12
+ p.name as product_name
13
+ FROM order_items oi1
14
+ JOIN order_items oi2 ON oi1.product_id = oi2.product_id
15
+ AND oi1.order_id < oi2.order_id -- Avoid duplicates
16
+ JOIN orders o1 ON oi1.order_id = o1.order_id
17
+ JOIN orders o2 ON oi2.order_id = o2.order_id
18
+ JOIN customers c1 ON o1.customer_id = c1.customer_id
19
+ JOIN customers c2 ON o2.customer_id = c2.customer_id
20
+ JOIN products p ON oi1.product_id = p.product_id
21
+ WHERE c1.customer_id != c2.customer_id;
22
+
23
+ -- Example 2: Find sequential orders by same customer
24
+ SELECT
25
+ c.name,
26
+ o1.order_id as first_order,
27
+ o1.order_date as first_date,
28
+ o2.order_id as next_order,
29
+ o2.order_date as next_date,
30
+ o2.order_date - o1.order_date as days_between
31
+ FROM orders o1
32
+ JOIN orders o2 ON o1.customer_id = o2.customer_id
33
+ AND o2.order_date > o1.order_date
34
+ JOIN customers c ON o1.customer_id = c.customer_id
35
+ ORDER BY c.name, o1.order_date;
36
+
37
+ -- Key Concepts:
38
+ -- - Join table to itself with different aliases
39
+ -- - Use inequality (< or !=) to avoid matching same row
40
+ -- - Useful for finding patterns, sequences, or relationships
41
+ -- - Can be combined with window functions for "next" or "previous" record
rag/sample_templates/13_union_dedupe.sql ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: UNION vs UNION ALL for Deduplication
2
+ -- Pattern: Combine results from multiple queries
3
+ -- Use Case: Merge data from different sources, combine segments
4
+
5
+ -- UNION ALL: Keeps all rows including duplicates (FASTER)
6
+ SELECT customer_id, name, 'Active' as status
7
+ FROM customers
8
+ WHERE last_order_date >= CURRENT_DATE - INTERVAL '90 days'
9
+ UNION ALL
10
+ SELECT customer_id, name, 'VIP' as status
11
+ FROM customers
12
+ WHERE total_lifetime_value > 10000;
13
+
14
+ -- UNION: Removes duplicates (SLOWER but cleaner)
15
+ SELECT customer_id, name, email
16
+ FROM customers
17
+ WHERE city = 'New York'
18
+ UNION
19
+ SELECT customer_id, name, email
20
+ FROM customers
21
+ WHERE total_lifetime_value > 5000;
22
+
23
+ -- Example: Combine current and archived orders
24
+ SELECT
25
+ order_id,
26
+ customer_id,
27
+ order_date,
28
+ total_amount,
29
+ 'current' as source
30
+ FROM orders
31
+ WHERE order_date >= '2024-01-01'
32
+ UNION ALL
33
+ SELECT
34
+ order_id,
35
+ customer_id,
36
+ order_date,
37
+ total_amount,
38
+ 'archived' as source
39
+ FROM archived_orders
40
+ WHERE order_date < '2024-01-01';
41
+
42
+ -- Key Concepts:
43
+ -- - UNION removes duplicates (requires sort/compare - slower)
44
+ -- - UNION ALL keeps all rows (faster, no deduplication)
45
+ -- - All SELECT statements must have same number and type of columns
46
+ -- - Use UNION ALL when you know there are no duplicates
47
+ -- - Add source identifier column to track origin
rag/sample_templates/14_pivoting.sql ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Pivoting Data (CASE with Aggregation)
2
+ -- Pattern: Transform rows into columns
3
+ -- Use Case: Crosstab reports, monthly summaries, category breakdowns
4
+
5
+ -- Example 1: Revenue by month in columns
6
+ SELECT
7
+ EXTRACT(YEAR FROM order_date) as year,
8
+ SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 1 THEN total_amount ELSE 0 END) as jan,
9
+ SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 2 THEN total_amount ELSE 0 END) as feb,
10
+ SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 3 THEN total_amount ELSE 0 END) as mar,
11
+ SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 4 THEN total_amount ELSE 0 END) as apr,
12
+ SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 5 THEN total_amount ELSE 0 END) as may,
13
+ SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 6 THEN total_amount ELSE 0 END) as jun,
14
+ SUM(total_amount) as total_year
15
+ FROM orders
16
+ GROUP BY EXTRACT(YEAR FROM order_date)
17
+ ORDER BY year;
18
+
19
+ -- Example 2: Customer count by status and city
20
+ SELECT
21
+ city,
22
+ SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_customers,
23
+ SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive_customers,
24
+ SUM(CASE WHEN status = 'vip' THEN 1 ELSE 0 END) as vip_customers,
25
+ COUNT(*) as total_customers
26
+ FROM customers
27
+ GROUP BY city
28
+ ORDER BY total_customers DESC;
29
+
30
+ -- Key Concepts:
31
+ -- - CASE WHEN inside aggregate function
32
+ -- - Each CASE creates a new column
33
+ -- - SUM with 0/1 for counts, SUM with value for totals
34
+ -- - Alternative: Use FILTER (WHERE) in PostgreSQL
35
+ -- - Useful for summary reports and dashboards
rag/sample_templates/15_subquery_optimization.sql ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Template: Subquery Optimization - NOT IN vs NOT EXISTS
2
+ -- Pattern: Efficient ways to exclude records based on subquery
3
+ -- Use Case: Find records that don't match conditions, anti-joins
4
+
5
+ -- ❌ SLOWER: NOT IN with subquery (issues with NULL values)
6
+ SELECT customer_id, name
7
+ FROM customers
8
+ WHERE customer_id NOT IN (
9
+ SELECT customer_id
10
+ FROM orders
11
+ WHERE order_date >= '2024-01-01'
12
+ );
13
+ -- Problem: If orders.customer_id has ANY NULL, entire query returns empty!
14
+
15
+ -- ✅ BETTER: NOT EXISTS (faster and NULL-safe)
16
+ SELECT c.customer_id, c.name
17
+ FROM customers c
18
+ WHERE NOT EXISTS (
19
+ SELECT 1
20
+ FROM orders o
21
+ WHERE o.customer_id = c.customer_id
22
+ AND o.order_date >= '2024-01-01'
23
+ );
24
+
25
+ -- ✅ ALTERNATIVE: LEFT JOIN with NULL check
26
+ SELECT c.customer_id, c.name
27
+ FROM customers c
28
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
29
+ AND o.order_date >= '2024-01-01'
30
+ WHERE o.order_id IS NULL;
31
+
32
+ -- Example: Products NOT ordered in specific date range
33
+ SELECT p.product_id, p.name, p.category
34
+ FROM products p
35
+ WHERE NOT EXISTS (
36
+ SELECT 1
37
+ FROM order_items oi
38
+ JOIN orders o ON oi.order_id = o.order_id
39
+ WHERE oi.product_id = p.product_id
40
+ AND o.order_date >= '2024-01-01'
41
+ AND o.order_date < '2024-04-01'
42
+ );
43
+
44
+ -- Key Concepts:
45
+ -- - NOT IN fails if subquery returns NULL
46
+ -- - NOT EXISTS is NULL-safe and often faster
47
+ -- - LEFT JOIN with IS NULL also works well
48
+ -- - NOT EXISTS can short-circuit (stops at first match)
49
+ -- - Use SELECT 1 in EXISTS for efficiency
rag/template_store.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAG Template Store using LlamaIndex
3
+ PRIMARY SPONSOR INTEGRATION - LlamaIndex
4
+ Provides similar pattern suggestions from ETL template library
5
+ """
6
+
7
+ import os
8
+ from pathlib import Path
9
+ from typing import List, Dict
10
+ from llama_index.core import VectorStoreIndex, Document, StorageContext
11
+ from llama_index.core.node_parser import SimpleNodeParser
12
+ from llama_index.embeddings.openai import OpenAIEmbedding
13
+ from llama_index.core import Settings
14
+ import chromadb
15
+ from llama_index.vector_stores.chroma import ChromaVectorStore
16
+
17
+
18
+ class TemplateStore:
19
+ """
20
+ RAG-powered template store using LlamaIndex
21
+ Finds similar SQL patterns from template library
22
+ """
23
+
24
+ def __init__(self, templates_dir: str = None):
25
+ """Initialize the template store with LlamaIndex"""
26
+
27
+ if templates_dir is None:
28
+ # Default to sample_templates directory
29
+ current_dir = Path(__file__).parent
30
+ templates_dir = current_dir / "sample_templates"
31
+ else:
32
+ templates_dir = Path(templates_dir)
33
+
34
+ self.templates_dir = templates_dir
35
+
36
+ # Initialize OpenAI embeddings
37
+ try:
38
+ Settings.embed_model = OpenAIEmbedding(
39
+ model="text-embedding-3-small",
40
+ api_key=os.getenv("OPENAI_API_KEY")
41
+ )
42
+ except Exception as e:
43
+ print(f"⚠️ Warning: Could not initialize OpenAI embeddings: {e}")
44
+ print(" RAG features will be limited. Set OPENAI_API_KEY in .env")
45
+ self.index = None
46
+ return
47
+
48
+ # Initialize ChromaDB
49
+ try:
50
+ chroma_client = chromadb.EphemeralClient()
51
+ chroma_collection = chroma_client.create_collection("sql_templates")
52
+ vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
53
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
54
+
55
+ # Load templates
56
+ documents = self._load_templates()
57
+
58
+ if not documents:
59
+ print("⚠️ Warning: No templates found")
60
+ self.index = None
61
+ return
62
+
63
+ # Create index
64
+ self.index = VectorStoreIndex.from_documents(
65
+ documents,
66
+ storage_context=storage_context
67
+ )
68
+
69
+ print(f"✓ RAG Template Store initialized with {len(documents)} templates")
70
+
71
+ except Exception as e:
72
+ print(f"⚠️ Warning: Could not initialize RAG: {e}")
73
+ self.index = None
74
+
75
+ def _load_templates(self) -> List[Document]:
76
+ """Load all SQL templates from directory"""
77
+ documents = []
78
+
79
+ if not self.templates_dir.exists():
80
+ print(f"⚠️ Warning: Templates directory not found: {self.templates_dir}")
81
+ return documents
82
+
83
+ # Load all .sql files
84
+ for sql_file in sorted(self.templates_dir.glob("*.sql")):
85
+ try:
86
+ with open(sql_file, 'r', encoding='utf-8') as f:
87
+ content = f.read()
88
+
89
+ # Extract template name from filename
90
+ template_name = sql_file.stem.replace('_', ' ').title()
91
+
92
+ # Create document with metadata
93
+ doc = Document(
94
+ text=content,
95
+ metadata={
96
+ "filename": sql_file.name,
97
+ "template_name": template_name,
98
+ "path": str(sql_file)
99
+ }
100
+ )
101
+ documents.append(doc)
102
+
103
+ except Exception as e:
104
+ print(f"⚠️ Warning: Could not load template {sql_file}: {e}")
105
+
106
+ return documents
107
+
108
+ def find_similar(self, query: str, top_k: int = 3) -> List[Dict]:
109
+ """
110
+ Find similar templates based on natural language query
111
+
112
+ Args:
113
+ query: Natural language description of desired pattern
114
+ top_k: Number of similar templates to return
115
+
116
+ Returns:
117
+ List of dicts with template info and similarity scores
118
+ """
119
+ if self.index is None:
120
+ return []
121
+
122
+ try:
123
+ # Query the index
124
+ retriever = self.index.as_retriever(similarity_top_k=top_k)
125
+ nodes = retriever.retrieve(query)
126
+
127
+ results = []
128
+ for node in nodes:
129
+ # Extract template information
130
+ template_info = {
131
+ "template_name": node.metadata.get("template_name", "Unknown"),
132
+ "filename": node.metadata.get("filename", ""),
133
+ "content": node.text,
134
+ "score": node.score if hasattr(node, 'score') else 0.0,
135
+ "excerpt": self._extract_excerpt(node.text)
136
+ }
137
+ results.append(template_info)
138
+
139
+ return results
140
+
141
+ except Exception as e:
142
+ print(f"⚠️ Warning: Error finding similar templates: {e}")
143
+ return []
144
+
145
+ def _extract_excerpt(self, content: str, max_lines: int = 5) -> str:
146
+ """Extract a short excerpt from template"""
147
+ lines = content.split('\n')
148
+
149
+ # Skip comment lines and find actual SQL
150
+ sql_lines = []
151
+ for line in lines:
152
+ stripped = line.strip()
153
+ if stripped and not stripped.startswith('--'):
154
+ sql_lines.append(line)
155
+ if len(sql_lines) >= max_lines:
156
+ break
157
+
158
+ if sql_lines:
159
+ excerpt = '\n'.join(sql_lines[:max_lines])
160
+ if len(sql_lines) > max_lines:
161
+ excerpt += "\n..."
162
+ return excerpt
163
+ else:
164
+ # Return first few non-empty lines if no SQL found
165
+ non_empty = [l for l in lines if l.strip()][:max_lines]
166
+ return '\n'.join(non_empty)
167
+
168
+ def get_all_templates(self) -> List[Dict]:
169
+ """Get information about all available templates"""
170
+ templates = []
171
+
172
+ if not self.templates_dir.exists():
173
+ return templates
174
+
175
+ for sql_file in sorted(self.templates_dir.glob("*.sql")):
176
+ try:
177
+ with open(sql_file, 'r', encoding='utf-8') as f:
178
+ content = f.read()
179
+
180
+ # Extract first comment line as description
181
+ first_line = content.split('\n')[0].strip()
182
+ description = first_line.replace('--', '').strip() if first_line.startswith('--') else ""
183
+
184
+ templates.append({
185
+ "filename": sql_file.name,
186
+ "template_name": sql_file.stem.replace('_', ' ').title(),
187
+ "description": description,
188
+ "path": str(sql_file)
189
+ })
190
+ except Exception as e:
191
+ print(f"⚠️ Warning: Error reading template {sql_file}: {e}")
192
+
193
+ return templates
194
+
195
+
196
+ # Singleton instance
197
+ _template_store = None
198
+
199
+ def get_template_store() -> TemplateStore:
200
+ """Get or create the global template store instance"""
201
+ global _template_store
202
+ if _template_store is None:
203
+ _template_store = TemplateStore()
204
+ return _template_store
requirements.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core UI
2
+ gradio>=4.44.1
3
+ python-dotenv==1.0.0
4
+
5
+ # AI/ML
6
+ anthropic>=0.39.0
7
+
8
+ # PRIMARY SPONSOR - LlamaIndex RAG
9
+ llama-index==0.9.14
10
+ llama-index-embeddings-openai
11
+ chromadb==0.4.18
12
+ openai
13
+
14
+ # SECONDARY SPONSOR - Modal Testing
15
+ modal>=1.2.0
16
+
17
+ # Database
18
+ sqlalchemy==2.0.23
19
+ pandas==2.1.3
20
+ duckdb==0.9.2
21
+
22
+ # SQL Processing
23
+ sqlparse==0.4.4
24
+ jinja2==3.1.2
25
+ pyyaml==6.0.1
26
+
27
+ # Optional
28
+ plotly==5.18.0
sample.db ADDED
Binary file (45.1 kB). View file
 
schema_analyzer.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+
3
+ class SchemaAnalyzer:
4
+ """Analyzes database schema"""
5
+
6
+ def __init__(self, db_path='sample.db'):
7
+ self.db_path = db_path
8
+
9
+ def get_schema(self):
10
+ """Get complete database schema"""
11
+ conn = sqlite3.connect(self.db_path)
12
+ cursor = conn.cursor()
13
+
14
+ # Get all tables
15
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
16
+ tables = [row[0] for row in cursor.fetchall()]
17
+
18
+ schema = {}
19
+ for table in tables:
20
+ cursor.execute(f"PRAGMA table_info({table})")
21
+ columns = []
22
+ for row in cursor.fetchall():
23
+ columns.append({
24
+ "name": row[1],
25
+ "type": row[2],
26
+ "nullable": not row[3],
27
+ "primary_key": bool(row[5])
28
+ })
29
+ schema[table] = columns
30
+
31
+ conn.close()
32
+ return schema
sql_validator.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQL Query Validator and Optimizer
3
+ Provides validation, optimization suggestions, and query analysis
4
+ """
5
+
6
+ import re
7
+ from typing import Dict, List, Tuple
8
+
9
+ class SQLValidator:
10
+ """Validates and analyzes SQL queries"""
11
+
12
+ def __init__(self, schema: Dict):
13
+ self.schema = schema
14
+ self.table_names = set(schema.keys())
15
+ self.column_map = {}
16
+
17
+ # Build column map for quick lookup
18
+ for table, columns in schema.items():
19
+ for col in columns:
20
+ col_name = col['name'].lower()
21
+ if col_name not in self.column_map:
22
+ self.column_map[col_name] = []
23
+ self.column_map[col_name].append(table)
24
+
25
+ def validate(self, sql: str) -> Dict[str, any]:
26
+ """
27
+ Validate SQL query against schema
28
+ Returns dict with validation results
29
+ """
30
+ results = {
31
+ "valid": True,
32
+ "errors": [],
33
+ "warnings": [],
34
+ "suggestions": [],
35
+ "query_type": self._detect_query_type(sql)
36
+ }
37
+
38
+ # Check for common SQL anti-patterns
39
+ self._check_null_comparison(sql, results)
40
+ self._check_select_star(sql, results)
41
+ self._check_missing_where(sql, results)
42
+ self._check_implicit_joins(sql, results)
43
+ self._check_table_names(sql, results)
44
+
45
+ # If we found errors, mark as invalid
46
+ if results["errors"]:
47
+ results["valid"] = False
48
+
49
+ return results
50
+
51
+ def _detect_query_type(self, sql: str) -> str:
52
+ """Detect the type of query"""
53
+ sql_upper = sql.upper()
54
+
55
+ if "WITH" in sql_upper and "AS" in sql_upper:
56
+ return "cte"
57
+ elif any(func in sql_upper for func in ["ROW_NUMBER(", "RANK(", "DENSE_RANK(", "PARTITION BY"]):
58
+ return "window"
59
+ elif "GROUP BY" in sql_upper or any(func in sql_upper for func in ["COUNT(", "SUM(", "AVG(", "MAX(", "MIN("]):
60
+ return "aggregate"
61
+ elif "JOIN" in sql_upper:
62
+ return "join"
63
+ elif "UNION" in sql_upper:
64
+ return "union"
65
+ elif "EXISTS" in sql_upper or "IN (SELECT" in sql_upper:
66
+ return "subquery"
67
+ else:
68
+ return "simple"
69
+
70
+ def _check_null_comparison(self, sql: str, results: Dict):
71
+ """Check for = NULL instead of IS NULL"""
72
+ if re.search(r"=\s*NULL|!=\s*NULL|<>\s*NULL", sql, re.IGNORECASE):
73
+ results["errors"].append(
74
+ "Use IS NULL or IS NOT NULL instead of = NULL or != NULL"
75
+ )
76
+
77
+ def _check_select_star(self, sql: str, results: Dict):
78
+ """Warn about SELECT *"""
79
+ if re.search(r"SELECT\s+\*", sql, re.IGNORECASE):
80
+ results["warnings"].append(
81
+ "Consider specifying column names instead of SELECT * for better performance"
82
+ )
83
+
84
+ def _check_missing_where(self, sql: str, results: Dict):
85
+ """Check for queries without WHERE clause on large tables"""
86
+ sql_upper = sql.upper()
87
+ if "DELETE" in sql_upper or "UPDATE" in sql_upper:
88
+ if "WHERE" not in sql_upper:
89
+ results["errors"].append(
90
+ "DELETE or UPDATE without WHERE clause will affect all rows"
91
+ )
92
+
93
+ def _check_implicit_joins(self, sql: str, results: Dict):
94
+ """Check for implicit joins (comma-separated tables)"""
95
+ # Look for FROM table1, table2 pattern
96
+ if re.search(r"FROM\s+\w+\s*,\s*\w+", sql, re.IGNORECASE):
97
+ results["suggestions"].append(
98
+ "Consider using explicit JOIN syntax instead of comma-separated tables"
99
+ )
100
+
101
+ def _check_table_names(self, sql: str, results: Dict):
102
+ """Check if referenced tables exist in schema"""
103
+ # Extract table names from FROM and JOIN clauses
104
+ from_pattern = r"FROM\s+(\w+)"
105
+ join_pattern = r"JOIN\s+(\w+)"
106
+
107
+ tables_in_query = set()
108
+
109
+ for match in re.finditer(from_pattern, sql, re.IGNORECASE):
110
+ tables_in_query.add(match.group(1).lower())
111
+
112
+ for match in re.finditer(join_pattern, sql, re.IGNORECASE):
113
+ tables_in_query.add(match.group(1).lower())
114
+
115
+ # Check against schema
116
+ schema_tables = set(t.lower() for t in self.table_names)
117
+ invalid_tables = tables_in_query - schema_tables
118
+
119
+ if invalid_tables:
120
+ results["errors"].append(
121
+ f"Table(s) not found in schema: {', '.join(invalid_tables)}"
122
+ )
123
+
124
+ def suggest_optimizations(self, sql: str) -> List[str]:
125
+ """Suggest optimizations for the query"""
126
+ suggestions = []
127
+ sql_upper = sql.upper()
128
+
129
+ # Check for NOT IN with subquery
130
+ if "NOT IN (SELECT" in sql_upper:
131
+ suggestions.append(
132
+ "Consider using NOT EXISTS instead of NOT IN for better NULL handling"
133
+ )
134
+
135
+ # Check for multiple subqueries
136
+ subquery_count = sql_upper.count("(SELECT")
137
+ if subquery_count > 2:
138
+ suggestions.append(
139
+ "Consider using CTEs (WITH clause) for better readability with multiple subqueries"
140
+ )
141
+
142
+ # Check for DISTINCT
143
+ if "DISTINCT" in sql_upper and "GROUP BY" not in sql_upper:
144
+ suggestions.append(
145
+ "DISTINCT can be expensive. Consider if GROUP BY might be more appropriate"
146
+ )
147
+
148
+ # Check for ORDER BY in subquery
149
+ if re.search(r"\(SELECT.*ORDER BY.*\)", sql, re.IGNORECASE):
150
+ suggestions.append(
151
+ "ORDER BY in subquery may be ignored. Apply ORDER BY to outer query"
152
+ )
153
+
154
+ return suggestions
155
+
156
+ def format_sql(self, sql: str) -> str:
157
+ """Basic SQL formatting for readability"""
158
+ # This is a simple formatter - for production use a proper SQL formatter
159
+ formatted = sql.strip()
160
+
161
+ # Add newlines before major keywords
162
+ keywords = ['SELECT', 'FROM', 'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT']
163
+ for keyword in keywords:
164
+ formatted = re.sub(
165
+ f'\\b{keyword}\\b',
166
+ f'\n{keyword}',
167
+ formatted,
168
+ flags=re.IGNORECASE
169
+ )
170
+
171
+ return formatted.strip()
testing/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Testing module for CodeFlow AI
3
+ Uses Modal for serverless SQL execution
4
+ """
testing/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (265 Bytes). View file
 
testing/__pycache__/test_runner.cpython-311.pyc ADDED
Binary file (9.64 kB). View file
 
testing/test_runner.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQL Test Runner using Modal (SECONDARY SPONSOR)
3
+ Provides serverless SQL execution for testing queries
4
+ """
5
+
6
+ import os
7
+ from typing import Dict, Any
8
+
9
+ # Try to import Modal, but don't fail if not available
10
+ try:
11
+ import modal
12
+ MODAL_AVAILABLE = True
13
+ except ImportError:
14
+ MODAL_AVAILABLE = False
15
+ print("⚠️ Modal not available. Install with: pip install modal")
16
+
17
+ # Try to import DuckDB for local fallback
18
+ try:
19
+ import duckdb
20
+ DUCKDB_AVAILABLE = True
21
+ except ImportError:
22
+ DUCKDB_AVAILABLE = False
23
+ print("⚠️ DuckDB not available for local testing fallback")
24
+
25
+
26
+ class SQLTestRunner:
27
+ """
28
+ Test runner for SQL queries
29
+ Uses Modal for serverless execution, with DuckDB fallback
30
+ """
31
+
32
+ def __init__(self):
33
+ self.modal_available = MODAL_AVAILABLE
34
+ self.duckdb_available = DUCKDB_AVAILABLE
35
+
36
+ # Initialize Modal app if available
37
+ if self.modal_available:
38
+ try:
39
+ self.app = modal.App("codeflow-sql-tester")
40
+ self._setup_modal()
41
+ except Exception as e:
42
+ print(f"⚠️ Modal setup failed: {e}")
43
+ self.modal_available = False
44
+
45
+ def _setup_modal(self):
46
+ """Setup Modal function for SQL execution"""
47
+ if not self.modal_available:
48
+ return
49
+
50
+ try:
51
+ # Define Modal image with DuckDB
52
+ image = modal.Image.debian_slim().pip_install("duckdb==0.9.2")
53
+
54
+ # Define Modal function
55
+ @self.app.function(image=image, timeout=60)
56
+ def execute_sql_modal(sql: str, sample_data: dict = None) -> dict:
57
+ """Execute SQL in Modal sandbox"""
58
+ import duckdb
59
+
60
+ try:
61
+ # Create in-memory DuckDB database
62
+ conn = duckdb.connect(':memory:')
63
+
64
+ # If sample data provided, create tables
65
+ if sample_data:
66
+ for table_name, data in sample_data.items():
67
+ conn.execute(f"CREATE TABLE {table_name} AS SELECT * FROM ?", [data])
68
+
69
+ # Execute the SQL
70
+ result = conn.execute(sql).fetchall()
71
+ columns = [desc[0] for desc in conn.description] if conn.description else []
72
+
73
+ conn.close()
74
+
75
+ return {
76
+ "success": True,
77
+ "rows": result[:100], # Limit to 100 rows
78
+ "row_count": len(result),
79
+ "columns": columns,
80
+ "error": None
81
+ }
82
+
83
+ except Exception as e:
84
+ return {
85
+ "success": False,
86
+ "rows": [],
87
+ "row_count": 0,
88
+ "columns": [],
89
+ "error": str(e)
90
+ }
91
+
92
+ self.execute_sql_modal = execute_sql_modal
93
+
94
+ except Exception as e:
95
+ print(f"⚠️ Modal function setup failed: {e}")
96
+ self.modal_available = False
97
+
98
+ def test_sql(self, sql: str, sample_data: Dict = None) -> Dict[str, Any]:
99
+ """
100
+ Test SQL query execution
101
+
102
+ Args:
103
+ sql: SQL query to test
104
+ sample_data: Optional sample data as dict of table_name -> rows
105
+
106
+ Returns:
107
+ Dict with test results
108
+ """
109
+
110
+ # Try Modal first if available
111
+ if self.modal_available:
112
+ try:
113
+ result = self.execute_sql_modal.remote(sql, sample_data)
114
+ result["execution_method"] = "Modal (Serverless)"
115
+ return result
116
+ except Exception as e:
117
+ print(f"⚠️ Modal execution failed, falling back to local: {e}")
118
+
119
+ # Fallback to local DuckDB
120
+ if self.duckdb_available:
121
+ return self._test_sql_local(sql, sample_data)
122
+
123
+ # No execution method available
124
+ return {
125
+ "success": False,
126
+ "rows": [],
127
+ "row_count": 0,
128
+ "columns": [],
129
+ "error": "No SQL execution method available. Install Modal or DuckDB.",
130
+ "execution_method": "None"
131
+ }
132
+
133
+ def _test_sql_local(self, sql: str, sample_data: Dict = None) -> Dict[str, Any]:
134
+ """Execute SQL locally using DuckDB"""
135
+ try:
136
+ conn = duckdb.connect(':memory:')
137
+
138
+ # Create sample tables if provided
139
+ if sample_data:
140
+ for table_name, data in sample_data.items():
141
+ conn.execute(f"CREATE TABLE {table_name} AS SELECT * FROM ?", [data])
142
+
143
+ # Execute SQL
144
+ result = conn.execute(sql).fetchall()
145
+ columns = [desc[0] for desc in conn.description] if conn.description else []
146
+
147
+ conn.close()
148
+
149
+ return {
150
+ "success": True,
151
+ "rows": result[:100], # Limit to 100 rows
152
+ "row_count": len(result),
153
+ "columns": columns,
154
+ "error": None,
155
+ "execution_method": "DuckDB (Local)"
156
+ }
157
+
158
+ except Exception as e:
159
+ return {
160
+ "success": False,
161
+ "rows": [],
162
+ "row_count": 0,
163
+ "columns": [],
164
+ "error": str(e),
165
+ "execution_method": "DuckDB (Local)"
166
+ }
167
+
168
+ def validate_syntax(self, sql: str) -> Dict[str, Any]:
169
+ """
170
+ Quick syntax validation without execution
171
+
172
+ Args:
173
+ sql: SQL query to validate
174
+
175
+ Returns:
176
+ Dict with validation results
177
+ """
178
+ if not self.duckdb_available:
179
+ return {
180
+ "valid": None,
181
+ "error": "DuckDB not available for syntax validation"
182
+ }
183
+
184
+ try:
185
+ conn = duckdb.connect(':memory:')
186
+ # Try to prepare the query (doesn't execute, just validates syntax)
187
+ conn.execute(f"EXPLAIN {sql}")
188
+ conn.close()
189
+
190
+ return {
191
+ "valid": True,
192
+ "error": None
193
+ }
194
+
195
+ except Exception as e:
196
+ return {
197
+ "valid": False,
198
+ "error": str(e)
199
+ }
200
+
201
+ def get_execution_plan(self, sql: str) -> Dict[str, Any]:
202
+ """
203
+ Get query execution plan
204
+
205
+ Args:
206
+ sql: SQL query
207
+
208
+ Returns:
209
+ Dict with execution plan
210
+ """
211
+ if not self.duckdb_available:
212
+ return {
213
+ "success": False,
214
+ "plan": None,
215
+ "error": "DuckDB not available"
216
+ }
217
+
218
+ try:
219
+ conn = duckdb.connect(':memory:')
220
+ plan = conn.execute(f"EXPLAIN {sql}").fetchall()
221
+ conn.close()
222
+
223
+ return {
224
+ "success": True,
225
+ "plan": "\n".join([str(row[0]) for row in plan]),
226
+ "error": None
227
+ }
228
+
229
+ except Exception as e:
230
+ return {
231
+ "success": False,
232
+ "plan": None,
233
+ "error": str(e)
234
+ }
235
+
236
+
237
+ # Singleton instance
238
+ _test_runner = None
239
+
240
+ def get_test_runner() -> SQLTestRunner:
241
+ """Get or create the global test runner instance"""
242
+ global _test_runner
243
+ if _test_runner is None:
244
+ _test_runner = SQLTestRunner()
245
+ return _test_runner