parquet-cli 0.2.0

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! Reading rows: the first few, all of them, or a conversion to another form.

use std::fs::File;
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result};
use arrow_array::{ArrayRef, RecordBatch};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::arrow_writer::ArrowWriter;
use parquet::basic::{Compression, ZstdLevel};
use parquet::file::properties::WriterProperties;

use crate::output::Table;
use crate::value::cell;

/// The first `rows` rows of a file.
pub fn head(path: &Path, rows: usize) -> Result<Table> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    let columns: Vec<String> = builder
        .schema()
        .fields()
        .iter()
        .map(|field| field.name().clone())
        .collect();
    let reader = builder.with_batch_size(rows.max(1)).build()?;

    let mut table = Table::new(columns);
    for batch in reader {
        let batch = batch?;
        for row in 0..batch.num_rows() {
            if table.rows.len() >= rows {
                return Ok(table);
            }
            table.push(
                batch
                    .columns()
                    .iter()
                    .map(|column| cell(column, row))
                    .collect(),
            );
        }
    }
    Ok(table)
}

/// All the rows of one or more files, in order.
pub fn cat(paths: &[std::path::PathBuf]) -> Result<Table> {
    let mut table = Table::default();
    for path in paths {
        let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
        let builder = ParquetRecordBatchReaderBuilder::try_new(file)
            .with_context(|| format!("read the footer of {}", path.display()))?;
        let names: Vec<String> = builder
            .schema()
            .fields()
            .iter()
            .map(|field| field.name().clone())
            .collect();
        if table.columns.is_empty() {
            table.columns = names;
        }
        for batch in builder.build()? {
            let batch = batch?;
            for row in 0..batch.num_rows() {
                table.push(
                    batch
                        .columns()
                        .iter()
                        .map(|column| cell(column, row))
                        .collect(),
                );
            }
        }
    }
    Ok(table)
}

/// What `parquet to` writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ConvertFormat {
    /// Comma separated values.
    Csv,
    /// A JSON array of row objects.
    Json,
    /// One JSON object per line.
    Jsonl,
    /// A new Parquet file, ZSTD compressed.
    Parquet,
}

impl std::fmt::Display for ConvertFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            ConvertFormat::Csv => "csv",
            ConvertFormat::Json => "json",
            ConvertFormat::Jsonl => "jsonl",
            ConvertFormat::Parquet => "parquet",
        };
        f.write_str(name)
    }
}

/// Write a file out as CSV, JSON, JSON lines, or a new Parquet file.
pub fn convert(
    path: &Path,
    out: &Path,
    format: ConvertFormat,
    columns: Option<&[String]>,
) -> Result<()> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;

    match format {
        ConvertFormat::Parquet => {
            let properties = WriterProperties::builder()
                .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?))
                .build();
            let schema = builder.schema().clone();
            let wanted = wanted_columns(&schema, columns)?;

            // The new file has only the columns that were asked for.
            let write_schema = match &wanted {
                Some(wanted) => {
                    let fields: Vec<arrow_schema::FieldRef> = wanted
                        .iter()
                        .map(|index| schema.fields()[*index].clone())
                        .collect();
                    Arc::new(arrow_schema::Schema::new(fields))
                }
                None => schema.clone(),
            };

            let mut writer = ArrowWriter::try_new(
                File::create(out).with_context(|| format!("create {}", out.display()))?,
                write_schema.clone(),
                Some(properties),
            )?;
            for batch in builder.build()? {
                let batch = batch?;
                let batch = match &wanted {
                    Some(wanted) => {
                        let kept: Vec<ArrayRef> = wanted
                            .iter()
                            .map(|index| batch.column(*index).clone())
                            .collect();
                        RecordBatch::try_new(write_schema.clone(), kept)?
                    }
                    None => batch,
                };
                writer.write(&batch)?;
            }
            writer.close()?;
        }
        ConvertFormat::Csv | ConvertFormat::Json | ConvertFormat::Jsonl => {
            let table = cat(&[path.to_path_buf()])?;
            let table = match columns {
                Some(names) => keep_columns(&table, names),
                None => table,
            };
            let mut handle =
                File::create(out).with_context(|| format!("create {}", out.display()))?;
            let format = match format {
                ConvertFormat::Csv => crate::output::Format::Csv,
                ConvertFormat::Json => crate::output::Format::Json,
                _ => crate::output::Format::Jsonl,
            };
            crate::output::write_table(&mut handle, &table, format)?;
        }
    }
    Ok(())
}

/// The columns to keep, and where they are.
fn wanted_columns(
    schema: &std::sync::Arc<arrow_schema::Schema>,
    columns: Option<&[String]>,
) -> Result<Option<Vec<usize>>> {
    let names = match columns {
        Some(names) => names,
        None => return Ok(None),
    };
    let mut wanted = Vec::new();
    for name in names {
        let index = schema
            .fields()
            .iter()
            .position(|field| field.name() == name)
            .with_context(|| format!("the file has no column named {name}"))?;
        wanted.push(index);
    }
    Ok(Some(wanted))
}

/// A table with only the named columns.
fn keep_columns(table: &Table, names: &[String]) -> Table {
    let keep: Vec<usize> = table
        .columns
        .iter()
        .enumerate()
        .filter(|(_, name)| names.contains(name))
        .map(|(index, _)| index)
        .collect();
    let mut kept = Table::new(
        keep.iter()
            .map(|index| table.columns[*index].clone())
            .collect(),
    );
    for row in &table.rows {
        kept.push(keep.iter().map(|index| row[*index].clone()).collect());
    }
    kept
}

/// A reader that hands out batches of rows.
pub struct BatchReader {
    reader: parquet::arrow::arrow_reader::ParquetRecordBatchReader,
}

impl BatchReader {
    /// The next batch of rows, or none when the file ends.
    pub fn next_batch(&mut self) -> Option<arrow_array::RecordBatch> {
        self.reader.next().and_then(|batch| batch.ok())
    }
}

/// Open a file to read batches of rows from.
pub fn reader(path: &Path, batch_size: usize) -> Result<BatchReader> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
        .with_context(|| format!("read the footer of {}", path.display()))?;
    let reader = builder
        .with_batch_size(batch_size.max(1))
        .build()
        .context("open the reader")?;
    Ok(BatchReader { reader })
}

/// Build a batch of rows out of records (a list of objects).
pub fn batch_from_json(records: &serde_json::Value) -> Result<arrow_array::RecordBatch> {
    let list = records
        .as_array()
        .ok_or_else(|| anyhow::anyhow!("the rows are a list of records"))?;

    // The columns, in the order they first show up.
    let mut names: Vec<String> = Vec::new();
    for record in list {
        if let Some(object) = record.as_object() {
            for name in object.keys() {
                if !names.contains(name) {
                    names.push(name.clone());
                }
            }
        }
    }
    if names.is_empty() {
        return Err(anyhow::anyhow!("there are no rows to write"));
    }

    let mut fields: Vec<arrow_schema::FieldRef> = Vec::new();
    let mut arrays: Vec<ArrayRef> = Vec::new();
    for name in &names {
        let values: Vec<serde_json::Value> = list
            .iter()
            .map(|record| record.get(name).cloned().unwrap_or(serde_json::Value::Null))
            .collect();
        let (data_type, array) = array_of(&values, name)?;
        fields.push(Arc::new(arrow_schema::Field::new(name, data_type, true)));
        arrays.push(array);
    }

    let schema = Arc::new(arrow_schema::Schema::new(fields));
    arrow_array::RecordBatch::try_new(schema, arrays).context("build the batch")
}

/// The values of one column, as an Arrow array.
fn array_of(
    values: &[serde_json::Value],
    name: &str,
) -> Result<(arrow_schema::DataType, ArrayRef)> {
    use arrow_array::{BooleanArray, Float64Array, Int64Array};

    let all_null = values.iter().all(|value| value.is_null());
    let all_bool = values
        .iter()
        .all(|value| value.is_boolean() || value.is_null());
    let all_int = values
        .iter()
        .all(|value| value.is_i64() || value.is_u64() || value.is_null());
    let all_number = values
        .iter()
        .all(|value| value.is_number() || value.is_null());
    let all_string = values
        .iter()
        .all(|value| value.is_string() || value.is_null());

    if all_null {
        return Ok((
            arrow_schema::DataType::Null,
            Arc::new(arrow_array::NullArray::new(values.len())),
        ));
    }
    if all_bool {
        let array: BooleanArray = values.iter().map(|value| value.as_bool()).collect();
        return Ok((arrow_schema::DataType::Boolean, Arc::new(array)));
    }
    if all_int {
        let array: Int64Array = values
            .iter()
            .map(|value| value.as_i64().or_else(|| value.as_u64().map(|v| v as i64)))
            .collect();
        return Ok((arrow_schema::DataType::Int64, Arc::new(array)));
    }
    if all_number {
        let array: Float64Array = values.iter().map(|value| value.as_f64()).collect();
        return Ok((arrow_schema::DataType::Float64, Arc::new(array)));
    }
    if all_string {
        let array: arrow_array::StringArray = values
            .iter()
            .map(|value| value.as_str().map(|text| text.to_string()))
            .collect();
        return Ok((arrow_schema::DataType::Utf8, Arc::new(array)));
    }
    Err(anyhow::anyhow!(
        "the column {name} has values of more than one kind"
    ))
}

/// Write a batch of rows out as a Parquet file.
pub fn write_batch(
    path: &Path,
    batch: arrow_array::RecordBatch,
    plan: &crate::plan::Plan,
) -> Result<u64> {
    let columns = Vec::new();
    let properties = plan.writer_properties(&columns)?;
    let output = File::create(path).with_context(|| format!("create {}", path.display()))?;
    let mut writer = ArrowWriter::try_new(output, batch.schema(), Some(properties))
        .context("open the writer")?;
    writer.write(&batch)?;
    writer.close()?;
    Ok(std::fs::metadata(path)?.len())
}