parquet-cli 0.1.6

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! A plan for writing a Parquet file.
//!
//! The vocabulary is DuckDB's — the names of its `COPY ... TO` options — so
//! that somebody who knows DuckDB already knows this. A plan is a set of
//! options; turning it into a writer is a translation, and the translation
//! lives here (in Rust), not in the script that writes the plan.

use std::collections::BTreeMap;

use anyhow::{anyhow, Context, Result};
use parquet::basic::{Compression, Encoding};
use parquet::file::metadata::KeyValue;
use parquet::file::properties::{EnabledStatistics, WriterProperties, WriterVersion};
use parquet::schema::types::ColumnPath;

/// The options we know about, and whether we can do them yet.
///
/// The names are DuckDB's `COPY ... TO` options for Parquet (taken from
/// `parquet_extension.cpp` in the DuckDB source).
const KNOWN: &[(&str, bool)] = &[
    ("compression", true),
    ("codec", true),
    ("compression_level", true),
    ("row_group_size", true),
    ("row_group_size_bytes", true),
    ("row_groups_per_file", false),
    ("data_page_size_limit", true),
    ("dictionary_size_limit", true),
    ("string_dictionary_page_size_limit", true),
    ("write_bloom_filter", true),
    ("bloom_filter_false_positive_ratio", true),
    ("write_page_index", true),
    ("parquet_version", true),
    ("kv_metadata", true),
    ("write_timestamp_as_int96", false),
    ("timestamp_is_adjusted_to_utc", false),
    ("encryption_config", false),
    ("shredding", false),
    ("field_ids", false),
    // Ours: DuckDB decides on its own whether a dictionary pays, and deprecated
    // the option that used to say so. We keep the name and make it work.
    ("dictionary_compression_ratio_threshold", true),
    // Ours: the dictionary, on or off, for every column or for one.
    ("dictionary", true),
    // Ours: the encoding, for every column or for one.
    ("encoding", true),
];

/// The options we know, and whether we can do them yet.
pub fn known_options() -> Vec<(&'static str, bool)> {
    KNOWN.to_vec()
}

/// One column, as far as a plan is concerned.
#[derive(Clone, Debug)]
pub struct Column {
    /// The column's name.
    pub name: String,
    /// How many different values it has, when we know.
    pub distinct: Option<u64>,
    /// How many rows the file has.
    pub rows: i64,
}

/// A plan: the options for writing a file.
#[derive(Clone, Debug, Default)]
pub struct Plan {
    options: BTreeMap<String, String>,
}

impl Plan {
    /// A plan with nothing in it.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set an option. The name is checked, so a typo is an error and not a
    /// setting that quietly does nothing.
    pub fn set(&mut self, name: &str, value: &str) -> Result<()> {
        let name = name.trim().to_lowercase();
        let (name, column) = match name.split_once('.') {
            Some((name, column)) => (name.to_string(), Some(column.to_string())),
            None => (name, None),
        };
        let known = KNOWN.iter().find(|(option, _)| *option == name);
        match known {
            Some((_, true)) => {}
            Some((_, false)) => return Err(anyhow!("{name} is a DuckDB option we do not do yet")),
            None => {
                return Err(anyhow!(
                    "unknown option: {name} (the ones we know: {})",
                    KNOWN
                        .iter()
                        .filter(|(_, supported)| *supported)
                        .map(|(option, _)| *option)
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            }
        }
        let key = match column {
            Some(column) => format!("{name}.{column}"),
            None => name,
        };
        self.options.insert(key, value.to_string());
        Ok(())
    }

    /// Take the options of another plan on top of this one.
    pub fn merge(&mut self, other: &Plan) {
        for (name, value) in &other.options {
            self.options.insert(name.clone(), value.clone());
        }
    }

    /// The value of an option.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.options.get(name).map(|value| value.as_str())
    }

    /// The value of an option for one column.
    pub fn get_for(&self, name: &str, column: &str) -> Option<&str> {
        self.get(&format!("{name}.{column}"))
    }

    /// The options, for printing.
    pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
        self.options.iter()
    }

    /// Whether the plan needs to know how many distinct values each column
    /// has.
    pub fn needs_distinct(&self) -> bool {
        self.get("dictionary_compression_ratio_threshold").is_some()
    }

    /// Turn the plan into the settings a writer takes.
    ///
    /// `columns` is what the plan needs to know about the data: the columns
    /// and, where we counted them, how many different values they have.
    pub fn writer_properties(&self, columns: &[Column]) -> Result<WriterProperties> {
        let mut properties = WriterProperties::builder();

        if let Some(codec) = self.get("compression").or_else(|| self.get("codec")) {
            properties = properties.set_compression(compression_of(codec, self.level())?);
        }
        if let Some(rows) = self.get("row_group_size") {
            properties =
                properties.set_max_row_group_row_count(Some(number(rows, "row_group_size")?));
        }
        if let Some(bytes) = self.get("row_group_size_bytes") {
            properties =
                properties.set_max_row_group_bytes(Some(number(bytes, "row_group_size_bytes")?));
        }
        if let Some(size) = self.get("data_page_size_limit") {
            properties = properties.set_data_page_size_limit(number(size, "data_page_size_limit")?);
        }
        if let Some(size) = self.get("dictionary_size_limit") {
            properties =
                properties.set_dictionary_page_size_limit(number(size, "dictionary_size_limit")?);
        }
        if let Some(on) = self.get("write_bloom_filter") {
            properties = properties.set_bloom_filter_enabled(on_off(on, "write_bloom_filter")?);
        }
        if let Some(ratio) = self.get("bloom_filter_false_positive_ratio") {
            properties = properties
                .set_bloom_filter_fpp(decimal(ratio, "bloom_filter_false_positive_ratio")?);
        }
        if let Some(on) = self.get("write_page_index") {
            let on = on_off(on, "write_page_index")?;
            // The page index is the offset index plus the per-page statistics.
            properties = properties.set_offset_index_disabled(!on);
            properties = properties.set_statistics_enabled(if on {
                EnabledStatistics::Page
            } else {
                EnabledStatistics::Chunk
            });
        }
        if let Some(version) = self.get("parquet_version") {
            properties = properties.set_writer_version(match version.to_lowercase().as_str() {
                "v1" | "1" | "1.0" => WriterVersion::PARQUET_1_0,
                "v2" | "2" | "2.0" => WriterVersion::PARQUET_2_0,
                other => return Err(anyhow!("parquet_version takes v1 or v2, not {other}")),
            });
        }
        if let Some(metadata) = self.get("kv_metadata") {
            let entries: Vec<KeyValue> = metadata
                .split(',')
                .filter(|pair| !pair.is_empty())
                .filter_map(|pair| {
                    pair.split_once('=').map(|(key, value)| KeyValue {
                        key: key.to_string(),
                        value: Some(value.to_string()),
                    })
                })
                .collect();
            properties = properties.set_key_value_metadata(Some(entries));
        }
        if let Some(encoding) = self.get("encoding") {
            properties = properties.set_encoding(encoding_of(encoding)?);
        }
        if let Some(on) = self.get("dictionary") {
            properties = properties.set_dictionary_enabled(on_off(on, "dictionary")?);
        }

        // The per-column knobs: a column's own setting wins over the global one.
        for column in columns {
            let path = ColumnPath::from(column.name.clone());
            if let Some(codec) = self.get_for("compression", &column.name) {
                properties = properties
                    .set_column_compression(path.clone(), compression_of(codec, self.level())?);
            }
            if let Some(encoding) = self.get_for("encoding", &column.name) {
                properties = properties.set_column_encoding(path.clone(), encoding_of(encoding)?);
            }
            if let Some(on) = self.get_for("dictionary", &column.name) {
                properties = properties
                    .set_column_dictionary_enabled(path.clone(), on_off(on, "dictionary")?);
            }
        }

        // Our own: the dictionary only pays when the values repeat. The
        // threshold is the share of rows that may have a different value; a
        // column above it is written without a dictionary.
        if let Some(threshold) = self.get("dictionary_compression_ratio_threshold") {
            let threshold = decimal(threshold, "dictionary_compression_ratio_threshold")?;
            for column in columns {
                properties = properties.set_column_dictionary_enabled(
                    ColumnPath::from(column.name.clone()),
                    dictionary_pays(column, threshold),
                );
            }
        }

        Ok(properties.build())
    }

    /// The compression level, if the plan has one.
    fn level(&self) -> Option<i32> {
        self.get("compression_level")
            .and_then(|level| level.parse().ok())
    }
}

/// Whether a column's dictionary pays for itself.
///
/// The dictionary has to hold every different value, and every row still needs
/// an index into it. So the dictionary pays when the values repeat: the
/// threshold is the share of rows that may have a different value.
fn dictionary_pays(column: &Column, threshold: f64) -> bool {
    match column.distinct {
        Some(distinct) => {
            if column.rows <= 0 {
                return true;
            }
            (distinct as f64) / (column.rows as f64) <= threshold
        }
        None => true,
    }
}

/// Read a number.
fn number(value: &str, name: &str) -> Result<usize> {
    value
        .parse()
        .with_context(|| format!("{name} takes a number, not {value}"))
}

/// Read a decimal number.
fn decimal(value: &str, name: &str) -> Result<f64> {
    value
        .parse()
        .with_context(|| format!("{name} takes a number, not {value}"))
}

/// Read an on or off.
fn on_off(value: &str, name: &str) -> Result<bool> {
    match value.to_lowercase().as_str() {
        "on" | "true" | "yes" | "1" => Ok(true),
        "off" | "false" | "no" | "0" => Ok(false),
        other => Err(anyhow!("{name} takes on or off, not {other}")),
    }
}

/// Read a compression, with the level the plan gives.
fn compression_of(name: &str, level: Option<i32>) -> Result<Compression> {
    let level = level.unwrap_or(1);
    match name.to_lowercase().as_str() {
        "snappy" => Ok(Compression::SNAPPY),
        "none" | "uncompressed" => Ok(Compression::UNCOMPRESSED),
        "lz4" | "lz4_raw" => Ok(Compression::LZ4_RAW),
        "gzip" => Ok(Compression::GZIP(parquet::basic::GzipLevel::try_new(
            level.max(1) as u32,
        )?)),
        "brotli" => Ok(Compression::BROTLI(parquet::basic::BrotliLevel::try_new(
            level.max(1) as u32,
        )?)),
        "zstd" => Ok(Compression::ZSTD(parquet::basic::ZstdLevel::try_new(
            level,
        )?)),
        other => Err(anyhow!("unknown compression: {other}")),
    }
}

/// Read an encoding.
fn encoding_of(name: &str) -> Result<Encoding> {
    match name.to_lowercase().as_str() {
        "plain" => Ok(Encoding::PLAIN),
        "delta" | "delta_binary_packed" => Ok(Encoding::DELTA_BINARY_PACKED),
        "delta-length-bytes" => Ok(Encoding::DELTA_LENGTH_BYTE_ARRAY),
        other => Err(anyhow!("unknown encoding: {other}")),
    }
}

/// Read one option the user gave, in either DuckDB's spelling or the short
/// one.
///
/// DuckDB's spelling is `name=value` (`compression=zstd`). The short one is
/// `name:value` (`zstd:19`), which is what the command line is nicer with.
pub fn parse_option(option: &str) -> Result<Vec<(String, String)>> {
    let option = option.trim();
    if let Some((name, value)) = option.split_once('=') {
        return Ok(vec![(name.trim().to_string(), value.trim().to_string())]);
    }
    if let Some((name, value)) = option.split_once(':') {
        return Ok(match name.to_lowercase().as_str() {
            "row-group" | "row_group" | "rowgroup" => {
                vec![("row_group_size".to_string(), value.trim().to_string())]
            }
            "page-size" | "page_size" => {
                vec![("data_page_size_limit".to_string(), value.trim().to_string())]
            }
            "dictionary" => vec![("dictionary".to_string(), value.trim().to_string())],
            "encoding" => vec![("encoding".to_string(), value.trim().to_string())],
            "data-page" | "data_page" => {
                vec![("parquet_version".to_string(), value.trim().to_string())]
            }
            _ => {
                // A compression with its level: `zstd:19`.
                vec![
                    ("compression".to_string(), name.trim().to_string()),
                    ("compression_level".to_string(), value.trim().to_string()),
                ]
            }
        });
    }
    // A bare compression: `snappy`.
    Ok(vec![("compression".to_string(), option.to_string())])
}