Skip to main content

sql_splitter/duckdb/
output.rs

1//! Output formatting for query results.
2
3use super::QueryResult;
4use std::io::Write;
5
6/// Output format for query results
7#[derive(Debug, Clone, Copy, PartialEq, Default)]
8pub enum OutputFormat {
9    /// ASCII table format (default)
10    #[default]
11    Table,
12    /// JSON array format
13    Json,
14    /// JSON lines format (one object per line)
15    JsonLines,
16    /// CSV format
17    Csv,
18    /// Tab-separated values
19    Tsv,
20}
21
22impl std::str::FromStr for OutputFormat {
23    type Err = String;
24
25    fn from_str(s: &str) -> Result<Self, Self::Err> {
26        match s.to_lowercase().as_str() {
27            "table" => Ok(OutputFormat::Table),
28            "json" => Ok(OutputFormat::Json),
29            "jsonl" | "jsonlines" | "ndjson" => Ok(OutputFormat::JsonLines),
30            "csv" => Ok(OutputFormat::Csv),
31            "tsv" => Ok(OutputFormat::Tsv),
32            _ => Err(format!(
33                "Unknown format: {}. Valid: table, json, jsonl, csv, tsv",
34                s
35            )),
36        }
37    }
38}
39
40impl std::fmt::Display for OutputFormat {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            OutputFormat::Table => write!(f, "table"),
44            OutputFormat::Json => write!(f, "json"),
45            OutputFormat::JsonLines => write!(f, "jsonl"),
46            OutputFormat::Csv => write!(f, "csv"),
47            OutputFormat::Tsv => write!(f, "tsv"),
48        }
49    }
50}
51
52/// Formatter for query results
53pub struct QueryResultFormatter;
54
55impl QueryResultFormatter {
56    /// Format a query result to a string
57    pub fn format(result: &QueryResult, format: OutputFormat) -> String {
58        match format {
59            OutputFormat::Table => Self::format_table(result),
60            OutputFormat::Json => Self::format_json(result),
61            OutputFormat::JsonLines => Self::format_jsonl(result),
62            OutputFormat::Csv => Self::format_csv(result),
63            OutputFormat::Tsv => Self::format_tsv(result),
64        }
65    }
66
67    /// Write formatted result to a writer
68    pub fn write<W: Write>(
69        result: &QueryResult,
70        format: OutputFormat,
71        writer: &mut W,
72    ) -> std::io::Result<()> {
73        let output = Self::format(result, format);
74        writer.write_all(output.as_bytes())
75    }
76
77    /// Format as ASCII table
78    fn format_table(result: &QueryResult) -> String {
79        if result.columns.is_empty() {
80            return String::new();
81        }
82
83        // Calculate column widths
84        let mut widths: Vec<usize> = result.columns.iter().map(|c| c.chars().count()).collect();
85
86        for row in &result.rows {
87            for (i, val) in row.iter().enumerate() {
88                if i < widths.len() {
89                    widths[i] = widths[i].max(val.chars().count());
90                }
91            }
92        }
93
94        // Cap widths at 50 chars for readability
95        let max_width = 50;
96        widths.iter_mut().for_each(|w| *w = (*w).min(max_width));
97
98        let mut output = String::new();
99
100        // Top border
101        output.push('┌');
102        for (i, width) in widths.iter().enumerate() {
103            output.push_str(&"─".repeat(*width + 2));
104            if i < widths.len() - 1 {
105                output.push('┬');
106            }
107        }
108        output.push_str("┐\n");
109
110        // Header row
111        output.push('│');
112        for (i, col) in result.columns.iter().enumerate() {
113            let truncated = Self::truncate(col, widths[i]);
114            output.push_str(&format!(" {:width$} │", truncated, width = widths[i]));
115        }
116        output.push('\n');
117
118        // Header separator
119        output.push('├');
120        for (i, width) in widths.iter().enumerate() {
121            output.push_str(&"─".repeat(*width + 2));
122            if i < widths.len() - 1 {
123                output.push('┼');
124            }
125        }
126        output.push_str("┤\n");
127
128        // Data rows
129        for row in &result.rows {
130            output.push('│');
131            for (i, val) in row.iter().enumerate() {
132                if i < widths.len() {
133                    let truncated = Self::truncate(val, widths[i]);
134                    output.push_str(&format!(" {:width$} │", truncated, width = widths[i]));
135                }
136            }
137            output.push('\n');
138        }
139
140        // Bottom border
141        output.push('└');
142        for (i, width) in widths.iter().enumerate() {
143            output.push_str(&"─".repeat(*width + 2));
144            if i < widths.len() - 1 {
145                output.push('┴');
146            }
147        }
148        output.push_str("┘\n");
149
150        // Row count
151        output.push_str(&format!(
152            "{} row{}\n",
153            result.rows.len(),
154            if result.rows.len() == 1 { "" } else { "s" }
155        ));
156
157        output
158    }
159
160    /// Truncate a string to a maximum length
161    fn truncate(s: &str, max_len: usize) -> String {
162        if s.chars().count() <= max_len {
163            s.to_string()
164        } else {
165            let prefix: String = s.chars().take(max_len.saturating_sub(1)).collect();
166            format!("{prefix}…")
167        }
168    }
169
170    /// Format as JSON array
171    fn format_json(result: &QueryResult) -> String {
172        let rows: Vec<serde_json::Value> = result
173            .rows
174            .iter()
175            .map(|row| {
176                let obj: serde_json::Map<String, serde_json::Value> = result
177                    .columns
178                    .iter()
179                    .zip(row.iter())
180                    .map(|(col, val)| (col.clone(), Self::json_value(val)))
181                    .collect();
182                serde_json::Value::Object(obj)
183            })
184            .collect();
185
186        serde_json::to_string_pretty(&rows).unwrap_or_else(|_| "[]".to_string())
187    }
188
189    /// Format as JSON lines (NDJSON)
190    fn format_jsonl(result: &QueryResult) -> String {
191        result
192            .rows
193            .iter()
194            .map(|row| {
195                let obj: serde_json::Map<String, serde_json::Value> = result
196                    .columns
197                    .iter()
198                    .zip(row.iter())
199                    .map(|(col, val)| (col.clone(), Self::json_value(val)))
200                    .collect();
201                serde_json::to_string(&serde_json::Value::Object(obj))
202                    .unwrap_or_else(|_| "{}".to_string())
203            })
204            .collect::<Vec<_>>()
205            .join("\n")
206    }
207
208    /// Convert a string value to appropriate JSON type
209    fn json_value(val: &str) -> serde_json::Value {
210        if val == "NULL" {
211            return serde_json::Value::Null;
212        }
213
214        // Try to parse as number
215        if let Ok(n) = val.parse::<i64>() {
216            return serde_json::Value::Number(n.into());
217        }
218        if let Ok(n) = val.parse::<f64>() {
219            if let Some(num) = serde_json::Number::from_f64(n) {
220                return serde_json::Value::Number(num);
221            }
222        }
223
224        // Try to parse as boolean
225        if val.eq_ignore_ascii_case("true") {
226            return serde_json::Value::Bool(true);
227        }
228        if val.eq_ignore_ascii_case("false") {
229            return serde_json::Value::Bool(false);
230        }
231
232        // Return as string
233        serde_json::Value::String(val.to_string())
234    }
235
236    /// Format as CSV
237    fn format_csv(result: &QueryResult) -> String {
238        let mut output = String::new();
239
240        // Header
241        output.push_str(&Self::csv_row(&result.columns));
242        output.push('\n');
243
244        // Data rows
245        for row in &result.rows {
246            output.push_str(&Self::csv_row(row));
247            output.push('\n');
248        }
249
250        output
251    }
252
253    /// Format a single CSV row
254    fn csv_row(values: &[String]) -> String {
255        values
256            .iter()
257            .map(|v| Self::csv_escape(v))
258            .collect::<Vec<_>>()
259            .join(",")
260    }
261
262    /// Escape a value for CSV
263    fn csv_escape(val: &str) -> String {
264        if val.contains(',') || val.contains('"') || val.contains('\n') || val.contains('\r') {
265            format!("\"{}\"", val.replace('"', "\"\""))
266        } else {
267            val.to_string()
268        }
269    }
270
271    /// Format as TSV
272    fn format_tsv(result: &QueryResult) -> String {
273        let mut output = String::new();
274
275        // Header
276        output.push_str(&result.columns.join("\t"));
277        output.push('\n');
278
279        // Data rows
280        for row in &result.rows {
281            let escaped: Vec<String> = row
282                .iter()
283                .map(|v| v.replace('\t', "\\t").replace('\n', "\\n"))
284                .collect();
285            output.push_str(&escaped.join("\t"));
286            output.push('\n');
287        }
288
289        output
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    fn sample_result() -> QueryResult {
298        QueryResult {
299            columns: vec!["id".to_string(), "name".to_string(), "age".to_string()],
300            column_types: vec![
301                "INTEGER".to_string(),
302                "VARCHAR".to_string(),
303                "INTEGER".to_string(),
304            ],
305            rows: vec![
306                vec!["1".to_string(), "Alice".to_string(), "30".to_string()],
307                vec!["2".to_string(), "Bob".to_string(), "25".to_string()],
308            ],
309            execution_time_secs: 0.001,
310        }
311    }
312
313    #[test]
314    fn test_format_table() {
315        let result = sample_result();
316        let output = QueryResultFormatter::format(&result, OutputFormat::Table);
317        assert!(output.contains("Alice"));
318        assert!(output.contains("Bob"));
319        assert!(output.contains("2 rows"));
320    }
321
322    #[test]
323    fn table_output_truncates_unicode_without_panicking() {
324        let mut result = sample_result();
325        result.rows = vec![vec!["あ".repeat(51), "値".to_string(), "1".to_string()]];
326
327        let output = QueryResultFormatter::format(&result, OutputFormat::Table);
328
329        assert!(output.contains("あ"));
330        assert!(output.contains('…'));
331    }
332
333    #[test]
334    fn test_format_json() {
335        let result = sample_result();
336        let output = QueryResultFormatter::format(&result, OutputFormat::Json);
337        let parsed: Vec<serde_json::Value> = serde_json::from_str(&output).unwrap();
338        assert_eq!(parsed.len(), 2);
339        assert_eq!(parsed[0]["name"], "Alice");
340        assert_eq!(parsed[0]["age"], 30);
341    }
342
343    #[test]
344    fn test_format_csv() {
345        let result = sample_result();
346        let output = QueryResultFormatter::format(&result, OutputFormat::Csv);
347        assert!(output.starts_with("id,name,age\n"));
348        assert!(output.contains("1,Alice,30"));
349    }
350
351    #[test]
352    fn test_csv_escape() {
353        assert_eq!(QueryResultFormatter::csv_escape("hello"), "hello");
354        assert_eq!(
355            QueryResultFormatter::csv_escape("hello,world"),
356            "\"hello,world\""
357        );
358        assert_eq!(
359            QueryResultFormatter::csv_escape("say \"hi\""),
360            "\"say \"\"hi\"\"\""
361        );
362    }
363
364    #[test]
365    fn test_format_tsv() {
366        let result = sample_result();
367        let output = QueryResultFormatter::format(&result, OutputFormat::Tsv);
368        assert!(output.starts_with("id\tname\tage\n"));
369        assert!(output.contains("1\tAlice\t30"));
370    }
371
372    #[test]
373    #[allow(clippy::approx_constant)]
374    fn test_json_value_conversion() {
375        assert_eq!(
376            QueryResultFormatter::json_value("NULL"),
377            serde_json::Value::Null
378        );
379        assert_eq!(
380            QueryResultFormatter::json_value("42"),
381            serde_json::json!(42)
382        );
383        assert_eq!(
384            QueryResultFormatter::json_value("3.14"),
385            serde_json::json!(3.14)
386        );
387        assert_eq!(
388            QueryResultFormatter::json_value("true"),
389            serde_json::json!(true)
390        );
391        assert_eq!(
392            QueryResultFormatter::json_value("hello"),
393            serde_json::json!("hello")
394        );
395    }
396}