parquet-cli 0.1.7

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
}