sql-cli 1.70.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
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
use crate::data::datatable::DataValue;
use crate::sql::functions::{ArgCount, FunctionCategory, FunctionSignature, SqlFunction};
use anyhow::{anyhow, Result};

/// RENDER_NUMBER function - Format numbers with various separators and abbreviations
pub struct RenderNumberFunction;

impl SqlFunction for RenderNumberFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "RENDER_NUMBER",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(1, 3),
            description: "Format numbers with separators, abbreviations, or regional formats",
            returns: "STRING",
            examples: vec![
                "SELECT RENDER_NUMBER(1234567.89)",             // "1,234,567.89"
                "SELECT RENDER_NUMBER(1234567.89, 'compact')",  // "1.2M"
                "SELECT RENDER_NUMBER(1234.56, 'eu')",          // "1.234,56"
                "SELECT RENDER_NUMBER(-1234.56, 'accounting')", // "(1,234.56)"
                "SELECT RENDER_NUMBER(1500000, 'compact', 1)",  // "1.5M"
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let value = match &args[0] {
            DataValue::Integer(n) => *n as f64,
            DataValue::Float(f) => *f,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("RENDER_NUMBER requires a numeric value")),
        };

        let format = if args.len() >= 2 {
            match &args[1] {
                DataValue::String(s) => s.to_lowercase(),
                DataValue::Null => "standard".to_string(),
                _ => "standard".to_string(),
            }
        } else {
            "standard".to_string()
        };

        let decimals = if args.len() >= 3 {
            match &args[2] {
                DataValue::Integer(n) => *n as usize,
                DataValue::Float(f) => *f as usize,
                _ => 2,
            }
        } else {
            2
        };

        let formatted = match format.as_str() {
            "compact" => format_compact(value, decimals),
            "eu" | "european" => format_european(value, decimals),
            "ch" | "swiss" => format_swiss(value, decimals),
            "in" | "indian" => format_indian(value, decimals),
            "accounting" => format_accounting(value, decimals),
            _ => format_standard(value, decimals), // Default US/UK style
        };

        Ok(DataValue::String(formatted))
    }
}

/// FORMAT_CURRENCY function - Format numbers as currency with flexible options
pub struct FormatCurrencyFunction;

impl SqlFunction for FormatCurrencyFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "FORMAT_CURRENCY",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(2, 4),
            description: "Format numbers as currency with symbols, codes, or names. Currency can be from a column.",
            returns: "STRING",
            examples: vec![
                "SELECT FORMAT_CURRENCY(1234.56, 'USD')",              // "$1,234.56"
                "SELECT FORMAT_CURRENCY(1234.56, 'GBP', 'symbol')",    // "£1,234.56"
                "SELECT FORMAT_CURRENCY(amount, currency_code)",       // Uses currency from column
                "SELECT FORMAT_CURRENCY(3000, 'GBP', 'compact_code')", // "3k GBP"
                "SELECT FORMAT_CURRENCY(1234.56, 'EUR', 'eu')",        // "1.234,56 €"
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let value = match &args[0] {
            DataValue::Integer(n) => *n as f64,
            DataValue::Float(f) => *f,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("FORMAT_CURRENCY requires a numeric value")),
        };

        let currency_code = match &args[1] {
            DataValue::String(s) => s.to_uppercase(),
            DataValue::Null => return Ok(DataValue::Null),
            _ => {
                return Err(anyhow!(
                    "FORMAT_CURRENCY requires a currency code (e.g., 'USD', 'EUR', 'GBP')"
                ))
            }
        };

        let format = if args.len() >= 3 {
            match &args[2] {
                DataValue::String(s) => s.to_lowercase(),
                DataValue::Null => "symbol".to_string(),
                _ => "symbol".to_string(),
            }
        } else {
            "symbol".to_string()
        };

        let decimals_override = if args.len() >= 4 {
            match &args[3] {
                DataValue::Integer(n) => Some(*n as usize),
                DataValue::Float(f) => Some(*f as usize),
                _ => None,
            }
        } else {
            None
        };

        let currency_info = get_currency_info(&currency_code);
        let decimals = decimals_override.unwrap_or(currency_info.decimals as usize);

        let formatted = format_currency(value, &currency_code, &format, decimals, &currency_info);

        Ok(DataValue::String(formatted))
    }
}

// Currency information structure
struct CurrencyInfo {
    symbol: &'static str,
    name: &'static str,
    decimals: u8,
    symbol_before: bool,
}

// Get currency information
fn get_currency_info(code: &str) -> CurrencyInfo {
    match code {
        "USD" => CurrencyInfo {
            symbol: "$",
            name: "US dollar",
            decimals: 2,
            symbol_before: true,
        },
        "EUR" => CurrencyInfo {
            symbol: "",
            name: "Euro",
            decimals: 2,
            symbol_before: true,
        },
        "GBP" => CurrencyInfo {
            symbol: "£",
            name: "British pound",
            decimals: 2,
            symbol_before: true,
        },
        "JPY" | "YEN" => CurrencyInfo {
            symbol: "¥",
            name: "Japanese yen",
            decimals: 0,
            symbol_before: true,
        },
        "CHF" => CurrencyInfo {
            symbol: "CHF",
            name: "Swiss franc",
            decimals: 2,
            symbol_before: true,
        },
        "CNY" | "RMB" => CurrencyInfo {
            symbol: "¥",
            name: "Chinese yuan",
            decimals: 2,
            symbol_before: true,
        },
        "INR" => CurrencyInfo {
            symbol: "",
            name: "Indian rupee",
            decimals: 2,
            symbol_before: true,
        },
        "AUD" => CurrencyInfo {
            symbol: "A$",
            name: "Australian dollar",
            decimals: 2,
            symbol_before: true,
        },
        "CAD" => CurrencyInfo {
            symbol: "C$",
            name: "Canadian dollar",
            decimals: 2,
            symbol_before: true,
        },
        "SEK" => CurrencyInfo {
            symbol: "kr",
            name: "Swedish krona",
            decimals: 2,
            symbol_before: false,
        },
        "NOK" => CurrencyInfo {
            symbol: "kr",
            name: "Norwegian krone",
            decimals: 2,
            symbol_before: false,
        },
        "DKK" => CurrencyInfo {
            symbol: "kr",
            name: "Danish krone",
            decimals: 2,
            symbol_before: false,
        },
        _ => CurrencyInfo {
            symbol: "¤", // Generic currency symbol
            name: "Unknown currency",
            decimals: 2,
            symbol_before: false,
        },
    }
}

// Format currency based on options
fn format_currency(
    value: f64,
    code: &str,
    format: &str,
    decimals: usize,
    info: &CurrencyInfo,
) -> String {
    let is_negative = value < 0.0;
    let abs_value = value.abs();

    match format {
        "accounting" => {
            // Accounting format: negative numbers in parentheses
            let formatted = format_standard(abs_value, decimals);
            if info.symbol_before {
                if is_negative {
                    format!("({}{})", info.symbol, formatted)
                } else {
                    format!("{}{}", info.symbol, formatted)
                }
            } else {
                if is_negative {
                    format!("({}{})", formatted, info.symbol)
                } else {
                    format!("{}{}", formatted, info.symbol)
                }
            }
        }
        "accounting_code" => {
            // Accounting format with currency code
            let formatted = format_standard(abs_value, decimals);
            if is_negative {
                format!("({} {})", formatted, code)
            } else {
                format!("{} {}", formatted, code)
            }
        }
        "compact" => {
            let compact = format_compact(abs_value, decimals.min(1));
            if info.symbol_before {
                format!(
                    "{}{}{}",
                    if is_negative { "-" } else { "" },
                    info.symbol,
                    compact
                )
            } else {
                format!(
                    "{}{}{}",
                    if is_negative { "-" } else { "" },
                    compact,
                    info.symbol
                )
            }
        }
        "compact_code" => {
            let compact = format_compact(abs_value, decimals.min(1));
            format!("{}{} {}", if is_negative { "-" } else { "" }, compact, code)
        }
        "code" => {
            let formatted = format_standard(abs_value, decimals);
            format!(
                "{}{} {}",
                if is_negative { "-" } else { "" },
                formatted,
                code
            )
        }
        "name" => {
            let formatted = format_standard(abs_value, decimals);
            let plural = if abs_value != 1.0 { "s" } else { "" };
            format!(
                "{}{} {}{}",
                if is_negative { "-" } else { "" },
                formatted,
                info.name,
                plural
            )
        }
        "eu" | "european" => {
            let formatted = format_european(abs_value, decimals);
            if code == "EUR" {
                format!("{}{}", if is_negative { "-" } else { "" }, formatted)
            } else {
                format!(
                    "{}{} {}",
                    if is_negative { "-" } else { "" },
                    formatted,
                    code
                )
            }
        }
        "ch" | "swiss" => {
            let formatted = format_swiss(abs_value, decimals);
            format!(
                "{}{} {}",
                if is_negative { "-" } else { "" },
                code,
                formatted
            )
        }
        _ => {
            // Default "symbol" format
            let formatted = format_standard(abs_value, decimals);
            if info.symbol_before {
                format!(
                    "{}{}{}",
                    if is_negative { "-" } else { "" },
                    info.symbol,
                    formatted
                )
            } else {
                format!(
                    "{}{}{}",
                    if is_negative { "-" } else { "" },
                    formatted,
                    info.symbol
                )
            }
        }
    }
}

// Format with US/UK style (comma thousands, period decimal)
fn format_standard(value: f64, decimals: usize) -> String {
    let formatted = format!("{:.prec$}", value, prec = decimals);
    add_separators(&formatted, ',', '.')
}

// Format with European style (period thousands, comma decimal)
fn format_european(value: f64, decimals: usize) -> String {
    let formatted = format!("{:.prec$}", value, prec = decimals);
    add_separators(&formatted, '.', ',')
}

// Format with Swiss style (apostrophe thousands, period decimal)
fn format_swiss(value: f64, decimals: usize) -> String {
    let formatted = format!("{:.prec$}", value, prec = decimals);
    add_separators(&formatted, '\'', '.')
}

// Format with Indian style (lakhs and crores)
fn format_indian(value: f64, decimals: usize) -> String {
    let formatted = format!("{:.prec$}", value, prec = decimals);
    add_indian_separators(&formatted)
}

// Format with accounting style (negatives in parentheses)
fn format_accounting(value: f64, decimals: usize) -> String {
    let is_negative = value < 0.0;
    let abs_value = value.abs();
    let formatted = format!("{:.prec$}", abs_value, prec = decimals);
    let with_separators = add_separators(&formatted, ',', '.');

    if is_negative {
        format!("({})", with_separators)
    } else {
        with_separators
    }
}

// Format in compact notation (k, M, B, T)
fn format_compact(value: f64, decimals: usize) -> String {
    let (num, suffix) = if value >= 1_000_000_000_000.0 {
        (value / 1_000_000_000_000.0, "T")
    } else if value >= 1_000_000_000.0 {
        (value / 1_000_000_000.0, "B")
    } else if value >= 1_000_000.0 {
        (value / 1_000_000.0, "M")
    } else if value >= 1_000.0 {
        (value / 1_000.0, "k")
    } else {
        (value, "")
    };

    if suffix.is_empty() {
        format!("{:.prec$}", num, prec = decimals)
    } else {
        // Remove trailing zeros and decimal point if not needed
        let formatted = format!("{:.prec$}", num, prec = decimals);
        let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');
        format!("{}{}", trimmed, suffix)
    }
}

// Add thousand separators with specified characters
fn add_separators(formatted: &str, thousand_sep: char, decimal_sep: char) -> String {
    let parts: Vec<&str> = formatted.split('.').collect();
    let integer_part = parts[0];
    let decimal_part = parts.get(1);

    let mut result = String::new();
    let mut count = 0;

    for ch in integer_part.chars().rev() {
        if count == 3 {
            result.push(thousand_sep);
            count = 0;
        }
        result.push(ch);
        count += 1;
    }

    let mut final_result: String = result.chars().rev().collect();

    if let Some(dec) = decimal_part {
        final_result.push(decimal_sep);
        final_result.push_str(dec);
    }

    final_result
}

// Add Indian-style separators (lakhs and crores)
fn add_indian_separators(formatted: &str) -> String {
    let parts: Vec<&str> = formatted.split('.').collect();
    let integer_part = parts[0];
    let decimal_part = parts.get(1);

    let mut result = String::new();
    let chars: Vec<char> = integer_part.chars().rev().collect();

    for (i, ch) in chars.iter().enumerate() {
        if i == 3 || (i > 3 && i % 2 == 1) {
            result.push(',');
        }
        result.push(*ch);
    }

    let mut final_result: String = result.chars().rev().collect();

    if let Some(dec) = decimal_part {
        final_result.push('.');
        final_result.push_str(dec);
    }

    final_result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_render_number_standard() {
        let func = RenderNumberFunction;

        let result = func.evaluate(&[DataValue::Float(1234567.89)]).unwrap();
        assert_eq!(result, DataValue::String("1,234,567.89".to_string()));

        let result = func.evaluate(&[DataValue::Integer(1000)]).unwrap();
        assert_eq!(result, DataValue::String("1,000.00".to_string()));
    }

    #[test]
    fn test_render_number_compact() {
        let func = RenderNumberFunction;

        let result = func
            .evaluate(&[
                DataValue::Float(1500000.0),
                DataValue::String("compact".to_string()),
            ])
            .unwrap();
        assert_eq!(result, DataValue::String("1.5M".to_string()));

        let result = func
            .evaluate(&[
                DataValue::Integer(3000),
                DataValue::String("compact".to_string()),
            ])
            .unwrap();
        assert_eq!(result, DataValue::String("3k".to_string()));
    }

    #[test]
    fn test_format_currency() {
        let func = FormatCurrencyFunction;

        let result = func
            .evaluate(&[
                DataValue::Float(1234.56),
                DataValue::String("USD".to_string()),
            ])
            .unwrap();
        assert_eq!(result, DataValue::String("$1,234.56".to_string()));

        let result = func
            .evaluate(&[
                DataValue::Float(1234.56),
                DataValue::String("GBP".to_string()),
            ])
            .unwrap();
        assert_eq!(result, DataValue::String("£1,234.56".to_string()));

        let result = func
            .evaluate(&[
                DataValue::Integer(3000),
                DataValue::String("GBP".to_string()),
                DataValue::String("compact_code".to_string()),
            ])
            .unwrap();
        assert_eq!(result, DataValue::String("3k GBP".to_string()));
    }
}

// ============================================================================
// FORMAT_BYTES — human-readable byte sizes (like `ls -lh` / `du -h`)
// ============================================================================

/// FORMAT_BYTES function - Format byte counts as human-readable sizes
pub struct FormatBytesFunction;

impl SqlFunction for FormatBytesFunction {
    fn signature(&self) -> FunctionSignature {
        FunctionSignature {
            name: "FORMAT_BYTES",
            category: FunctionCategory::String,
            arg_count: ArgCount::Range(1, 2),
            description:
                "Format byte counts as human-readable sizes (KB, MB, GB, etc.) like ls -lh",
            returns: "STRING",
            examples: vec![
                "SELECT FORMAT_BYTES(1024)",       // "1.0 KB"
                "SELECT FORMAT_BYTES(1536000)",    // "1.5 MB"
                "SELECT FORMAT_BYTES(2147483648)", // "2.0 GB"
                "SELECT FORMAT_BYTES(819770)",     // "800.6 KB"
                "SELECT FORMAT_BYTES(1536000, 0)", // "1 MB"
                "SELECT FORMAT_BYTES(1536000, 2)", // "1.46 MB"
            ],
        }
    }

    fn evaluate(&self, args: &[DataValue]) -> Result<DataValue> {
        self.validate_args(args)?;

        let bytes = match &args[0] {
            DataValue::Integer(n) => *n as f64,
            DataValue::Float(f) => *f,
            DataValue::Null => return Ok(DataValue::Null),
            _ => return Err(anyhow!("FORMAT_BYTES requires a numeric value")),
        };

        let decimals = if args.len() >= 2 {
            match &args[1] {
                DataValue::Integer(n) => *n as usize,
                DataValue::Float(f) => *f as usize,
                _ => 1,
            }
        } else {
            1
        };

        let abs_bytes = bytes.abs();
        let sign = if bytes < 0.0 { "-" } else { "" };

        let (value, unit) = if abs_bytes < 1024.0 {
            (abs_bytes, "B")
        } else if abs_bytes < 1024.0 * 1024.0 {
            (abs_bytes / 1024.0, "KB")
        } else if abs_bytes < 1024.0 * 1024.0 * 1024.0 {
            (abs_bytes / (1024.0 * 1024.0), "MB")
        } else if abs_bytes < 1024.0 * 1024.0 * 1024.0 * 1024.0 {
            (abs_bytes / (1024.0 * 1024.0 * 1024.0), "GB")
        } else if abs_bytes < 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0 {
            (abs_bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0), "TB")
        } else {
            (
                abs_bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0),
                "PB",
            )
        };

        let formatted = format!("{sign}{value:.decimals$} {unit}");
        Ok(DataValue::String(formatted))
    }
}