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}
217
218/// A reader that hands out batches of rows.
219pub struct BatchReader {
220    reader: parquet::arrow::arrow_reader::ParquetRecordBatchReader,
221}
222
223impl BatchReader {
224    /// The next batch of rows, or none when the file ends.
225    pub fn next_batch(&mut self) -> Option<arrow_array::RecordBatch> {
226        self.reader.next().and_then(|batch| batch.ok())
227    }
228}
229
230/// Open a file to read batches of rows from.
231pub fn reader(path: &Path, batch_size: usize) -> Result<BatchReader> {
232    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
233    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
234        .with_context(|| format!("read the footer of {}", path.display()))?;
235    let reader = builder
236        .with_batch_size(batch_size.max(1))
237        .build()
238        .context("open the reader")?;
239    Ok(BatchReader { reader })
240}
241
242/// Build a batch of rows out of records (a list of objects).
243pub fn batch_from_json(records: &serde_json::Value) -> Result<arrow_array::RecordBatch> {
244    let list = records
245        .as_array()
246        .ok_or_else(|| anyhow::anyhow!("the rows are a list of records"))?;
247
248    // The columns, in the order they first show up.
249    let mut names: Vec<String> = Vec::new();
250    for record in list {
251        if let Some(object) = record.as_object() {
252            for name in object.keys() {
253                if !names.contains(name) {
254                    names.push(name.clone());
255                }
256            }
257        }
258    }
259    if names.is_empty() {
260        return Err(anyhow::anyhow!("there are no rows to write"));
261    }
262
263    let mut fields: Vec<arrow_schema::FieldRef> = Vec::new();
264    let mut arrays: Vec<ArrayRef> = Vec::new();
265    for name in &names {
266        let values: Vec<serde_json::Value> = list
267            .iter()
268            .map(|record| record.get(name).cloned().unwrap_or(serde_json::Value::Null))
269            .collect();
270        let (data_type, array) = array_of(&values, name)?;
271        fields.push(Arc::new(arrow_schema::Field::new(name, data_type, true)));
272        arrays.push(array);
273    }
274
275    let schema = Arc::new(arrow_schema::Schema::new(fields));
276    arrow_array::RecordBatch::try_new(schema, arrays).context("build the batch")
277}
278
279/// The values of one column, as an Arrow array.
280fn array_of(
281    values: &[serde_json::Value],
282    name: &str,
283) -> Result<(arrow_schema::DataType, ArrayRef)> {
284    use arrow_array::{BooleanArray, Float64Array, Int64Array};
285
286    let all_null = values.iter().all(|value| value.is_null());
287    let all_bool = values
288        .iter()
289        .all(|value| value.is_boolean() || value.is_null());
290    let all_int = values
291        .iter()
292        .all(|value| value.is_i64() || value.is_u64() || value.is_null());
293    let all_number = values
294        .iter()
295        .all(|value| value.is_number() || value.is_null());
296    let all_string = values
297        .iter()
298        .all(|value| value.is_string() || value.is_null());
299
300    if all_null {
301        return Ok((
302            arrow_schema::DataType::Null,
303            Arc::new(arrow_array::NullArray::new(values.len())),
304        ));
305    }
306    if all_bool {
307        let array: BooleanArray = values.iter().map(|value| value.as_bool()).collect();
308        return Ok((arrow_schema::DataType::Boolean, Arc::new(array)));
309    }
310    if all_int {
311        let array: Int64Array = values
312            .iter()
313            .map(|value| value.as_i64().or_else(|| value.as_u64().map(|v| v as i64)))
314            .collect();
315        return Ok((arrow_schema::DataType::Int64, Arc::new(array)));
316    }
317    if all_number {
318        let array: Float64Array = values.iter().map(|value| value.as_f64()).collect();
319        return Ok((arrow_schema::DataType::Float64, Arc::new(array)));
320    }
321    if all_string {
322        let array: arrow_array::StringArray = values
323            .iter()
324            .map(|value| value.as_str().map(|text| text.to_string()))
325            .collect();
326        return Ok((arrow_schema::DataType::Utf8, Arc::new(array)));
327    }
328    Err(anyhow::anyhow!(
329        "the column {name} has values of more than one kind"
330    ))
331}
332
333/// Write a batch of rows out as a Parquet file.
334pub fn write_batch(
335    path: &Path,
336    batch: arrow_array::RecordBatch,
337    plan: &crate::plan::Plan,
338) -> Result<u64> {
339    // The plan may want to know how many different values each column has
340    // (that is how it decides whether a dictionary pays).
341    let distinct = crate::plan::distinct_of_batch(&batch);
342    let columns: Vec<crate::plan::Column> = batch
343        .schema()
344        .fields()
345        .iter()
346        .enumerate()
347        .map(|(index, field)| crate::plan::Column {
348            name: field.name().clone(),
349            distinct: distinct.get(index).map(|count| *count as u64),
350            rows: batch.num_rows() as i64,
351        })
352        .collect();
353    let properties = plan.writer_properties(&columns)?;
354    let output = File::create(path).with_context(|| format!("create {}", path.display()))?;
355    let mut writer = ArrowWriter::try_new(output, batch.schema(), Some(properties))
356        .context("open the writer")?;
357    writer.write(&batch)?;
358    writer.close()?;
359    Ok(std::fs::metadata(path)?.len())
360}