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;
5use std::sync::Arc;
6
7use anyhow::{Context, Result};
8use arrow_array::{ArrayRef, RecordBatch};
9use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
10use parquet::arrow::arrow_writer::ArrowWriter;
11use parquet::basic::{Compression, ZstdLevel};
12use parquet::file::properties::WriterProperties;
13
14use crate::output::Table;
15use crate::value::cell;
16
17/// The first `rows` rows of a file.
18pub fn head(path: &Path, rows: usize) -> Result<Table> {
19    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
20    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
21        .with_context(|| format!("read the footer of {}", path.display()))?;
22    let columns: Vec<String> = builder
23        .schema()
24        .fields()
25        .iter()
26        .map(|field| field.name().clone())
27        .collect();
28    let reader = builder.with_batch_size(rows.max(1)).build()?;
29
30    let mut table = Table::new(columns);
31    for batch in reader {
32        let batch = batch?;
33        for row in 0..batch.num_rows() {
34            if table.rows.len() >= rows {
35                return Ok(table);
36            }
37            table.push(
38                batch
39                    .columns()
40                    .iter()
41                    .map(|column| cell(column, row))
42                    .collect(),
43            );
44        }
45    }
46    Ok(table)
47}
48
49/// All the rows of one or more files, in order.
50pub fn cat(paths: &[std::path::PathBuf]) -> Result<Table> {
51    let mut table = Table::default();
52    for path in paths {
53        let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
54        let builder = ParquetRecordBatchReaderBuilder::try_new(file)
55            .with_context(|| format!("read the footer of {}", path.display()))?;
56        let names: Vec<String> = builder
57            .schema()
58            .fields()
59            .iter()
60            .map(|field| field.name().clone())
61            .collect();
62        if table.columns.is_empty() {
63            table.columns = names;
64        }
65        for batch in builder.build()? {
66            let batch = batch?;
67            for row in 0..batch.num_rows() {
68                table.push(
69                    batch
70                        .columns()
71                        .iter()
72                        .map(|column| cell(column, row))
73                        .collect(),
74                );
75            }
76        }
77    }
78    Ok(table)
79}
80
81/// What `parquet to` writes.
82#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
83pub enum ConvertFormat {
84    /// Comma separated values.
85    Csv,
86    /// A JSON array of row objects.
87    Json,
88    /// One JSON object per line.
89    Jsonl,
90    /// A new Parquet file, ZSTD compressed.
91    Parquet,
92}
93
94impl std::fmt::Display for ConvertFormat {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        let name = match self {
97            ConvertFormat::Csv => "csv",
98            ConvertFormat::Json => "json",
99            ConvertFormat::Jsonl => "jsonl",
100            ConvertFormat::Parquet => "parquet",
101        };
102        f.write_str(name)
103    }
104}
105
106/// Write a file out as CSV, JSON, JSON lines, or a new Parquet file.
107pub fn convert(
108    path: &Path,
109    out: &Path,
110    format: ConvertFormat,
111    columns: Option<&[String]>,
112) -> Result<()> {
113    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
114    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
115        .with_context(|| format!("read the footer of {}", path.display()))?;
116
117    match format {
118        ConvertFormat::Parquet => {
119            let properties = WriterProperties::builder()
120                .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?))
121                .build();
122            let schema = builder.schema().clone();
123            let wanted = wanted_columns(&schema, columns)?;
124
125            // The new file has only the columns that were asked for.
126            let write_schema = match &wanted {
127                Some(wanted) => {
128                    let fields: Vec<arrow_schema::FieldRef> = wanted
129                        .iter()
130                        .map(|index| schema.fields()[*index].clone())
131                        .collect();
132                    Arc::new(arrow_schema::Schema::new(fields))
133                }
134                None => schema.clone(),
135            };
136
137            let mut writer = ArrowWriter::try_new(
138                File::create(out).with_context(|| format!("create {}", out.display()))?,
139                write_schema.clone(),
140                Some(properties),
141            )?;
142            for batch in builder.build()? {
143                let batch = batch?;
144                let batch = match &wanted {
145                    Some(wanted) => {
146                        let kept: Vec<ArrayRef> = wanted
147                            .iter()
148                            .map(|index| batch.column(*index).clone())
149                            .collect();
150                        RecordBatch::try_new(write_schema.clone(), kept)?
151                    }
152                    None => batch,
153                };
154                writer.write(&batch)?;
155            }
156            writer.close()?;
157        }
158        ConvertFormat::Csv | ConvertFormat::Json | ConvertFormat::Jsonl => {
159            let table = cat(&[path.to_path_buf()])?;
160            let table = match columns {
161                Some(names) => keep_columns(&table, names),
162                None => table,
163            };
164            let mut handle =
165                File::create(out).with_context(|| format!("create {}", out.display()))?;
166            let format = match format {
167                ConvertFormat::Csv => crate::output::Format::Csv,
168                ConvertFormat::Json => crate::output::Format::Json,
169                _ => crate::output::Format::Jsonl,
170            };
171            crate::output::write_table(&mut handle, &table, format)?;
172        }
173    }
174    Ok(())
175}
176
177/// The columns to keep, and where they are.
178fn wanted_columns(
179    schema: &std::sync::Arc<arrow_schema::Schema>,
180    columns: Option<&[String]>,
181) -> Result<Option<Vec<usize>>> {
182    let names = match columns {
183        Some(names) => names,
184        None => return Ok(None),
185    };
186    let mut wanted = Vec::new();
187    for name in names {
188        let index = schema
189            .fields()
190            .iter()
191            .position(|field| field.name() == name)
192            .with_context(|| format!("the file has no column named {name}"))?;
193        wanted.push(index);
194    }
195    Ok(Some(wanted))
196}
197
198/// A table with only the named columns.
199fn keep_columns(table: &Table, names: &[String]) -> Table {
200    let keep: Vec<usize> = table
201        .columns
202        .iter()
203        .enumerate()
204        .filter(|(_, name)| names.contains(name))
205        .map(|(index, _)| index)
206        .collect();
207    let mut kept = Table::new(
208        keep.iter()
209            .map(|index| table.columns[*index].clone())
210            .collect(),
211    );
212    for row in &table.rows {
213        kept.push(keep.iter().map(|index| row[*index].clone()).collect());
214    }
215    kept
216}