parquet-cli 0.2.1

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! 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::{
    BloomFilterPosition, 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),
    // Ours (Arrow has them, DuckDB does not): the knobs that make the
    // metadata smaller.
    ("statistics_truncate_length", true),
    ("column_index_truncate_length", true),
    ("write_row_group_number_distinct_values", true),
    ("data_page_row_count_limit", true),
    ("write_page_header_statistics", true),
    ("bloom_filter_max_ndv", true),
    ("bloom_filter_position", true),
    ("bloom_filter_for_dictionary_encoded_chunks", true),
    ("created_by", true),
];

/// The columns of a file, with how many different values they have when the
/// plan needs to know.
pub fn columns_of(path: &std::path::Path, plan: &Plan, rows: i64) -> Result<Vec<Column>> {
    let facts = crate::meta::column_facts(path, false)?;
    let mut columns: Vec<Column> = facts
        .iter()
        .map(|column| Column {
            name: column.name.clone(),
            distinct: None,
            rows,
        })
        .collect();

    if plan.needs_distinct() {
        let distinct = crate::meta::scan_distinct(path)?;
        for (index, column) in columns.iter_mut().enumerate() {
            column.distinct = distinct.get(index).map(|values| values.len() as u64);
        }
    }
    Ok(columns)
}

/// 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(length) = self.get("statistics_truncate_length") {
            properties = properties.set_statistics_truncate_length(Some(number(
                length,
                "statistics_truncate_length",
            )?));
        }
        if let Some(length) = self.get("column_index_truncate_length") {
            properties = properties.set_column_index_truncate_length(Some(number(
                length,
                "column_index_truncate_length",
            )?));
        }
        if let Some(on) = self.get("write_row_group_number_distinct_values") {
            properties = properties.set_write_row_group_number_distinct_values(on_off(
                on,
                "write_row_group_number_distinct_values",
            )?);
        }
        if let Some(rows) = self.get("data_page_row_count_limit") {
            properties = properties
                .set_data_page_row_count_limit(number(rows, "data_page_row_count_limit")?);
        }
        if let Some(on) = self.get("write_page_header_statistics") {
            properties = properties
                .set_write_page_header_statistics(on_off(on, "write_page_header_statistics")?);
        }
        if let Some(count) = self.get("bloom_filter_max_ndv") {
            properties =
                properties.set_bloom_filter_max_ndv(number(count, "bloom_filter_max_ndv")? as u64);
        }
        if let Some(position) = self.get("bloom_filter_position") {
            properties =
                properties.set_bloom_filter_position(match position.to_lowercase().as_str() {
                    "after-row-group" => BloomFilterPosition::AfterRowGroup,
                    "end" => BloomFilterPosition::End,
                    other => {
                        return Err(anyhow!(
                            "bloom_filter_position takes after-row-group or end, not {other}"
                        ))
                    }
                });
        }
        if let Some(on) = self.get("bloom_filter_for_dictionary_encoded_chunks") {
            properties = properties.set_bloom_filter_for_dictionary_encoded_chunks(on_off(
                on,
                "bloom_filter_for_dictionary_encoded_chunks",
            )?);
        }
        if let Some(name) = self.get("created_by") {
            properties = properties.set_created_by(name.to_string());
        }
        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())])
}