parquet-cli 0.1.0

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! What is in the file: its facts, its schema, and its columns' statistics.

use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::File;
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::data_type::AsBytes;
use parquet::file::metadata::ParquetMetaData;
use parquet::file::statistics::Statistics;
use serde_json::{json, Map, Value};

use crate::value::{data_type_name, field_json};

/// Open a Parquet file and read its footer.
pub fn open(path: &Path) -> Result<Arc<ParquetMetaData>> {
    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()))?;
    Ok(builder.metadata().clone())
}

/// File-level facts: size, rows, row groups, who wrote it.
pub fn facts(path: &Path) -> Result<Value> {
    let metadata = open(path)?;
    let file = metadata.file_metadata();
    let size = std::fs::metadata(path)?.len();
    let rows = file.num_rows();

    let mut compressions = BTreeSet::new();
    let mut encodings = BTreeSet::new();
    for group in metadata.row_groups() {
        for chunk in group.columns() {
            compressions.insert(format!("{}", chunk.compression_codec()));
            for encoding in chunk.encodings() {
                encodings.insert(format!("{encoding}"));
            }
        }
    }

    let key_value_metadata: Vec<Value> = file
        .key_value_metadata()
        .map(|entries| {
            entries
                .iter()
                .map(|entry| {
                    json!({
                        "key": entry.key,
                        "value": entry.value,
                    })
                })
                .collect()
        })
        .unwrap_or_default();

    let row_groups: Vec<Value> = metadata
        .row_groups()
        .iter()
        .enumerate()
        .map(|(index, group)| {
            json!({
                "index": index,
                "rows": group.num_rows(),
                "compressed_size": group.compressed_size(),
                "uncompressed_size": group.total_byte_size(),
            })
        })
        .collect();

    Ok(json!({
        "file": path.display().to_string(),
        "size_bytes": size,
        "rows": rows,
        "row_groups": metadata.row_groups().len(),
        "columns": metadata.file_metadata().schema_descr().num_columns(),
        "format_version": file.version(),
        "created_by": file.created_by(),
        "bytes_per_row": if rows > 0 { size as f64 / rows as f64 } else { 0.0 },
        "compressions": compressions.into_iter().collect::<Vec<_>>(),
        "encodings": encodings.into_iter().collect::<Vec<_>>(),
        "key_value_metadata": key_value_metadata,
        "row_group_detail": row_groups,
    }))
}

/// The schema, as Arrow sees it.
pub fn schema(path: &Path) -> Result<Value> {
    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 arrow_schema = builder.schema().clone();
    let fields: Vec<Value> = arrow_schema
        .fields()
        .iter()
        .map(|field| field_json(field.as_ref()))
        .collect();
    Ok(json!({
        "file": path.display().to_string(),
        "fields": fields,
    }))
}

/// The schema as flat lines: `name  type  nullable`.
pub fn schema_lines(path: &Path) -> Result<Vec<(String, String, bool)>> {
    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 arrow_schema = builder.schema().clone();
    let mut lines = Vec::new();
    for field in arrow_schema.fields().iter() {
        lines.push((
            field.name().clone(),
            data_type_name(field.data_type()),
            field.is_nullable(),
        ));
    }
    Ok(lines)
}

/// Per-column statistics, taken from the footer.
///
/// With `scan`, the file is also read so the distinct counts are exact.
pub fn columns(path: &Path, scan: bool) -> Result<Value> {
    let metadata = open(path)?;
    let arrow_schema = {
        let file = File::open(path)?;
        ParquetRecordBatchReaderBuilder::try_new(file)?
            .schema()
            .clone()
    };

    let distinct_counts: Option<Vec<HashSet<String>>> = if scan {
        Some(scan_distinct(path)?)
    } else {
        None
    };

    // The footer describes columns in leaf order; the Arrow schema describes
    // them in field order. Pair them by index so both agree.
    let leaf_names: Vec<String> = metadata
        .file_metadata()
        .schema_descr()
        .columns()
        .iter()
        .map(|column| column.path().string())
        .collect();
    let arrow_names: Vec<String> = arrow_schema
        .fields()
        .iter()
        .map(|field| field.name().clone())
        .collect();

    let mut out = Vec::new();
    // Gather per column across row groups.
    let mut per_column: BTreeMap<usize, ColumnStats> = BTreeMap::new();
    for (group_index, group) in metadata.row_groups().iter().enumerate() {
        for (position, chunk) in group.columns().iter().enumerate() {
            let stats = per_column.entry(position).or_insert_with(|| ColumnStats {
                path: chunk.column_path().string(),
                physical_type: format!("{}", chunk.column_type()),
                logical_type: chunk
                    .column_descr()
                    .logical_type_ref()
                    .map(|logical| format!("{logical:?}"))
                    .unwrap_or_else(|| "-".into()),
                compression: format!("{}", chunk.compression_codec()),
                encodings: BTreeSet::new(),
                num_values: 0,
                null_count: 0,
                min: None,
                max: None,
                compressed_size: 0,
                uncompressed_size: 0,
                row_groups: Vec::new(),
            });
            stats
                .encodings
                .extend(chunk.encodings().map(|e| format!("{e}")));
            stats.num_values += chunk.num_values();
            stats.compressed_size += chunk.compressed_size();
            stats.uncompressed_size += chunk.uncompressed_size();
            let mut group_min = Value::Null;
            let mut group_max = Value::Null;
            if let Some(statistics) = chunk.statistics() {
                stats.null_count += statistics.null_count_opt().unwrap_or(0);
                let (min, max) = bounds(statistics);
                group_min = min.clone().unwrap_or(Value::Null);
                group_max = max.clone().unwrap_or(Value::Null);
                stats.min = merge_min(stats.min.take(), min);
                stats.max = merge_max(stats.max.take(), max);
            }
            stats.row_groups.push(json!({
                "index": group_index,
                "rows": group.num_rows(),
                "min": group_min,
                "max": group_max,
            }));
        }
    }

    for (position, stats) in per_column.iter() {
        let name = arrow_names
            .get(*position)
            .cloned()
            .unwrap_or_else(|| leaf_names.get(*position).cloned().unwrap_or_default());
        let mut object = Map::new();
        object.insert("name".into(), Value::String(name));
        object.insert("path".into(), Value::String(stats.path.clone()));
        object.insert(
            "physical_type".into(),
            Value::String(stats.physical_type.clone()),
        );
        object.insert(
            "logical_type".into(),
            Value::String(stats.logical_type.clone()),
        );
        object.insert(
            "compression".into(),
            Value::String(stats.compression.clone()),
        );
        object.insert(
            "encodings".into(),
            Value::Array(
                stats
                    .encodings
                    .iter()
                    .map(|e| Value::String(e.clone()))
                    .collect(),
            ),
        );
        object.insert("num_values".into(), json!(stats.num_values));
        object.insert("null_count".into(), json!(stats.null_count));
        object.insert("min".into(), stats.min.clone().unwrap_or(Value::Null));
        object.insert("max".into(), stats.max.clone().unwrap_or(Value::Null));
        object.insert("compressed_size".into(), json!(stats.compressed_size));
        object.insert("uncompressed_size".into(), json!(stats.uncompressed_size));
        object.insert(
            "ratio".into(),
            json!(if stats.uncompressed_size > 0 {
                stats.compressed_size as f64 / stats.uncompressed_size as f64
            } else {
                0.0
            }),
        );
        object.insert(
            "bytes_per_value".into(),
            json!(if stats.num_values > 0 {
                stats.compressed_size as f64 / stats.num_values as f64
            } else {
                0.0
            }),
        );
        if let Some(distinct) = &distinct_counts {
            object.insert(
                "distinct_count".into(),
                json!(distinct.get(*position).map(|set| set.len()).unwrap_or(0)),
            );
        }
        object.insert("row_groups".into(), Value::Array(stats.row_groups.clone()));
        out.push(Value::Object(object));
    }

    Ok(json!({
        "file": path.display().to_string(),
        "columns": out,
    }))
}

struct ColumnStats {
    path: String,
    physical_type: String,
    logical_type: String,
    compression: String,
    encodings: BTreeSet<String>,
    num_values: i64,
    null_count: u64,
    min: Option<Value>,
    max: Option<Value>,
    compressed_size: i64,
    uncompressed_size: i64,
    row_groups: Vec<Value>,
}

/// Read the file and count the distinct values of every column.
fn scan_distinct(path: &Path) -> Result<Vec<HashSet<String>>> {
    let file = File::open(path)?;
    let reader = ParquetRecordBatchReaderBuilder::try_new(file)?
        .with_batch_size(8192)
        .build()?;
    let mut sets: Vec<HashSet<String>> = Vec::new();
    for batch in reader {
        let batch = batch?;
        if sets.is_empty() {
            sets = (0..batch.num_columns()).map(|_| HashSet::new()).collect();
        }
        for (index, column) in batch.columns().iter().enumerate() {
            let set = &mut sets[index];
            for row in 0..batch.num_rows() {
                let value = crate::value::cell(column, row);
                set.insert(value.to_string());
            }
        }
    }
    Ok(sets)
}

/// The smallest of two bounds, comparing as JSON numbers when possible.
fn merge_min(left: Option<Value>, right: Option<Value>) -> Option<Value> {
    match (left, right) {
        (None, other) | (other, None) => other,
        (Some(a), Some(b)) => {
            let take_a = match (&a, &b) {
                (Value::Number(x), Value::Number(y)) => {
                    x.as_f64().unwrap_or(f64::MAX) <= y.as_f64().unwrap_or(f64::MAX)
                }
                _ => {
                    let (a, b) = (a.to_string(), b.to_string());
                    a <= b
                }
            };
            Some(if take_a { a } else { b })
        }
    }
}

/// The largest of two bounds, comparing as JSON numbers when possible.
fn merge_max(left: Option<Value>, right: Option<Value>) -> Option<Value> {
    match (left, right) {
        (None, other) | (other, None) => other,
        (Some(a), Some(b)) => {
            let take_a = match (&a, &b) {
                (Value::Number(x), Value::Number(y)) => {
                    x.as_f64().unwrap_or(f64::MIN) >= y.as_f64().unwrap_or(f64::MIN)
                }
                _ => {
                    let (a, b) = (a.to_string(), b.to_string());
                    a >= b
                }
            };
            Some(if take_a { a } else { b })
        }
    }
}

/// The min and max of a column's statistics.
fn bounds(statistics: &Statistics) -> (Option<Value>, Option<Value>) {
    match statistics {
        Statistics::Boolean(values) => (
            values.min_opt().map(|v| Value::Bool(*v)),
            values.max_opt().map(|v| Value::Bool(*v)),
        ),
        Statistics::Int32(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::Int64(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::Int96(values) => (
            values.min_opt().map(|v| json!(v.to_string())),
            values.max_opt().map(|v| json!(v.to_string())),
        ),
        Statistics::Float(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::Double(values) => (
            values.min_opt().map(|v| json!(v)),
            values.max_opt().map(|v| json!(v)),
        ),
        Statistics::ByteArray(values) => (
            values.min_opt().map(|v| bytes_value(v.as_bytes())),
            values.max_opt().map(|v| bytes_value(v.as_bytes())),
        ),
        Statistics::FixedLenByteArray(values) => (
            values.min_opt().map(|v| bytes_value(v.as_bytes())),
            values.max_opt().map(|v| bytes_value(v.as_bytes())),
        ),
    }
}

/// Bytes as text when they are text, as hex when they are not.
fn bytes_value(bytes: &[u8]) -> Value {
    match std::str::from_utf8(bytes) {
        Ok(text) => Value::String(text.to_string()),
        Err(_) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
    }
}