sql-cli 1.72.0

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
// Window aggregate functions that can handle expressions
// These wrap standard aggregates but evaluate expressions within window contexts

use super::{ExpressionEvaluator, WindowFunction};
use crate::data::datatable::DataValue;
use crate::sql::parser::ast::SqlExpression;
use crate::sql::window_context::WindowContext;
use anyhow::{anyhow, Result};

/// Window SUM aggregate that can handle expressions
/// Example: SUM(price * quantity) OVER (PARTITION BY ...)
pub struct WindowSumFunction;

impl WindowFunction for WindowSumFunction {
    fn name(&self) -> &str {
        "SUM"
    }

    fn description(&self) -> &str {
        "Calculate sum of expression over window"
    }

    fn signature(&self) -> &str {
        "SUM(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        if args.is_empty() {
            return Err(anyhow!("SUM requires 1 argument"));
        }

        // Get the rows to sum over (frame-aware)
        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        // Evaluate the expression for each row and sum
        let mut sum: Option<DataValue> = None;
        let mut has_non_null = false;

        for &frame_row_idx in &frame_rows {
            // Evaluate the expression at this row
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;

            if !matches!(value, DataValue::Null) {
                has_non_null = true;
                match (&sum, &value) {
                    (None, DataValue::Integer(v)) => sum = Some(DataValue::Integer(*v)),
                    (None, DataValue::Float(v)) => sum = Some(DataValue::Float(*v)),
                    (Some(DataValue::Integer(s)), DataValue::Integer(v)) => {
                        sum = Some(DataValue::Integer(s + v));
                    }
                    (Some(DataValue::Integer(s)), DataValue::Float(v)) => {
                        sum = Some(DataValue::Float(*s as f64 + v));
                    }
                    (Some(DataValue::Float(s)), DataValue::Integer(v)) => {
                        sum = Some(DataValue::Float(s + *v as f64));
                    }
                    (Some(DataValue::Float(s)), DataValue::Float(v)) => {
                        sum = Some(DataValue::Float(s + v));
                    }
                    _ => {} // Skip non-numeric values
                }
            }
        }

        Ok(sum.unwrap_or(DataValue::Null))
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() != 1 {
            return Err(anyhow!("SUM requires exactly 1 argument"));
        }
        Ok(())
    }
}

/// Window AVG aggregate that can handle expressions
pub struct WindowAvgFunction;

impl WindowFunction for WindowAvgFunction {
    fn name(&self) -> &str {
        "AVG"
    }

    fn description(&self) -> &str {
        "Calculate average of expression over window"
    }

    fn signature(&self) -> &str {
        "AVG(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        if args.is_empty() {
            return Err(anyhow!("AVG requires 1 argument"));
        }

        // Get the rows to average over
        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        // Evaluate the expression for each row and compute average
        let mut sum = 0.0;
        let mut count = 0;

        for &frame_row_idx in &frame_rows {
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;

            match value {
                DataValue::Integer(v) => {
                    sum += v as f64;
                    count += 1;
                }
                DataValue::Float(v) => {
                    sum += v;
                    count += 1;
                }
                DataValue::Null => {} // Skip nulls
                _ => {}               // Skip non-numeric values
            }
        }

        if count > 0 {
            Ok(DataValue::Float(sum / count as f64))
        } else {
            Ok(DataValue::Null)
        }
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() != 1 {
            return Err(anyhow!("AVG requires exactly 1 argument"));
        }
        Ok(())
    }
}

/// Window MIN aggregate that can handle expressions
pub struct WindowMinFunction;

impl WindowFunction for WindowMinFunction {
    fn name(&self) -> &str {
        "MIN"
    }

    fn description(&self) -> &str {
        "Calculate minimum of expression over window"
    }

    fn signature(&self) -> &str {
        "MIN(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        if args.is_empty() {
            return Err(anyhow!("MIN requires 1 argument"));
        }

        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        let mut min_value: Option<DataValue> = None;

        for &frame_row_idx in &frame_rows {
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;

            if !matches!(value, DataValue::Null) {
                match &min_value {
                    None => min_value = Some(value),
                    Some(current_min) => {
                        if value < *current_min {
                            min_value = Some(value);
                        }
                    }
                }
            }
        }

        Ok(min_value.unwrap_or(DataValue::Null))
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() != 1 {
            return Err(anyhow!("MIN requires exactly 1 argument"));
        }
        Ok(())
    }
}

/// Window MAX aggregate that can handle expressions
pub struct WindowMaxFunction;

impl WindowFunction for WindowMaxFunction {
    fn name(&self) -> &str {
        "MAX"
    }

    fn description(&self) -> &str {
        "Calculate maximum of expression over window"
    }

    fn signature(&self) -> &str {
        "MAX(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        if args.is_empty() {
            return Err(anyhow!("MAX requires 1 argument"));
        }

        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        let mut max_value: Option<DataValue> = None;

        for &frame_row_idx in &frame_rows {
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;

            if !matches!(value, DataValue::Null) {
                match &max_value {
                    None => max_value = Some(value),
                    Some(current_max) => {
                        if value > *current_max {
                            max_value = Some(value);
                        }
                    }
                }
            }
        }

        Ok(max_value.unwrap_or(DataValue::Null))
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() != 1 {
            return Err(anyhow!("MAX requires exactly 1 argument"));
        }
        Ok(())
    }
}

/// Window COUNT aggregate that can handle expressions
pub struct WindowCountFunction;

impl WindowFunction for WindowCountFunction {
    fn name(&self) -> &str {
        "COUNT"
    }

    fn description(&self) -> &str {
        "Count non-null values of expression over window"
    }

    fn signature(&self) -> &str {
        "COUNT(expression | *) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        // Handle COUNT(*)
        if args.is_empty()
            || (args.len() == 1
                && matches!(&args[0],
                SqlExpression::Column(col) if col.name == "*" || 
                matches!(&args[0], SqlExpression::StringLiteral(s) if s == "*")))
        {
            return Ok(DataValue::Integer(frame_rows.len() as i64));
        }

        // COUNT(expression) - count non-null values
        let mut count = 0;
        for &frame_row_idx in &frame_rows {
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;
            if !matches!(value, DataValue::Null) {
                count += 1;
            }
        }

        Ok(DataValue::Integer(count))
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() > 1 {
            return Err(anyhow!("COUNT requires 0 or 1 arguments"));
        }
        Ok(())
    }
}

/// Window STDDEV aggregate that can handle expressions
pub struct WindowStddevFunction;

impl WindowFunction for WindowStddevFunction {
    fn name(&self) -> &str {
        "STDDEV"
    }

    fn description(&self) -> &str {
        "Calculate standard deviation of expression over window"
    }

    fn signature(&self) -> &str {
        "STDDEV(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        if args.is_empty() {
            return Err(anyhow!("STDDEV requires 1 argument"));
        }

        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        // Collect values
        let mut values = Vec::new();
        for &frame_row_idx in &frame_rows {
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;
            match value {
                DataValue::Integer(v) => values.push(v as f64),
                DataValue::Float(v) => values.push(v),
                DataValue::Null => {} // Skip nulls
                _ => {}               // Skip non-numeric
            }
        }

        if values.len() <= 1 {
            return Ok(DataValue::Null);
        }

        // Calculate mean
        let mean = values.iter().sum::<f64>() / values.len() as f64;

        // Calculate standard deviation
        let variance =
            values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (values.len() - 1) as f64;

        Ok(DataValue::Float(variance.sqrt()))
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() != 1 {
            return Err(anyhow!("STDDEV requires exactly 1 argument"));
        }
        Ok(())
    }
}

/// Window VARIANCE aggregate that can handle expressions
pub struct WindowVarianceFunction;

impl WindowFunction for WindowVarianceFunction {
    fn name(&self) -> &str {
        "VARIANCE"
    }

    fn description(&self) -> &str {
        "Calculate variance of expression over window"
    }

    fn signature(&self) -> &str {
        "VARIANCE(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        if args.is_empty() {
            return Err(anyhow!("VARIANCE requires 1 argument"));
        }

        let frame_rows = if context.has_frame() {
            context.get_frame_rows(row_index)
        } else {
            context.get_partition_rows(row_index)
        };

        // Collect values
        let mut values = Vec::new();
        for &frame_row_idx in &frame_rows {
            let value = evaluator.evaluate(&args[0], frame_row_idx)?;
            match value {
                DataValue::Integer(v) => values.push(v as f64),
                DataValue::Float(v) => values.push(v),
                DataValue::Null => {} // Skip nulls
                _ => {}               // Skip non-numeric
            }
        }

        if values.len() <= 1 {
            return Ok(DataValue::Null);
        }

        // Calculate mean
        let mean = values.iter().sum::<f64>() / values.len() as f64;

        // Calculate variance
        let variance =
            values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (values.len() - 1) as f64;

        Ok(DataValue::Float(variance))
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        if args.len() != 1 {
            return Err(anyhow!("VARIANCE requires exactly 1 argument"));
        }
        Ok(())
    }
}

/// Alias for STDDEV
pub struct WindowStdevFunction;

impl WindowFunction for WindowStdevFunction {
    fn name(&self) -> &str {
        "STDEV"
    }

    fn description(&self) -> &str {
        "Calculate standard deviation of expression over window (alias for STDDEV)"
    }

    fn signature(&self) -> &str {
        "STDEV(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        // Delegate to STDDEV implementation
        WindowStddevFunction.compute(context, row_index, args, evaluator)
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        WindowStddevFunction.validate_args(args)
    }
}

/// Alias for VARIANCE
pub struct WindowVarFunction;

impl WindowFunction for WindowVarFunction {
    fn name(&self) -> &str {
        "VAR"
    }

    fn description(&self) -> &str {
        "Calculate variance of expression over window (alias for VARIANCE)"
    }

    fn signature(&self) -> &str {
        "VAR(expression) OVER (...)"
    }

    fn compute(
        &self,
        context: &WindowContext,
        row_index: usize,
        args: &[SqlExpression],
        evaluator: &mut dyn ExpressionEvaluator,
    ) -> Result<DataValue> {
        // Delegate to VARIANCE implementation
        WindowVarianceFunction.compute(context, row_index, args, evaluator)
    }

    fn validate_args(&self, args: &[SqlExpression]) -> Result<()> {
        WindowVarianceFunction.validate_args(args)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sql::parser::ast::ColumnRef;

    #[test]
    fn test_window_sum_function() {
        let func = WindowSumFunction;
        assert_eq!(func.name(), "SUM");

        // Validate args
        let args = vec![SqlExpression::Column(ColumnRef::unquoted(
            "amount".to_string(),
        ))];
        assert!(func.validate_args(&args).is_ok());

        let empty_args: Vec<SqlExpression> = vec![];
        assert!(func.validate_args(&empty_args).is_err());
    }

    #[test]
    fn test_window_count_function() {
        let func = WindowCountFunction;
        assert_eq!(func.name(), "COUNT");

        // COUNT(*) with no args is valid
        let empty_args: Vec<SqlExpression> = vec![];
        assert!(func.validate_args(&empty_args).is_ok());

        // COUNT(column) is valid
        let args = vec![SqlExpression::Column(ColumnRef::unquoted("id".to_string()))];
        assert!(func.validate_args(&args).is_ok());

        // COUNT with 2 args is invalid
        let two_args = vec![
            SqlExpression::Column(ColumnRef::unquoted("id".to_string())),
            SqlExpression::Column(ColumnRef::unquoted("name".to_string())),
        ];
        assert!(func.validate_args(&two_args).is_err());
    }
}