parquet-cli 0.1.0

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! Printing rows: as JSON, as CSV, or as an aligned table.

use std::io::Write;

use anyhow::Result;
use serde_json::{Map, Value};

/// How rows are printed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Format {
    /// A JSON array of row objects.
    Json,
    /// One JSON object per line.
    Jsonl,
    /// Comma separated values, with a header row.
    Csv,
    /// An aligned table.
    Table,
}

/// A result set: column names plus rows of JSON values.
#[derive(Clone, Debug, Default)]
pub struct Table {
    pub columns: Vec<String>,
    pub rows: Vec<Vec<Value>>,
}

impl Table {
    pub fn new(columns: Vec<String>) -> Self {
        Self {
            columns,
            rows: Vec::new(),
        }
    }

    pub fn push(&mut self, row: Vec<Value>) {
        self.rows.push(row);
    }

    /// The rows as JSON objects keyed by column name.
    pub fn objects(&self) -> Vec<Value> {
        self.rows
            .iter()
            .map(|row| {
                let mut object = Map::new();
                for (column, value) in self.columns.iter().zip(row.iter()) {
                    object.insert(column.clone(), value.clone());
                }
                Value::Object(object)
            })
            .collect()
    }
}

/// Write a table in the requested format.
pub fn write_table(out: &mut impl Write, table: &Table, format: Format) -> Result<()> {
    match format {
        Format::Json => {
            let objects = table.objects();
            serde_json::to_writer_pretty(&mut *out, &objects)?;
            writeln!(out)?;
        }
        Format::Jsonl => {
            for object in table.objects() {
                serde_json::to_writer(&mut *out, &object)?;
                writeln!(out)?;
            }
        }
        Format::Csv => {
            writeln!(out, "{}", table.columns.join(","))?;
            for row in &table.rows {
                let cells: Vec<String> = row.iter().map(csv_cell).collect();
                writeln!(out, "{}", cells.join(","))?;
            }
        }
        Format::Table => {
            write_aligned(out, table)?;
        }
    }
    Ok(())
}

/// Render a table as an aligned block of text.
pub fn write_aligned(out: &mut impl Write, table: &Table) -> Result<()> {
    let mut cells: Vec<Vec<String>> = Vec::with_capacity(table.rows.len());
    for row in &table.rows {
        cells.push(row.iter().map(display_cell).collect());
    }
    let widths: Vec<usize> = table
        .columns
        .iter()
        .enumerate()
        .map(|(i, column)| {
            let longest = cells
                .iter()
                .filter_map(|row| row.get(i))
                .map(|cell| cell.chars().count())
                .max()
                .unwrap_or(0);
            column.chars().count().max(longest)
        })
        .collect();

    let mut write_row = |row: &[String]| -> Result<()> {
        let mut line = String::new();
        for (i, cell) in row.iter().enumerate() {
            if i > 0 {
                line.push_str("  ");
            }
            let pad = widths[i].saturating_sub(cell.chars().count());
            line.push_str(cell);
            line.push_str(&" ".repeat(pad));
        }
        writeln!(out, "{}", line.trim_end())?;
        Ok(())
    };

    write_row(&table.columns)?;
    for row in &cells {
        write_row(row)?;
    }
    Ok(())
}

/// One cell as it appears in a table: JSON values without the quotes.
pub fn display_cell(value: &Value) -> String {
    match value {
        Value::Null => "NULL".into(),
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// One cell as it appears in CSV: quoted when it needs to be.
fn csv_cell(value: &Value) -> String {
    match value {
        Value::Null => String::new(),
        Value::String(s) => {
            if s.contains([',', '"', '\n', '\r']) {
                format!("\"{}\"", s.replace('"', "\"\""))
            } else {
                s.clone()
            }
        }
        other => other.to_string(),
    }
}