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
use serde_json::Value;
use sql_cli::data::datatable::{DataColumn, DataRow, DataTable, DataValue};
use sql_cli::data::query_engine::QueryEngine;
use std::fs;
use std::sync::Arc;

/// Load trades.json into a `DataTable`
fn load_trades_table() -> Arc<DataTable> {
    let json_str = fs::read_to_string("data/trades.json").expect("Failed to read trades.json");

    let trades: Vec<Value> = serde_json::from_str(&json_str).expect("Failed to parse trades.json");

    let mut table = DataTable::new("trades");

    // Add columns based on first trade structure
    if let Some(first_trade) = trades.first() {
        if let Value::Object(map) = first_trade {
            for key in map.keys() {
                table.add_column(DataColumn::new(key.clone()));
            }
        }
    }

    // Add rows
    for trade in trades {
        if let Value::Object(map) = trade {
            let mut row_values = Vec::new();

            // Get values in same order as columns
            for col in &table.columns {
                let value = map.get(&col.name).unwrap_or(&Value::Null);
                row_values.push(json_to_datavalue(value));
            }

            table.add_row(DataRow::new(row_values)).unwrap();
        }
    }

    Arc::new(table)
}

fn json_to_datavalue(value: &Value) -> DataValue {
    match value {
        Value::String(s) => DataValue::String(s.clone()),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                DataValue::Integer(i)
            } else if let Some(f) = n.as_f64() {
                DataValue::Float(f)
            } else {
                DataValue::Null
            }
        }
        Value::Bool(b) => DataValue::Boolean(*b),
        Value::Null => DataValue::Null,
        _ => DataValue::Null,
    }
}

#[test]
fn test_load_trades_table() {
    let table = load_trades_table();

    // Verify we loaded the right number of trades
    assert!(table.row_count() > 0);

    // Verify columns exist
    assert!(table.get_column_index("id").is_some());
    assert!(table.get_column_index("book").is_some());
    assert!(table.get_column_index("trader").is_some());
    assert!(table.get_column_index("currency").is_some());
    assert!(table.get_column_index("quantity").is_some());
    assert!(table.get_column_index("price").is_some());

    println!(
        "Loaded {} trades with {} columns",
        table.row_count(),
        table.column_count()
    );
}

#[test]
fn test_select_all_trades() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades")
        .unwrap();

    assert_eq!(view.row_count(), table.row_count());
    assert_eq!(view.column_count(), table.column_count());
}

#[test]
fn test_select_specific_columns() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT id, trader, currency, quantity, price FROM trades",
        )
        .unwrap();

    assert_eq!(view.row_count(), table.row_count());
    assert_eq!(view.column_count(), 5);

    let columns = view.column_names();
    assert_eq!(
        columns,
        vec!["id", "trader", "currency", "quantity", "price"]
    );
}

#[test]
fn test_filter_by_trader() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE trader = 'Jane Doe'",
        )
        .unwrap();

    // Check all results have the right trader
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let trader_index = view.source().get_column_index("trader").unwrap();
        assert_eq!(
            row.values[trader_index],
            DataValue::String("Jane Doe".to_string())
        );
    }
}

#[test]
fn test_filter_by_currency() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades WHERE currency = 'USD'")
        .unwrap();

    // Check all results have USD currency
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let currency_index = view.source().get_column_index("currency").unwrap();
        assert_eq!(
            row.values[currency_index],
            DataValue::String("USD".to_string())
        );
    }
}

#[test]
fn test_filter_by_quantity_range() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades WHERE quantity > 5000")
        .unwrap();

    // Check all results have quantity > 5000
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let qty_index = view.source().get_column_index("quantity").unwrap();
        if let DataValue::Integer(qty) = &row.values[qty_index] {
            assert!(*qty > 5000);
        }
    }
}

#[test]
fn test_filter_by_price_range() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE price BETWEEN 100 AND 300",
        )
        .unwrap();

    // Check all results have price in range
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let price_index = view.source().get_column_index("price").unwrap();
        if let DataValue::Float(price) = &row.values[price_index] {
            assert!(*price >= 100.0 && *price <= 300.0);
        }
    }
}

#[test]
fn test_filter_by_book() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE book LIKE '%EQUITY%'",
        )
        .unwrap();

    // Check all results have EQUITY in book name
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let book_index = view.source().get_column_index("book").unwrap();
        if let DataValue::String(book) = &row.values[book_index] {
            assert!(book.contains("EQUITY"));
        }
    }
}

#[test]
fn test_filter_by_counterparty_in_list() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades WHERE counterparty IN ('JP_MORGAN', 'GOLDMAN_SACHS', 'DEUTSCHE_BANK')")
        .unwrap();

    // Check all results have one of these counterparties
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let cp_index = view.source().get_column_index("counterparty").unwrap();
        if let DataValue::String(cp) = &row.values[cp_index] {
            assert!(cp == "JP_MORGAN" || cp == "GOLDMAN_SACHS" || cp == "DEUTSCHE_BANK");
        }
    }
}

#[test]
fn test_complex_filter_and() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE currency = 'USD' AND quantity > 5000",
        )
        .unwrap();

    // Check all results match both conditions
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();

        let currency_index = view.source().get_column_index("currency").unwrap();
        assert_eq!(
            row.values[currency_index],
            DataValue::String("USD".to_string())
        );

        let qty_index = view.source().get_column_index("quantity").unwrap();
        if let DataValue::Integer(qty) = &row.values[qty_index] {
            assert!(*qty > 5000);
        }
    }
}

#[test]
fn test_complex_filter_or() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE currency = 'EUR' OR currency = 'GBP'",
        )
        .unwrap();

    // Check all results have EUR or GBP
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let currency_index = view.source().get_column_index("currency").unwrap();
        if let DataValue::String(currency) = &row.values[currency_index] {
            assert!(currency == "EUR" || currency == "GBP");
        }
    }
}

#[test]
fn test_select_with_limit() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades LIMIT 10")
        .unwrap();

    assert_eq!(view.row_count(), 10);
}

#[test]
fn test_select_with_limit_offset() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades LIMIT 5 OFFSET 10")
        .unwrap();

    assert_eq!(view.row_count(), 5);

    // Verify it's actually offset by checking IDs
    let first_row = view.get_row(0).unwrap();
    let id_index = view.source().get_column_index("id").unwrap();
    if let DataValue::Integer(id) = &first_row.values[id_index] {
        assert_eq!(*id, 11); // Should be 11th record (offset by 10)
    }
}

#[test]
fn test_order_by_price() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades ORDER BY price ASC LIMIT 10",
        )
        .unwrap();

    // Check that prices are in ascending order
    let price_index = view.source().get_column_index("price").unwrap();
    let mut last_price = 0.0;

    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        if let DataValue::Float(price) = &row.values[price_index] {
            assert!(*price >= last_price);
            last_price = *price;
        }
    }
}

#[test]
fn test_filter_by_date() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE createdDate > '2024-06-01'",
        )
        .unwrap();

    // Check all dates are after June 1, 2024
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let date_index = view.source().get_column_index("createdDate").unwrap();
        if let DataValue::String(date) = &row.values[date_index] {
            assert!(date.as_str() > "2024-06-01");
        }
    }
}

#[test]
fn test_filter_by_confirmation_status() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE confirmationStatus = 'confirmed'",
        )
        .unwrap();

    // Check all have confirmed status
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let status_index = view
            .source()
            .get_column_index("confirmationStatus")
            .unwrap();
        assert_eq!(
            row.values[status_index],
            DataValue::String("confirmed".to_string())
        );
    }
}

#[test]
fn test_projection_with_filter() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT trader, currency, quantity, price FROM trades WHERE price > 500",
        )
        .unwrap();

    // Check we only have 4 columns
    assert_eq!(view.column_count(), 4);

    // Check all prices are > 500
    let price_index = 3; // price is 4th column in our projection
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        if let DataValue::Float(price) = &row.values[price_index] {
            assert!(*price > 500.0);
        }
    }
}

#[test]
fn test_filter_counterparty_type() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE counterpartyType = 'BANK'",
        )
        .unwrap();

    // Check all have BANK type
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let type_index = view.source().get_column_index("counterpartyType").unwrap();
        assert_eq!(
            row.values[type_index],
            DataValue::String("BANK".to_string())
        );
    }
}

// LINQ-style method tests

#[test]
fn test_linq_contains_method() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE trader.Contains('John')",
        )
        .unwrap();

    // Check all results contain 'John' in trader name
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let trader_index = view.source().get_column_index("trader").unwrap();
        if let DataValue::String(trader) = &row.values[trader_index] {
            assert!(
                trader.contains("John"),
                "Trader {trader} should contain 'John'"
            );
        }
    }
}

#[test]
fn test_linq_startswith_method() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE book.StartsWith('EQUITY')",
        )
        .unwrap();

    // Check all results start with 'EQUITY'
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let book_index = view.source().get_column_index("book").unwrap();
        if let DataValue::String(book) = &row.values[book_index] {
            assert!(
                book.starts_with("EQUITY"),
                "Book {book} should start with 'EQUITY'"
            );
        }
    }
}

#[test]
fn test_linq_endswith_method() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE instrumentName.EndsWith('Option')",
        )
        .unwrap();

    // Check all results end with 'Option'
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let inst_index = view.source().get_column_index("instrumentName").unwrap();
        if let DataValue::String(inst) = &row.values[inst_index] {
            assert!(
                inst.ends_with("Option"),
                "Instrument {inst} should end with 'Option'"
            );
        }
    }
}

#[test]
fn test_linq_method_with_and() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(
            table.clone(),
            "SELECT * FROM trades WHERE trader.Contains('John') AND currency = 'USD'",
        )
        .unwrap();

    // Check all results have John in trader name AND USD currency
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();

        let trader_index = view.source().get_column_index("trader").unwrap();
        if let DataValue::String(trader) = &row.values[trader_index] {
            assert!(trader.contains("John"));
        }

        let currency_index = view.source().get_column_index("currency").unwrap();
        assert_eq!(
            row.values[currency_index],
            DataValue::String("USD".to_string())
        );
    }
}

#[test]
fn test_linq_method_complex() {
    let table = load_trades_table();
    let engine = QueryEngine::new();

    let view = engine
        .execute(table.clone(), "SELECT * FROM trades WHERE counterparty.StartsWith('GOLD') OR counterparty.Contains('MORGAN')")
        .unwrap();

    // Check all results have counterparty starting with GOLD or containing MORGAN
    for i in 0..view.row_count() {
        let row = view.get_row(i).unwrap();
        let cp_index = view.source().get_column_index("counterparty").unwrap();
        if let DataValue::String(cp) = &row.values[cp_index] {
            assert!(
                cp.starts_with("GOLD") || cp.contains("MORGAN"),
                "Counterparty {cp} should start with GOLD or contain MORGAN"
            );
        }
    }
}

// Add more test cases as needed...