parquet-cli 0.1.2

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! pqt — inspect, measure and convert Parquet files.

use std::io::Write;
use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand};
use serde_json::Value;

use parquet_cli::advise;
use parquet_cli::meta;
use parquet_cli::output::{write_aligned, write_table, Format, Table};
use parquet_cli::rows::{self, ConvertFormat};

#[derive(Parser, Debug)]
#[command(
    name = "pqt",
    version,
    about = "A Parquet CLI for AI agents",
    long_about = "Inspect, measure and convert Parquet files.\n\n\
Every command is non-interactive, and every command has a JSON form: pass \
--json and the result is one object on stdout, ready to be read by a program."
)]
struct Cli {
    /// Print JSON instead of a human table.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Facts about the file: size, rows, row groups, who wrote it.
    Info {
        /// The Parquet file.
        file: PathBuf,
    },

    /// The schema of the file.
    Schema {
        /// The Parquet file.
        file: PathBuf,
    },

    /// Per-column statistics: values, nulls, bounds, bytes.
    Columns {
        /// The Parquet file.
        file: PathBuf,
        /// Read the data too, so the distinct counts are exact.
        #[arg(long)]
        scan: bool,
    },

    /// The first rows of the file.
    Head {
        /// The Parquet file.
        file: PathBuf,
        /// How many rows to print.
        #[arg(short = 'n', long, default_value_t = 10)]
        rows: usize,
        /// How to print them.
        #[arg(long, value_enum, default_value_t = Format::Table)]
        format: Format,
    },

    /// All the rows of one or more files.
    Cat {
        /// The Parquet files.
        files: Vec<PathBuf>,
        /// How to print them.
        #[arg(long, value_enum, default_value_t = Format::Table)]
        format: Format,
    },

    /// Look at the data and say what could be better.
    Advise {
        /// The Parquet file.
        file: PathBuf,
        /// Read the data too, so the advice can use the distinct values.
        #[arg(long)]
        scan: bool,
        /// Rewrite the largest columns with a constant, to see what their
        /// values cost. The number is how many columns.
        #[arg(long, value_name = "N")]
        contrast: Option<usize>,
    },

    /// Check the file's structure.
    Validate {
        /// The Parquet file.
        file: PathBuf,
    },

    /// Write the file out in another form.
    To {
        /// The Parquet file.
        file: PathBuf,
        /// Where to write it.
        #[arg(long)]
        out: PathBuf,
        /// What to write.
        #[arg(long, value_enum, default_value_t = ConvertFormat::Csv)]
        format: ConvertFormat,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    let mut out = std::io::stdout().lock();

    match cli.command {
        Command::Info { file } => {
            let facts = meta::facts(&file)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&facts)?)?;
            } else {
                print_facts(&mut out, &facts)?;
            }
        }
        Command::Schema { file } => {
            let schema = meta::schema(&file)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&schema)?)?;
            } else {
                let lines = meta::schema_lines(&file)?;
                let mut table = Table::new(vec!["column".into(), "type".into(), "nullable".into()]);
                for (name, data_type, nullable) in lines {
                    table.push(vec![
                        Value::String(name),
                        Value::String(data_type),
                        Value::Bool(nullable),
                    ]);
                }
                write_aligned(&mut out, &table)?;
            }
        }
        Command::Columns { file, scan } => {
            let columns = meta::columns(&file, scan)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&columns)?)?;
            } else {
                let mut table = Table::new(vec![
                    "column".into(),
                    "type".into(),
                    "compression".into(),
                    "values".into(),
                    "nulls".into(),
                    "min".into(),
                    "max".into(),
                    "bytes".into(),
                    "bytes/value".into(),
                ]);
                for column in columns["columns"].as_array().into_iter().flatten() {
                    table.push(vec![
                        column["name"].clone(),
                        column["type"].clone(),
                        column["compression"].clone(),
                        column["num_values"].clone(),
                        column["null_count"].clone(),
                        column["min"].clone(),
                        column["max"].clone(),
                        column["compressed_size"].clone(),
                        column["bytes_per_value"].clone(),
                    ]);
                }
                write_aligned(&mut out, &table)?;
            }
        }
        Command::Head { file, rows, format } => {
            let table = rows::head(&file, rows)?;
            write_table(&mut out, &table, format_for(cli.json, format))?;
        }
        Command::Cat { files, format } => {
            let table = rows::cat(&files)?;
            write_table(&mut out, &table, format_for(cli.json, format))?;
        }
        Command::Advise {
            file,
            scan,
            contrast,
        } => {
            let advice = advise::advise(&file, scan, contrast)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&advice.to_json())?)?;
            } else {
                print_advice(&mut out, &advice)?;
            }
        }
        Command::Validate { file } => {
            let report = parquet_cli::validate::validate(&file)?;
            if cli.json {
                writeln!(out, "{}", serde_json::to_string_pretty(&report)?)?;
            } else {
                for check in report["checks"].as_array().into_iter().flatten() {
                    let mark = if check["ok"].as_bool().unwrap_or(false) {
                        "ok"
                    } else {
                        "FAIL"
                    };
                    writeln!(
                        out,
                        "{mark:>4}  {:<14} {}",
                        check["name"].as_str().unwrap_or_default(),
                        check["detail"].as_str().unwrap_or_default()
                    )?;
                }
            }
            if !report["ok"].as_bool().unwrap_or(false) {
                std::process::exit(1);
            }
        }
        Command::To {
            file,
            out: target,
            format,
        } => {
            rows::convert(&file, &target, format)?;
            if cli.json {
                writeln!(
                    out,
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "file": file.display().to_string(),
                        "out": target.display().to_string(),
                        "format": format.to_string(),
                    }))?
                )?;
            } else {
                writeln!(out, "{} -> {}", file.display(), target.display())?;
            }
        }
    }
    Ok(())
}

/// Print the advice: what the file holds, then what could be better.
fn print_advice(out: &mut impl Write, advice: &advise::Advice) -> Result<()> {
    let mut facts = Table::new(vec!["file".into(), "size_bytes".into(), "rows".into()]);
    facts.push(vec![
        Value::String(advice.file.clone()),
        Value::from(advice.size_bytes),
        Value::from(advice.rows),
    ]);
    write_aligned(out, &facts)?;

    let mut columns = Table::new(vec![
        "column".into(),
        "type".into(),
        "bytes".into(),
        "share".into(),
        "distinct".into(),
        "values".into(),
        "shape".into(),
    ]);
    for column in &advice.columns {
        columns.push(vec![
            Value::String(column.name.clone()),
            Value::String(column.data_type.clone()),
            Value::from(column.bytes),
            Value::String(format!("{:.1}%", column.share * 100.0)),
            match column.distinct {
                Some(distinct) => Value::from(distinct),
                None => Value::Null,
            },
            match column.value_bytes {
                Some(bytes) => Value::from(bytes),
                None => Value::Null,
            },
            match column.structure_bytes {
                Some(bytes) => Value::from(bytes),
                None => Value::Null,
            },
        ]);
    }
    write_aligned(out, &columns)?;

    if advice.findings.is_empty() {
        writeln!(out, "\nnothing to complain about")?;
        return Ok(());
    }
    writeln!(out)?;
    for finding in &advice.findings {
        let column = match &finding.column {
            Some(column) => format!("{column}: "),
            None => String::new(),
        };
        writeln!(
            out,
            "{:>7}  {:<20} {}{}",
            finding.severity, finding.rule, column, finding.message
        )?;
    }
    Ok(())
}

/// `--json` wins over the format, so that every command has one JSON form.
fn format_for(json: bool, format: Format) -> Format {
    if json && format == Format::Table {
        Format::Json
    } else {
        format
    }
}

/// Print the file's facts as `key: value` lines.
fn print_facts(out: &mut impl Write, facts: &Value) -> Result<()> {
    let mut pairs: Vec<(String, Value)> = Vec::new();
    for key in [
        "file",
        "size_bytes",
        "rows",
        "row_groups",
        "columns",
        "format_version",
        "created_by",
        "bytes_per_row",
    ] {
        if let Some(value) = facts.get(key) {
            pairs.push((key.to_string(), value.clone()));
        }
    }
    for key in ["compressions", "encodings"] {
        if let Some(value) = facts.get(key) {
            let list: Vec<String> = value
                .as_array()
                .map(|items| {
                    items
                        .iter()
                        .map(|item| item.as_str().unwrap_or_default().to_string())
                        .collect()
                })
                .unwrap_or_default();
            pairs.push((key.to_string(), Value::String(list.join(", "))));
        }
    }
    let width = pairs.iter().map(|(key, _)| key.len()).max().unwrap_or(0);
    for (key, value) in pairs {
        let text = match value {
            Value::String(s) => s,
            other => other.to_string(),
        };
        writeln!(out, "{key:<width$}  {text}")?;
    }
    Ok(())
}