sql-cli 1.73.1

SQL query tool for CSV/JSON with both interactive TUI and non-interactive CLI modes - perfect for exploration and automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# Code CTE Design - Programmable Data Transformations

> **⚠️ DECISION: NOT PROCEEDING WITH THIS FEATURE (2025-01-11)**
>
> After investigation, we decided NOT to implement CODE CTEs due to Python environment management complexity (venvs, versions, dependencies). The same capability can be achieved more simply by:
>
> 1. **Enhancing WEB CTEs** to support POST with query result as body
> 2. **User runs their own Flask/Node/Go server** for transformations
> 3. User maintains full control of their Python environment
>
> This document is preserved for historical reference only.
>
> See `docs/SESSION_SUMMARY_2025-01-11.md` for full analysis.

---

## Executive Summary

This document outlines a strategic design for adding programmable CTEs to SQL-CLI, enabling users to write code-based data transformations that integrate seamlessly with the SQL execution pipeline. This is a long-term, multi-phase project that will be developed iteratively.

## Vision

Enable users to write testable, reusable code blocks that act as CTEs in the SQL pipeline:

```sql
-- External code file: ./scripts/enrich_trades.py
-- Testable independently with pytest

WITH base_trades AS (
    SELECT * FROM trades WHERE date = '2024-01-15'
),
CODE enriched AS (
    LANGUAGE python
    SOURCE './scripts/enrich_trades.py'
    FUNCTION enrich_trades
    INPUT base_trades
)
SELECT * FROM enriched WHERE risk_score > 50;
```

The code receives DataTable(s) as input, performs transformations, and returns a new DataTable that flows back into the SQL pipeline.

## Current State Analysis

### What We Have

1. **Temp Tables (#tmp)**   - Persist data across GO-delimited queries
   - TempTableRegistry for script-scoped storage
   - Already working well

2. **Template System**   - `@{VAR:name}`, `@{INPUT:prompt}`, `@{MACRO:name}` syntax
   - External template files with SQL syntax highlighting
   - Template expansion before query execution

3. **WEB CTEs**   - Fetch data from HTTP APIs
   - JSON/CSV format support
   - Template injection for dynamic queries

4. **Python Test Infrastructure**   - 40+ Python test files
   - Python already installed and working
   - subprocess integration proven

5. **Lua in Nvim Plugin**   - Client-side Lua for editor integration
   - Not embedded in CLI (yet)

### Architectural Foundation

```
Current Pipeline:
SQL Text → Parser → AST → Query Executor → DataTable → Results

Proposed Pipeline:
SQL Text → Parser → AST → Query Executor → [Code CTE Executor] → DataTable → Results
                    CTE Context (read-only)
                    Temp Tables (read-only)
```

## Technology Options Analysis

### Option 1: Python (via subprocess) ⭐ **RECOMMENDED FOR PHASE 1**

**Pros:**
- ✅ Already used extensively in test suite
- ✅ Rich ecosystem (pandas, numpy, polars)
- ✅ Most developers know Python
- ✅ Easy debugging - run scripts independently
- ✅ No new Rust dependencies
- ✅ Proven subprocess integration

**Cons:**
- ⚠️ Slower startup (subprocess overhead)
- ⚠️ Data serialization cost (JSON/CSV between processes)
- ⚠️ Not embedded (external Python required)

**Implementation Complexity:** Low
**Risk:** Low
**Performance:** Medium (acceptable for data transformation)

**Architecture:**
```rust
// Rust side
pub struct PythonCodeCTE {
    script_path: PathBuf,
    function_name: String,
}

impl PythonCodeCTE {
    fn execute(&self, input: &DataTable) -> Result<DataTable> {
        // 1. Serialize DataTable to JSON
        let input_json = serde_json::to_string(&input)?;

        // 2. Create temp file with input data
        let temp_input = NamedTempFile::new()?;
        write!(temp_input, "{}", input_json)?;

        // 3. Execute Python script
        let output = Command::new("python3")
            .arg(&self.script_path)
            .arg("--function")
            .arg(&self.function_name)
            .arg("--input")
            .arg(temp_input.path())
            .output()?;

        // 4. Parse output JSON back to DataTable
        let output_json = String::from_utf8(output.stdout)?;
        let result_table = DataTable::from_json(&output_json)?;

        Ok(result_table)
    }
}
```

```python
# Python side (user-written script)
import json
import sys
from typing import Dict, List, Any

def enrich_trades(input_table: Dict[str, Any]) -> Dict[str, Any]:
    """
    Process trade data and add risk scores.

    Args:
        input_table: {
            "columns": ["trade_id", "symbol", "amount"],
            "rows": [[1, "AAPL", 1000], [2, "GOOGL", 2000]]
        }

    Returns:
        Same structure with additional columns
    """
    # Add risk_score column
    rows = input_table["rows"]
    enriched_rows = []

    for row in rows:
        amount = row[2]
        risk_score = calculate_risk(amount)  # User logic
        enriched_rows.append(row + [risk_score])

    return {
        "columns": input_table["columns"] + ["risk_score"],
        "rows": enriched_rows
    }

# CLI framework code (provided by sql-cli)
if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--function", required=True)
    parser.add_argument("--input", required=True)
    args = parser.parse_args()

    # Load input
    with open(args.input) as f:
        input_data = json.load(f)

    # Execute user function
    func = globals()[args.function]
    result = func(input_data)

    # Output result
    print(json.dumps(result))
```

### Option 2: Embedded Lua (mlua crate)

**Pros:**
- ✅ Lightweight and fast
- ✅ Small runtime overhead
- ✅ Good Rust integration (mlua crate)
- ✅ Lua already familiar to Nvim users

**Cons:**
- ⚠️ Limited ecosystem compared to Python
- ⚠️ New dependency (mlua ~300KB)
- ⚠️ Separate language to learn
- ⚠️ Harder debugging than Python

**Implementation Complexity:** Medium
**Risk:** Medium
**Performance:** High

### Option 3: JavaScript (Rhai or boa)

**Pros:**
- ✅ Rhai designed for Rust embedding
- ✅ Familiar syntax for many developers
- ✅ Good performance

**Cons:**
- ⚠️ Another language to support
- ⚠️ Smaller ecosystem than Python/Lua
- ⚠️ Less proven in data processing

**Implementation Complexity:** Medium
**Risk:** Medium
**Performance:** High

### Option 4: WebAssembly (wasmtime)

**Pros:**
- ✅ Language agnostic (Python, Rust, C++, Go)
- ✅ Sandboxed execution
- ✅ Great performance potential

**Cons:**
- ❌ Complex compilation workflow
- ❌ Steep learning curve
- ❌ Hard to debug
- ❌ Overkill for current use case

**Implementation Complexity:** Very High
**Risk:** High
**Performance:** Very High

## Recommended Approach: Phased Implementation

### Phase 1: Python Subprocess (6-8 sessions)

**Goal:** Prove the concept with minimal risk

**Deliverables:**
1. JSON DataTable serialization format
2. Python helper library (`sql_cli_helper.py`)
3. CODE CTE parser syntax
4. Python subprocess executor
5. Error handling and validation
6. Documentation and examples
7. Test suite

**SQL Syntax:**
```sql
CODE result AS (
    LANGUAGE python
    SOURCE './transform.py'
    FUNCTION transform_data
    INPUT source_cte
)
```

**Success Criteria:**
- Can execute Python code from SQL
- Input/output DataTable serialization works
- Error messages are clear
- Performance acceptable for <100K rows

### Phase 2: Multiple Inputs & Optimization (3-4 sessions)

**Enhancements:**
- Multiple input CTEs
- Caching of Python interpreter
- Streaming for large datasets
- CSV serialization option (faster than JSON)

```sql
CODE joined AS (
    LANGUAGE python
    SOURCE './join_logic.py'
    FUNCTION custom_join
    INPUT trades, allocations  -- Multiple inputs
)
```

### Phase 3: Embedded Lua (Optional, 4-6 sessions)

**If Python proves successful and users want faster embedded option:**
- Add mlua dependency
- Implement Lua executor
- Provide Lua API for DataTable access
- Performance comparison

```sql
CODE filtered AS (
    LANGUAGE lua
    INLINE "
        return input:filter(function(row)
            return row.amount > 1000
        end)
    "
    INPUT trades
)
```

### Phase 4: Advanced Features (Future)

- Async/concurrent execution
- Streaming transformations
- Type system integration
- WASM support for compiled languages

## API Design

### DataTable JSON Format

```json
{
    "name": "trades",
    "columns": [
        {
            "name": "trade_id",
            "data_type": "Integer",
            "nullable": false
        },
        {
            "name": "symbol",
            "data_type": "String",
            "nullable": false
        },
        {
            "name": "amount",
            "data_type": "Float",
            "nullable": true
        }
    ],
    "rows": [
        [1, "AAPL", 1000.50],
        [2, "GOOGL", 2000.75],
        [3, "MSFT", null]
    ]
}
```

### Python Helper Library

```python
# sql_cli_helper.py (provided with installation)
from typing import List, Dict, Any, Optional
from dataclasses import dataclass

@dataclass
class Column:
    name: str
    data_type: str
    nullable: bool

class DataTable:
    """Wrapper around sql-cli DataTable JSON format"""

    def __init__(self, data: Dict[str, Any]):
        self.name = data["name"]
        self.columns = [Column(**c) for c in data["columns"]]
        self.rows = data["rows"]

    def to_dict(self) -> Dict[str, Any]:
        return {
            "name": self.name,
            "columns": [{"name": c.name, "data_type": c.data_type, "nullable": c.nullable}
                       for c in self.columns],
            "rows": self.rows
        }

    def filter(self, predicate):
        """Filter rows based on predicate"""
        filtered = [row for row in self.rows if predicate(row)]
        return DataTable({
            "name": self.name,
            "columns": [c.__dict__ for c in self.columns],
            "rows": filtered
        })

    def add_column(self, name: str, data_type: str, values: List[Any]):
        """Add a new column"""
        if len(values) != len(self.rows):
            raise ValueError(f"Expected {len(self.rows)} values, got {len(values)}")

        self.columns.append(Column(name, data_type, nullable=True))
        for i, row in enumerate(self.rows):
            row.append(values[i])

    def to_pandas(self):
        """Convert to pandas DataFrame (if pandas installed)"""
        import pandas as pd
        return pd.DataFrame(self.rows, columns=[c.name for c in self.columns])

    @staticmethod
    def from_pandas(df, name="result"):
        """Create from pandas DataFrame"""
        # Type inference logic
        pass
```

### User Script Template

```python
#!/usr/bin/env python3
"""
Trade enrichment script for sql-cli CODE CTE

This script can be tested independently:
    python enrich_trades.py --test
    pytest test_enrich_trades.py
"""
from sql_cli_helper import DataTable

def enrich_trades(trades: DataTable) -> DataTable:
    """
    Add risk scores and categories to trades

    Args:
        trades: DataTable with columns [trade_id, symbol, amount]

    Returns:
        DataTable with additional columns [risk_score, category]
    """
    risk_scores = []
    categories = []

    for row in trades.rows:
        trade_id, symbol, amount = row

        # Calculate risk score
        risk = calculate_risk(amount, symbol)
        risk_scores.append(risk)

        # Categorize
        category = categorize_trade(amount)
        categories.append(category)

    # Add new columns
    trades.add_column("risk_score", "Float", risk_scores)
    trades.add_column("category", "String", categories)

    return trades

def calculate_risk(amount: float, symbol: str) -> float:
    """Business logic for risk calculation"""
    base_risk = amount / 10000
    if symbol in ["TSLA", "GME"]:
        return base_risk * 2.0
    return base_risk

def categorize_trade(amount: float) -> str:
    """Categorize trade size"""
    if amount < 1000:
        return "small"
    elif amount < 10000:
        return "medium"
    else:
        return "large"

# Testing interface
if __name__ == "__main__":
    import sys
    import json

    if "--test" in sys.argv:
        # Run with test data
        test_data = DataTable({
            "name": "test_trades",
            "columns": [
                {"name": "trade_id", "data_type": "Integer", "nullable": False},
                {"name": "symbol", "data_type": "String", "nullable": False},
                {"name": "amount", "data_type": "Float", "nullable": False}
            ],
            "rows": [
                [1, "AAPL", 5000.0],
                [2, "TSLA", 15000.0],
                [3, "GOOGL", 500.0]
            ]
        })

        result = enrich_trades(test_data)
        print(json.dumps(result.to_dict(), indent=2))

    else:
        # SQL-CLI integration mode
        from sql_cli_helper import run_code_cte
        run_code_cte(enrich_trades)
```

## File Organization

```
sql-cli/
├── src/
│   ├── sql/
│   │   └── code_cte/
│   │       ├── mod.rs           # CODE CTE parser
│   │       ├── executor.rs      # Abstract executor trait
│   │       ├── python.rs        # Python subprocess executor
│   │       └── lua.rs           # Lua embedded executor (Phase 3)
│   └── data/
│       └── serialization/
│           ├── json_table.rs    # DataTable <-> JSON
│           └── csv_table.rs     # DataTable <-> CSV (Phase 2)
├── python/
│   ├── sql_cli_helper.py        # Helper library
│   ├── setup.py                 # Pip package
│   └── examples/
│       ├── enrich_trades.py
│       ├── custom_join.py
│       └── test_*.py
├── examples/
│   └── code_cte_examples.sql    # SQL examples
└── docs/
    ├── CODE_CTE_DESIGN.md       # This document
    ├── CODE_CTE_TUTORIAL.md     # User guide
    └── CODE_CTE_API.md          # Python API reference
```

## Security Considerations

1. **Code Execution Risk:**
   - Python scripts run with user's permissions
   - No sandboxing in Phase 1 (subprocess inherits permissions)
   - Users must trust their own code

2. **Path Handling:**
   - Validate SOURCE paths are readable
   - No automatic execution of code
   - Explicit SOURCE required (no implicit includes)

3. **Error Handling:**
   - Timeout for long-running scripts
   - Capture stderr for debugging
   - Clear error messages for invalid Python

4. **Future (Phase 3+):**
   - Consider Lua sandboxing
   - Resource limits (memory, CPU)
   - WASM for true sandboxing

## Testing Strategy

### Unit Tests (Rust)
- Parser for CODE CTE syntax
- JSON serialization/deserialization
- Error handling

### Integration Tests (Python)
- End-to-end CODE CTE execution
- Multiple input CTEs
- Error propagation
- Performance benchmarks

### Example Tests
```python
def test_code_cte_basic():
    """Test basic CODE CTE execution"""
    result = run_sql("""
        WITH data AS (SELECT value as n FROM RANGE(1, 5))
        CODE doubled AS (
            LANGUAGE python
            SOURCE './tests/scripts/double_values.py'
            FUNCTION double_values
            INPUT data
        )
        SELECT * FROM doubled;
    """)

    assert len(result) == 5
    assert result[0]["n"] == 2
    assert result[4]["n"] == 10
```

## Performance Expectations

### Phase 1 (Python Subprocess)

| Rows    | Serialization | Python Exec | Total      | Acceptable? |
|---------|---------------|-------------|------------|-------------|
| 100     | 1ms           | 50ms        | ~51ms      | ✅ Yes      |
| 1,000   | 5ms           | 55ms        | ~60ms      | ✅ Yes      |
| 10,000  | 50ms          | 100ms       | ~150ms     | ✅ Yes      |
| 100,000 | 500ms         | 500ms       | ~1s        | ⚠️ Acceptable |
| 1M+     | 5s+           | Variable    | 10s+       | ❌ Use streaming |

**Optimization paths:**
- CSV serialization (faster than JSON)
- Persistent Python process (avoid startup overhead)
- Streaming mode (Phase 2+)

## Migration Path for Existing Users

This is a **purely additive feature**:

1. No breaking changes to existing SQL syntax
2. CODE CTE is opt-in
3. Works alongside all existing features
4. Python scripts are external - no forced dependencies
5. Clear error if Python not available

## Success Metrics

### Phase 1 Success:
- [ ] Can execute Python function from SQL
- [ ] INPUT CTE data passed correctly
- [ ] OUTPUT DataTable integrates with SQL
- [ ] 10+ example scripts provided
- [ ] Documentation complete
- [ ] 5 users test and provide feedback
- [ ] Performance acceptable for 10K rows

### Long-term Vision:
- Stored procedure-like workflow
- Library of reusable transformations
- Community-contributed scripts
- Tight editor integration (LSP, debugging)

## Open Questions for Discussion

1. **Naming:** `CODE` vs `SCRIPT` vs `TRANSFORM` vs `PROC`?
2. **Error handling:** What happens if Python script fails mid-stream?
3. **Type system:** Should we enforce schema compatibility?
4. **Caching:** Cache Python interpreter process between queries?
5. **Async:** Should CODE CTEs run concurrently when independent?

## Next Steps

1. **Review this design** with user feedback
2. **Create Phase 1 task breakdown** (6-8 sessions)
3. **Prototype JSON serialization** (1 session)
4. **Prototype Python executor** (1-2 sessions)
5. **Iterate based on real-world usage**

## Conclusion

Starting with Python via subprocess is the **lowest-risk, highest-value** approach:
- Leverages existing infrastructure
- Familiar to most users
- Easy to test and debug
- Minimal new dependencies
- Can optimize later if needed

This provides a solid foundation for stored procedure-like functionality while maintaining sql-cli's philosophy of simplicity and transparency.

---

**Document Status:** Draft for discussion
**Author:** Claude with user guidance
**Date:** 2025-10-09
**Next Review:** After initial feedback