Skip to main content

datafusion_cli/
print_format.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Print format variants
6
7use std::str::FromStr;
8
9use crate::print_options::MaxRows;
10
11use arrow::csv::writer::WriterBuilder;
12use arrow::datatypes::SchemaRef;
13use arrow::json::{ArrayWriter, LineDelimitedWriter};
14use arrow::record_batch::RecordBatch;
15use arrow::util::pretty::pretty_format_batches_with_options;
16use datafusion::config::FormatOptions;
17use datafusion::error::Result;
18
19/// Allow records to be printed in different formats
20#[derive(Debug, PartialEq, Eq, clap::ValueEnum, Clone, Copy)]
21pub enum PrintFormat {
22    Csv,
23    Tsv,
24    Table,
25    Json,
26    NdJson,
27    Automatic,
28}
29
30impl FromStr for PrintFormat {
31    type Err = String;
32
33    fn from_str(s: &str) -> Result<Self, Self::Err> {
34        clap::ValueEnum::from_str(s, true)
35    }
36}
37
38macro_rules! batches_to_json {
39    ($WRITER: ident, $writer: expr, $batches: expr) => {{
40        {
41            if !$batches.is_empty() {
42                let mut json_writer = $WRITER::new(&mut *$writer);
43                for batch in $batches {
44                    json_writer.write(batch)?;
45                }
46                json_writer.finish()?;
47                json_finish!($WRITER, $writer);
48            }
49        }
50        Ok(()) as Result<()>
51    }};
52}
53
54macro_rules! json_finish {
55    (ArrayWriter, $writer: expr) => {{
56        writeln!($writer)?;
57    }};
58    (LineDelimitedWriter, $writer: expr) => {{}};
59}
60
61fn print_batches_with_sep<W: std::io::Write>(
62    writer: &mut W,
63    batches: &[RecordBatch],
64    delimiter: u8,
65    with_header: bool,
66) -> Result<()> {
67    let builder = WriterBuilder::new()
68        .with_header(with_header)
69        .with_delimiter(delimiter);
70    let mut csv_writer = builder.build(writer);
71
72    for batch in batches {
73        csv_writer.write(batch)?;
74    }
75
76    Ok(())
77}
78
79fn keep_only_maxrows(s: &str, maxrows: usize) -> String {
80    let lines: Vec<String> = s.lines().map(String::from).collect();
81
82    assert!(lines.len() >= maxrows + 4); // 4 lines for top and bottom border
83
84    let last_line = &lines[lines.len() - 1]; // bottom border line
85
86    let spaces = last_line.len().saturating_sub(4);
87    let dotted_line = format!("| .{}|", " ".repeat(spaces));
88
89    let mut result = lines[0..(maxrows + 3)].to_vec(); // Keep top border and `maxrows` lines
90    result.extend(vec![dotted_line; 3]); // Append ... lines
91    result.push(last_line.clone());
92
93    result.join("\n")
94}
95
96fn format_batches_with_maxrows<W: std::io::Write>(
97    writer: &mut W,
98    batches: &[RecordBatch],
99    maxrows: MaxRows,
100    format_options: &FormatOptions,
101) -> Result<()> {
102    let options: arrow::util::display::FormatOptions = format_options.try_into()?;
103
104    match maxrows {
105        MaxRows::Limited(maxrows) => {
106            // Filter batches to meet the maxrows condition
107            let mut filtered_batches = Vec::new();
108            let mut row_count: usize = 0;
109            let mut over_limit = false;
110            for batch in batches {
111                if row_count + batch.num_rows() > maxrows {
112                    // If adding this batch exceeds maxrows, slice the batch
113                    let limit = maxrows - row_count;
114                    let sliced_batch = batch.slice(0, limit);
115                    filtered_batches.push(sliced_batch);
116                    over_limit = true;
117                    break;
118                } else {
119                    filtered_batches.push(batch.clone());
120                    row_count += batch.num_rows();
121                }
122            }
123
124            let formatted =
125                pretty_format_batches_with_options(&filtered_batches, &options)?;
126            if over_limit {
127                let mut formatted_str = format!("{formatted}");
128                formatted_str = keep_only_maxrows(&formatted_str, maxrows);
129                writeln!(writer, "{formatted_str}")?;
130            } else {
131                writeln!(writer, "{formatted}")?;
132            }
133        }
134        MaxRows::Unlimited => {
135            let formatted = pretty_format_batches_with_options(batches, &options)?;
136            writeln!(writer, "{formatted}")?;
137        }
138    }
139
140    Ok(())
141}
142
143impl PrintFormat {
144    /// Print the batches to a writer using the specified format
145    pub fn print_batches<W: std::io::Write>(
146        &self,
147        writer: &mut W,
148        schema: SchemaRef,
149        batches: &[RecordBatch],
150        maxrows: MaxRows,
151        with_header: bool,
152        format_options: &FormatOptions,
153    ) -> Result<()> {
154        // filter out any empty batches
155        let batches: Vec<_> = batches
156            .iter()
157            .filter(|b| b.num_rows() > 0)
158            .cloned()
159            .collect();
160        if batches.is_empty() {
161            return self.print_empty(writer, schema, format_options);
162        }
163
164        match self {
165            Self::Csv | Self::Automatic => {
166                print_batches_with_sep(writer, &batches, b',', with_header)
167            }
168            Self::Tsv => print_batches_with_sep(writer, &batches, b'\t', with_header),
169            Self::Table => {
170                if maxrows == MaxRows::Limited(0) {
171                    return Ok(());
172                }
173                format_batches_with_maxrows(writer, &batches, maxrows, format_options)
174            }
175            Self::Json => batches_to_json!(ArrayWriter, writer, &batches),
176            Self::NdJson => batches_to_json!(LineDelimitedWriter, writer, &batches),
177        }
178    }
179
180    /// Print when the result batches contain no rows
181    fn print_empty<W: std::io::Write>(
182        &self,
183        writer: &mut W,
184        schema: SchemaRef,
185        format_options: &FormatOptions,
186    ) -> Result<()> {
187        match self {
188            // Print column headers for Table format
189            Self::Table if !schema.fields().is_empty() => {
190                let format_options: arrow::util::display::FormatOptions =
191                    format_options.try_into()?;
192
193                let empty_batch = RecordBatch::new_empty(schema);
194                let formatted =
195                    pretty_format_batches_with_options(&[empty_batch], &format_options)?;
196                writeln!(writer, "{formatted}")?;
197            }
198            _ => {}
199        }
200        Ok(())
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use std::sync::Arc;
208
209    use arrow::array::{Int32Array, Time64NanosecondArray};
210    use arrow::datatypes::{DataType, Field, Schema, TimeUnit};
211    use insta::{allow_duplicates, assert_snapshot};
212
213    #[test]
214    fn print_empty() {
215        for format in [
216            PrintFormat::Csv,
217            PrintFormat::Tsv,
218            PrintFormat::Json,
219            PrintFormat::NdJson,
220            PrintFormat::Automatic,
221        ] {
222            // no output for empty batches, even with header set
223            let output = PrintBatchesTest::new()
224                .with_format(format)
225                .with_schema(three_column_schema())
226                .with_batches(vec![])
227                .run();
228            assert_eq!(output, "")
229        }
230
231        // output column headers for empty batches when format is Table
232        let output = PrintBatchesTest::new()
233            .with_format(PrintFormat::Table)
234            .with_schema(three_column_schema())
235            .with_batches(vec![])
236            .run();
237        assert_snapshot!(output, @r"
238        +---+---+---+
239        | a | b | c |
240        +---+---+---+
241        +---+---+---+
242        ");
243    }
244
245    #[test]
246    fn print_csv_no_header() {
247        let output = PrintBatchesTest::new()
248            .with_format(PrintFormat::Csv)
249            .with_batches(split_batch(&three_column_batch()))
250            .with_header(WithHeader::No)
251            .run();
252        assert_snapshot!(output, @r"
253        1,4,7
254        2,5,8
255        3,6,9
256        ");
257    }
258
259    #[test]
260    fn print_csv_with_header() {
261        let output = PrintBatchesTest::new()
262            .with_format(PrintFormat::Csv)
263            .with_batches(split_batch(&three_column_batch()))
264            .with_header(WithHeader::Yes)
265            .run();
266        assert_snapshot!(output, @r"
267        a,b,c
268        1,4,7
269        2,5,8
270        3,6,9
271        ");
272    }
273
274    #[test]
275    fn print_tsv_no_header() {
276        let output = PrintBatchesTest::new()
277            .with_format(PrintFormat::Tsv)
278            .with_batches(split_batch(&three_column_batch()))
279            .with_header(WithHeader::No)
280            .run();
281        assert_snapshot!(output, @r"
282        1	4	7
283        2	5	8
284        3	6	9
285        ")
286    }
287
288    #[test]
289    fn print_tsv_with_header() {
290        let output = PrintBatchesTest::new()
291            .with_format(PrintFormat::Tsv)
292            .with_batches(split_batch(&three_column_batch()))
293            .with_header(WithHeader::Yes)
294            .run();
295        assert_snapshot!(output, @r"
296        a	b	c
297        1	4	7
298        2	5	8
299        3	6	9
300        ");
301    }
302
303    #[test]
304    fn print_table() {
305        let output = PrintBatchesTest::new()
306            .with_format(PrintFormat::Table)
307            .with_batches(split_batch(&three_column_batch()))
308            .with_header(WithHeader::Ignored)
309            .run();
310        assert_snapshot!(output, @r"
311        +---+---+---+
312        | a | b | c |
313        +---+---+---+
314        | 1 | 4 | 7 |
315        | 2 | 5 | 8 |
316        | 3 | 6 | 9 |
317        +---+---+---+
318        ");
319    }
320    #[test]
321    fn print_json() {
322        let output = PrintBatchesTest::new()
323            .with_format(PrintFormat::Json)
324            .with_batches(split_batch(&three_column_batch()))
325            .with_header(WithHeader::Ignored)
326            .run();
327        assert_snapshot!(output, @r#"[{"a":1,"b":4,"c":7},{"a":2,"b":5,"c":8},{"a":3,"b":6,"c":9}]"#);
328    }
329
330    #[test]
331    fn print_ndjson() {
332        let output = PrintBatchesTest::new()
333            .with_format(PrintFormat::NdJson)
334            .with_batches(split_batch(&three_column_batch()))
335            .with_header(WithHeader::Ignored)
336            .run();
337        assert_snapshot!(output, @r#"
338        {"a":1,"b":4,"c":7}
339        {"a":2,"b":5,"c":8}
340        {"a":3,"b":6,"c":9}
341        "#);
342    }
343
344    #[test]
345    fn print_automatic_no_header() {
346        let output = PrintBatchesTest::new()
347            .with_format(PrintFormat::Automatic)
348            .with_batches(split_batch(&three_column_batch()))
349            .with_header(WithHeader::No)
350            .run();
351        assert_snapshot!(output, @r"
352        1,4,7
353        2,5,8
354        3,6,9
355        ");
356    }
357    #[test]
358    fn print_automatic_with_header() {
359        let output = PrintBatchesTest::new()
360            .with_format(PrintFormat::Automatic)
361            .with_batches(split_batch(&three_column_batch()))
362            .with_header(WithHeader::Yes)
363            .run();
364        assert_snapshot!(output, @r"
365        a,b,c
366        1,4,7
367        2,5,8
368        3,6,9
369        ");
370    }
371
372    #[test]
373    fn print_maxrows_unlimited() {
374        // should print out entire output with no truncation if unlimited or
375        // limit greater than number of batches or equal to the number of batches
376        for max_rows in [MaxRows::Unlimited, MaxRows::Limited(5), MaxRows::Limited(3)] {
377            let output = PrintBatchesTest::new()
378                .with_format(PrintFormat::Table)
379                .with_schema(one_column_schema())
380                .with_batches(vec![one_column_batch()])
381                .with_maxrows(max_rows)
382                .run();
383            allow_duplicates! {
384                assert_snapshot!(output, @r"
385                +---+
386                | a |
387                +---+
388                | 1 |
389                | 2 |
390                | 3 |
391                +---+
392                ");
393            }
394        }
395    }
396
397    #[test]
398    fn print_maxrows_limited_one_batch() {
399        let output = PrintBatchesTest::new()
400            .with_format(PrintFormat::Table)
401            .with_batches(vec![one_column_batch()])
402            .with_maxrows(MaxRows::Limited(1))
403            .run();
404        assert_snapshot!(output, @r"
405        +---+
406        | a |
407        +---+
408        | 1 |
409        | . |
410        | . |
411        | . |
412        +---+
413        ");
414    }
415
416    #[test]
417    fn print_maxrows_limited_multi_batched() {
418        let output = PrintBatchesTest::new()
419            .with_format(PrintFormat::Table)
420            .with_batches(vec![
421                one_column_batch(),
422                one_column_batch(),
423                one_column_batch(),
424            ])
425            .with_maxrows(MaxRows::Limited(5))
426            .run();
427        assert_snapshot!(output, @r"
428        +---+
429        | a |
430        +---+
431        | 1 |
432        | 2 |
433        | 3 |
434        | 1 |
435        | 2 |
436        | . |
437        | . |
438        | . |
439        +---+
440        ");
441    }
442
443    #[test]
444    fn test_print_batches_empty_batches() {
445        let batch = one_column_batch();
446        let empty_batch = RecordBatch::new_empty(batch.schema());
447
448        let output = PrintBatchesTest::new()
449            .with_format(PrintFormat::Table)
450            .with_batches(vec![empty_batch.clone(), batch, empty_batch])
451            .run();
452        assert_snapshot!(output, @r"
453        +---+
454        | a |
455        +---+
456        | 1 |
457        | 2 |
458        | 3 |
459        +---+
460        ");
461    }
462
463    #[test]
464    fn test_print_batches_empty_batch() {
465        let empty_batch = RecordBatch::new_empty(one_column_batch().schema());
466
467        // Print column headers for empty batch when format is Table
468        let output = PrintBatchesTest::new()
469            .with_format(PrintFormat::Table)
470            .with_schema(one_column_schema())
471            .with_batches(vec![empty_batch])
472            .with_header(WithHeader::Yes)
473            .run();
474        assert_snapshot!(output, @r"
475        +---+
476        | a |
477        +---+
478        +---+
479        ");
480
481        // No output for empty batch when schema contains no columns
482        let empty_batch = RecordBatch::new_empty(Arc::new(Schema::empty()));
483        let output = PrintBatchesTest::new()
484            .with_format(PrintFormat::Table)
485            .with_schema(Arc::new(Schema::empty()))
486            .with_batches(vec![empty_batch])
487            .with_header(WithHeader::Yes)
488            .run();
489        assert_eq!(output, "")
490    }
491
492    #[test]
493    fn invalid_temporal_format_errors_before_table_output() {
494        let schema = Arc::new(Schema::new(vec![Field::new(
495            "time",
496            DataType::Time64(TimeUnit::Nanosecond),
497            false,
498        )]));
499        let batch = RecordBatch::try_new(
500            schema.clone(),
501            vec![Arc::new(Time64NanosecondArray::from(vec![1_000, 2_000]))],
502        )
503        .unwrap();
504        let empty_batch = RecordBatch::new_empty(schema.clone());
505        let format_options = FormatOptions {
506            time_format: Some("%Y".to_owned()),
507            ..Default::default()
508        };
509
510        for batches in [vec![batch], vec![empty_batch]] {
511            let mut output = Vec::new();
512            let error = PrintFormat::Table
513                .print_batches(
514                    &mut output,
515                    schema.clone(),
516                    &batches,
517                    MaxRows::Limited(1),
518                    true,
519                    &format_options,
520                )
521                .expect_err("incompatible time formats must fail before writing output");
522
523            assert!(
524                error.to_string().contains("datafusion.format.time_format"),
525                "unexpected error: {error}"
526            );
527            assert!(
528                output.is_empty(),
529                "format errors must not write partial output"
530            );
531        }
532    }
533
534    #[derive(Debug)]
535    struct PrintBatchesTest {
536        format: PrintFormat,
537        schema: SchemaRef,
538        batches: Vec<RecordBatch>,
539        maxrows: MaxRows,
540        with_header: WithHeader,
541    }
542
543    /// How to test with_header
544    #[derive(Debug, Clone)]
545    enum WithHeader {
546        Yes,
547        No,
548        /// output should be the same with or without header
549        Ignored,
550    }
551
552    impl PrintBatchesTest {
553        fn new() -> Self {
554            Self {
555                format: PrintFormat::Table,
556                schema: Arc::new(Schema::empty()),
557                batches: vec![],
558                maxrows: MaxRows::Unlimited,
559                with_header: WithHeader::Ignored,
560            }
561        }
562
563        /// set the format
564        fn with_format(mut self, format: PrintFormat) -> Self {
565            self.format = format;
566            self
567        }
568
569        // set the schema
570        fn with_schema(mut self, schema: SchemaRef) -> Self {
571            self.schema = schema;
572            self
573        }
574
575        /// set the batches to convert
576        fn with_batches(mut self, batches: Vec<RecordBatch>) -> Self {
577            self.batches = batches;
578            self
579        }
580
581        /// set maxrows
582        fn with_maxrows(mut self, maxrows: MaxRows) -> Self {
583            self.maxrows = maxrows;
584            self
585        }
586
587        /// set with_header
588        fn with_header(mut self, with_header: WithHeader) -> Self {
589            self.with_header = with_header;
590            self
591        }
592
593        /// run the test
594        /// formats batches using parameters and returns the resulting output
595        fn run(self) -> String {
596            match self.with_header {
597                WithHeader::Yes => self.output_with_header(true),
598                WithHeader::No => self.output_with_header(false),
599                WithHeader::Ignored => {
600                    let output = self.output_with_header(true);
601                    // ensure the output is the same without header
602                    let output_without_header = self.output_with_header(false);
603                    assert_eq!(
604                        output, output_without_header,
605                        "Expected output to be the same with or without header"
606                    );
607                    output
608                }
609            }
610        }
611
612        fn output_with_header(&self, with_header: bool) -> String {
613            let mut buffer: Vec<u8> = vec![];
614            self.format
615                .print_batches(
616                    &mut buffer,
617                    self.schema.clone(),
618                    &self.batches,
619                    self.maxrows,
620                    with_header,
621                    &FormatOptions::default(),
622                )
623                .unwrap();
624            String::from_utf8(buffer).unwrap()
625        }
626    }
627
628    /// Return a schema with three columns
629    fn three_column_schema() -> SchemaRef {
630        Arc::new(Schema::new(vec![
631            Field::new("a", DataType::Int32, false),
632            Field::new("b", DataType::Int32, false),
633            Field::new("c", DataType::Int32, false),
634        ]))
635    }
636
637    /// Return a batch with three columns and three rows
638    fn three_column_batch() -> RecordBatch {
639        RecordBatch::try_new(
640            three_column_schema(),
641            vec![
642                Arc::new(Int32Array::from(vec![1, 2, 3])),
643                Arc::new(Int32Array::from(vec![4, 5, 6])),
644                Arc::new(Int32Array::from(vec![7, 8, 9])),
645            ],
646        )
647        .unwrap()
648    }
649
650    /// Return a schema with one column
651    fn one_column_schema() -> SchemaRef {
652        Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]))
653    }
654
655    /// return a batch with one column and three rows
656    fn one_column_batch() -> RecordBatch {
657        RecordBatch::try_new(
658            one_column_schema(),
659            vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
660        )
661        .unwrap()
662    }
663
664    #[test]
665    fn print_maxrows_limited_wide_table() {
666        let output = PrintBatchesTest::new()
667            .with_format(PrintFormat::Table)
668            .with_batches(vec![wide_column_batch()])
669            .with_maxrows(MaxRows::Limited(1))
670            .run();
671        assert_snapshot!(output, @r"
672        +----+----+----+----+----+----+----+----+----+----+
673        | c0 | c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8 | c9 |
674        +----+----+----+----+----+----+----+----+----+----+
675        | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0  |
676        | .                                               |
677        | .                                               |
678        | .                                               |
679        +----+----+----+----+----+----+----+----+----+----+
680        ");
681    }
682
683    /// return a schema with many columns (to exercise wide table formatting)
684    fn wide_column_schema() -> SchemaRef {
685        let fields: Vec<Field> = (0..10)
686            .map(|i| Field::new(format!("c{i}"), DataType::Int32, false))
687            .collect();
688        Arc::new(Schema::new(fields))
689    }
690
691    /// return a batch with many columns and three rows
692    fn wide_column_batch() -> RecordBatch {
693        let arrays: Vec<Arc<dyn arrow::array::Array>> = (0..10)
694            .map(|_| Arc::new(Int32Array::from(vec![0, 1, 2])) as _)
695            .collect();
696        RecordBatch::try_new(wide_column_schema(), arrays).unwrap()
697    }
698
699    /// Slice the record batch into 2 batches
700    fn split_batch(batch: &RecordBatch) -> Vec<RecordBatch> {
701        assert!(batch.num_rows() > 1);
702        let split = batch.num_rows() / 2;
703        vec![
704            batch.slice(0, split),
705            batch.slice(split, batch.num_rows() - split),
706        ]
707    }
708}