Skip to main content

parquet_cli/
rows.rs

1//! Reading rows: the first few, all of them, or a conversion to another form.
2
3use std::fs::File;
4use std::path::Path;
5
6use anyhow::{Context, Result};
7use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
8use parquet::arrow::arrow_writer::ArrowWriter;
9use parquet::basic::{Compression, ZstdLevel};
10use parquet::file::properties::WriterProperties;
11
12use crate::output::Table;
13use crate::value::cell;
14
15/// The first `rows` rows of a file.
16pub fn head(path: &Path, rows: usize) -> Result<Table> {
17    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
18    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
19        .with_context(|| format!("read the footer of {}", path.display()))?;
20    let columns: Vec<String> = builder
21        .schema()
22        .fields()
23        .iter()
24        .map(|field| field.name().clone())
25        .collect();
26    let reader = builder.with_batch_size(rows.max(1)).build()?;
27
28    let mut table = Table::new(columns);
29    for batch in reader {
30        let batch = batch?;
31        for row in 0..batch.num_rows() {
32            if table.rows.len() >= rows {
33                return Ok(table);
34            }
35            table.push(
36                batch
37                    .columns()
38                    .iter()
39                    .map(|column| cell(column, row))
40                    .collect(),
41            );
42        }
43    }
44    Ok(table)
45}
46
47/// All the rows of one or more files, in order.
48pub fn cat(paths: &[std::path::PathBuf]) -> Result<Table> {
49    let mut table = Table::default();
50    for path in paths {
51        let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
52        let builder = ParquetRecordBatchReaderBuilder::try_new(file)
53            .with_context(|| format!("read the footer of {}", path.display()))?;
54        let names: Vec<String> = builder
55            .schema()
56            .fields()
57            .iter()
58            .map(|field| field.name().clone())
59            .collect();
60        if table.columns.is_empty() {
61            table.columns = names;
62        }
63        for batch in builder.build()? {
64            let batch = batch?;
65            for row in 0..batch.num_rows() {
66                table.push(
67                    batch
68                        .columns()
69                        .iter()
70                        .map(|column| cell(column, row))
71                        .collect(),
72                );
73            }
74        }
75    }
76    Ok(table)
77}
78
79/// What `parquet to` writes.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
81pub enum ConvertFormat {
82    /// Comma separated values.
83    Csv,
84    /// A JSON array of row objects.
85    Json,
86    /// One JSON object per line.
87    Jsonl,
88    /// A new Parquet file, ZSTD compressed.
89    Parquet,
90}
91
92impl std::fmt::Display for ConvertFormat {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        let name = match self {
95            ConvertFormat::Csv => "csv",
96            ConvertFormat::Json => "json",
97            ConvertFormat::Jsonl => "jsonl",
98            ConvertFormat::Parquet => "parquet",
99        };
100        f.write_str(name)
101    }
102}
103
104/// Write a file out as CSV, JSON, JSON lines, or a new Parquet file.
105pub fn convert(path: &Path, out: &Path, format: ConvertFormat) -> Result<()> {
106    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
107    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
108        .with_context(|| format!("read the footer of {}", path.display()))?;
109
110    match format {
111        ConvertFormat::Parquet => {
112            let properties = WriterProperties::builder()
113                .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?))
114                .build();
115            let mut writer = ArrowWriter::try_new(
116                File::create(out).with_context(|| format!("create {}", out.display()))?,
117                builder.schema().clone(),
118                Some(properties),
119            )?;
120            for batch in builder.build()? {
121                writer.write(&batch?)?;
122            }
123            writer.close()?;
124        }
125        ConvertFormat::Csv | ConvertFormat::Json | ConvertFormat::Jsonl => {
126            let table = cat(&[path.to_path_buf()])?;
127            let mut handle =
128                File::create(out).with_context(|| format!("create {}", out.display()))?;
129            let format = match format {
130                ConvertFormat::Csv => crate::output::Format::Csv,
131                ConvertFormat::Json => crate::output::Format::Json,
132                _ => crate::output::Format::Jsonl,
133            };
134            crate::output::write_table(&mut handle, &table, format)?;
135        }
136    }
137    Ok(())
138}