Skip to main content

parquet_cli/
plan.rs

1//! A plan for writing a Parquet file.
2//!
3//! The vocabulary is DuckDB's — the names of its `COPY ... TO` options — so
4//! that somebody who knows DuckDB already knows this. A plan is a set of
5//! options; turning it into a writer is a translation, and the translation
6//! lives here (in Rust), not in the script that writes the plan.
7
8use std::collections::BTreeMap;
9
10use anyhow::{anyhow, Context, Result};
11use parquet::basic::{Compression, Encoding};
12use parquet::file::metadata::KeyValue;
13use parquet::file::properties::{
14    BloomFilterPosition, EnabledStatistics, WriterProperties, WriterVersion,
15};
16use parquet::schema::types::ColumnPath;
17
18/// The options we know about, and whether we can do them yet.
19///
20/// The names are DuckDB's `COPY ... TO` options for Parquet (taken from
21/// `parquet_extension.cpp` in the DuckDB source).
22const KNOWN: &[(&str, bool)] = &[
23    ("compression", true),
24    ("codec", true),
25    ("compression_level", true),
26    ("row_group_size", true),
27    ("row_group_size_bytes", true),
28    ("row_groups_per_file", false),
29    ("data_page_size_limit", true),
30    ("dictionary_size_limit", true),
31    ("string_dictionary_page_size_limit", true),
32    ("write_bloom_filter", true),
33    ("bloom_filter_false_positive_ratio", true),
34    ("write_page_index", true),
35    ("parquet_version", true),
36    ("kv_metadata", true),
37    ("write_timestamp_as_int96", false),
38    ("timestamp_is_adjusted_to_utc", false),
39    ("encryption_config", false),
40    ("shredding", false),
41    ("field_ids", false),
42    // Ours: DuckDB decides on its own whether a dictionary pays, and deprecated
43    // the option that used to say so. We keep the name and make it work.
44    ("dictionary_compression_ratio_threshold", true),
45    // Ours: the dictionary, on or off, for every column or for one.
46    ("dictionary", true),
47    // Ours: the encoding, for every column or for one.
48    ("encoding", true),
49    // Ours (Arrow has them, DuckDB does not): the knobs that make the
50    // metadata smaller.
51    ("statistics_truncate_length", true),
52    ("column_index_truncate_length", true),
53    ("write_row_group_number_distinct_values", true),
54    ("data_page_row_count_limit", true),
55    ("write_page_header_statistics", true),
56    ("bloom_filter_max_ndv", true),
57    ("bloom_filter_position", true),
58    ("bloom_filter_for_dictionary_encoded_chunks", true),
59    ("created_by", true),
60];
61
62/// The columns of a file, with how many different values they have when the
63/// plan needs to know.
64pub fn columns_of(path: &std::path::Path, plan: &Plan, rows: i64) -> Result<Vec<Column>> {
65    let facts = crate::meta::column_facts(path, false)?;
66    let mut columns: Vec<Column> = facts
67        .iter()
68        .map(|column| Column {
69            name: column.name.clone(),
70            distinct: None,
71            rows,
72        })
73        .collect();
74
75    if plan.needs_distinct() {
76        let distinct = crate::meta::scan_distinct(path)?;
77        for (index, column) in columns.iter_mut().enumerate() {
78            column.distinct = distinct.get(index).map(|values| values.len() as u64);
79        }
80    }
81    Ok(columns)
82}
83
84/// The options we know, and whether we can do them yet.
85pub fn known_options() -> Vec<(&'static str, bool)> {
86    KNOWN.to_vec()
87}
88
89/// One column, as far as a plan is concerned.
90#[derive(Clone, Debug)]
91pub struct Column {
92    /// The column's name.
93    pub name: String,
94    /// How many different values it has, when we know.
95    pub distinct: Option<u64>,
96    /// How many rows the file has.
97    pub rows: i64,
98}
99
100/// A plan: the options for writing a file.
101#[derive(Clone, Debug, Default)]
102pub struct Plan {
103    options: BTreeMap<String, String>,
104}
105
106impl Plan {
107    /// A plan with nothing in it.
108    pub fn new() -> Self {
109        Self::default()
110    }
111
112    /// Set an option. The name is checked, so a typo is an error and not a
113    /// setting that quietly does nothing.
114    pub fn set(&mut self, name: &str, value: &str) -> Result<()> {
115        let name = name.trim().to_lowercase();
116        let (name, column) = match name.split_once('.') {
117            Some((name, column)) => (name.to_string(), Some(column.to_string())),
118            None => (name, None),
119        };
120        let known = KNOWN.iter().find(|(option, _)| *option == name);
121        match known {
122            Some((_, true)) => {}
123            Some((_, false)) => return Err(anyhow!("{name} is a DuckDB option we do not do yet")),
124            None => {
125                return Err(anyhow!(
126                    "unknown option: {name} (the ones we know: {})",
127                    KNOWN
128                        .iter()
129                        .filter(|(_, supported)| *supported)
130                        .map(|(option, _)| *option)
131                        .collect::<Vec<_>>()
132                        .join(", ")
133                ))
134            }
135        }
136        let key = match column {
137            Some(column) => format!("{name}.{column}"),
138            None => name,
139        };
140        self.options.insert(key, value.to_string());
141        Ok(())
142    }
143
144    /// Take the options of another plan on top of this one.
145    pub fn merge(&mut self, other: &Plan) {
146        for (name, value) in &other.options {
147            self.options.insert(name.clone(), value.clone());
148        }
149    }
150
151    /// The value of an option.
152    pub fn get(&self, name: &str) -> Option<&str> {
153        self.options.get(name).map(|value| value.as_str())
154    }
155
156    /// The value of an option for one column.
157    pub fn get_for(&self, name: &str, column: &str) -> Option<&str> {
158        self.get(&format!("{name}.{column}"))
159    }
160
161    /// The options, for printing.
162    pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
163        self.options.iter()
164    }
165
166    /// Whether the plan needs to know how many distinct values each column
167    /// has.
168    pub fn needs_distinct(&self) -> bool {
169        self.get("dictionary_compression_ratio_threshold").is_some()
170    }
171
172    /// Turn the plan into the settings a writer takes.
173    ///
174    /// `columns` is what the plan needs to know about the data: the columns
175    /// and, where we counted them, how many different values they have.
176    pub fn writer_properties(&self, columns: &[Column]) -> Result<WriterProperties> {
177        let mut properties = WriterProperties::builder();
178
179        if let Some(codec) = self.get("compression").or_else(|| self.get("codec")) {
180            properties = properties.set_compression(compression_of(codec, self.level())?);
181        }
182        if let Some(rows) = self.get("row_group_size") {
183            properties =
184                properties.set_max_row_group_row_count(Some(number(rows, "row_group_size")?));
185        }
186        if let Some(bytes) = self.get("row_group_size_bytes") {
187            properties =
188                properties.set_max_row_group_bytes(Some(number(bytes, "row_group_size_bytes")?));
189        }
190        if let Some(size) = self.get("data_page_size_limit") {
191            properties = properties.set_data_page_size_limit(number(size, "data_page_size_limit")?);
192        }
193        if let Some(size) = self.get("dictionary_size_limit") {
194            properties =
195                properties.set_dictionary_page_size_limit(number(size, "dictionary_size_limit")?);
196        }
197        if let Some(on) = self.get("write_bloom_filter") {
198            properties = properties.set_bloom_filter_enabled(on_off(on, "write_bloom_filter")?);
199        }
200        if let Some(ratio) = self.get("bloom_filter_false_positive_ratio") {
201            properties = properties
202                .set_bloom_filter_fpp(decimal(ratio, "bloom_filter_false_positive_ratio")?);
203        }
204        if let Some(on) = self.get("write_page_index") {
205            let on = on_off(on, "write_page_index")?;
206            // The page index is the offset index plus the per-page statistics.
207            properties = properties.set_offset_index_disabled(!on);
208            properties = properties.set_statistics_enabled(if on {
209                EnabledStatistics::Page
210            } else {
211                EnabledStatistics::Chunk
212            });
213        }
214        if let Some(version) = self.get("parquet_version") {
215            properties = properties.set_writer_version(match version.to_lowercase().as_str() {
216                "v1" | "1" | "1.0" => WriterVersion::PARQUET_1_0,
217                "v2" | "2" | "2.0" => WriterVersion::PARQUET_2_0,
218                other => return Err(anyhow!("parquet_version takes v1 or v2, not {other}")),
219            });
220        }
221        if let Some(metadata) = self.get("kv_metadata") {
222            let entries: Vec<KeyValue> = metadata
223                .split(',')
224                .filter(|pair| !pair.is_empty())
225                .filter_map(|pair| {
226                    pair.split_once('=').map(|(key, value)| KeyValue {
227                        key: key.to_string(),
228                        value: Some(value.to_string()),
229                    })
230                })
231                .collect();
232            properties = properties.set_key_value_metadata(Some(entries));
233        }
234        if let Some(encoding) = self.get("encoding") {
235            properties = properties.set_encoding(encoding_of(encoding)?);
236        }
237        if let Some(length) = self.get("statistics_truncate_length") {
238            properties = properties.set_statistics_truncate_length(Some(number(
239                length,
240                "statistics_truncate_length",
241            )?));
242        }
243        if let Some(length) = self.get("column_index_truncate_length") {
244            properties = properties.set_column_index_truncate_length(Some(number(
245                length,
246                "column_index_truncate_length",
247            )?));
248        }
249        if let Some(on) = self.get("write_row_group_number_distinct_values") {
250            properties = properties.set_write_row_group_number_distinct_values(on_off(
251                on,
252                "write_row_group_number_distinct_values",
253            )?);
254        }
255        if let Some(rows) = self.get("data_page_row_count_limit") {
256            properties = properties
257                .set_data_page_row_count_limit(number(rows, "data_page_row_count_limit")?);
258        }
259        if let Some(on) = self.get("write_page_header_statistics") {
260            properties = properties
261                .set_write_page_header_statistics(on_off(on, "write_page_header_statistics")?);
262        }
263        if let Some(count) = self.get("bloom_filter_max_ndv") {
264            properties =
265                properties.set_bloom_filter_max_ndv(number(count, "bloom_filter_max_ndv")? as u64);
266        }
267        if let Some(position) = self.get("bloom_filter_position") {
268            properties =
269                properties.set_bloom_filter_position(match position.to_lowercase().as_str() {
270                    "after-row-group" => BloomFilterPosition::AfterRowGroup,
271                    "end" => BloomFilterPosition::End,
272                    other => {
273                        return Err(anyhow!(
274                            "bloom_filter_position takes after-row-group or end, not {other}"
275                        ))
276                    }
277                });
278        }
279        if let Some(on) = self.get("bloom_filter_for_dictionary_encoded_chunks") {
280            properties = properties.set_bloom_filter_for_dictionary_encoded_chunks(on_off(
281                on,
282                "bloom_filter_for_dictionary_encoded_chunks",
283            )?);
284        }
285        if let Some(name) = self.get("created_by") {
286            properties = properties.set_created_by(name.to_string());
287        }
288        if let Some(on) = self.get("dictionary") {
289            properties = properties.set_dictionary_enabled(on_off(on, "dictionary")?);
290        }
291
292        // The per-column knobs: a column's own setting wins over the global one.
293        for column in columns {
294            let path = ColumnPath::from(column.name.clone());
295            if let Some(codec) = self.get_for("compression", &column.name) {
296                properties = properties
297                    .set_column_compression(path.clone(), compression_of(codec, self.level())?);
298            }
299            if let Some(encoding) = self.get_for("encoding", &column.name) {
300                properties = properties.set_column_encoding(path.clone(), encoding_of(encoding)?);
301            }
302            if let Some(on) = self.get_for("dictionary", &column.name) {
303                properties = properties
304                    .set_column_dictionary_enabled(path.clone(), on_off(on, "dictionary")?);
305            }
306        }
307
308        // Our own: the dictionary only pays when the values repeat. The
309        // threshold is the share of rows that may have a different value; a
310        // column above it is written without a dictionary.
311        if let Some(threshold) = self.get("dictionary_compression_ratio_threshold") {
312            let threshold = decimal(threshold, "dictionary_compression_ratio_threshold")?;
313            for column in columns {
314                properties = properties.set_column_dictionary_enabled(
315                    ColumnPath::from(column.name.clone()),
316                    dictionary_pays(column, threshold),
317                );
318            }
319        }
320
321        Ok(properties.build())
322    }
323
324    /// The compression level, if the plan has one.
325    fn level(&self) -> Option<i32> {
326        self.get("compression_level")
327            .and_then(|level| level.parse().ok())
328    }
329}
330
331/// Whether a column's dictionary pays for itself.
332///
333/// The dictionary has to hold every different value, and every row still needs
334/// an index into it. So the dictionary pays when the values repeat: the
335/// threshold is the share of rows that may have a different value.
336fn dictionary_pays(column: &Column, threshold: f64) -> bool {
337    match column.distinct {
338        Some(distinct) => {
339            if column.rows <= 0 {
340                return true;
341            }
342            (distinct as f64) / (column.rows as f64) <= threshold
343        }
344        None => true,
345    }
346}
347
348/// Read a number.
349fn number(value: &str, name: &str) -> Result<usize> {
350    value
351        .parse()
352        .with_context(|| format!("{name} takes a number, not {value}"))
353}
354
355/// Read a decimal number.
356fn decimal(value: &str, name: &str) -> Result<f64> {
357    value
358        .parse()
359        .with_context(|| format!("{name} takes a number, not {value}"))
360}
361
362/// Read an on or off.
363fn on_off(value: &str, name: &str) -> Result<bool> {
364    match value.to_lowercase().as_str() {
365        "on" | "true" | "yes" | "1" => Ok(true),
366        "off" | "false" | "no" | "0" => Ok(false),
367        other => Err(anyhow!("{name} takes on or off, not {other}")),
368    }
369}
370
371/// Read a compression, with the level the plan gives.
372fn compression_of(name: &str, level: Option<i32>) -> Result<Compression> {
373    let level = level.unwrap_or(1);
374    match name.to_lowercase().as_str() {
375        "snappy" => Ok(Compression::SNAPPY),
376        "none" | "uncompressed" => Ok(Compression::UNCOMPRESSED),
377        "lz4" | "lz4_raw" => Ok(Compression::LZ4_RAW),
378        "gzip" => Ok(Compression::GZIP(parquet::basic::GzipLevel::try_new(
379            level.max(1) as u32,
380        )?)),
381        "brotli" => Ok(Compression::BROTLI(parquet::basic::BrotliLevel::try_new(
382            level.max(1) as u32,
383        )?)),
384        "zstd" => Ok(Compression::ZSTD(parquet::basic::ZstdLevel::try_new(
385            level,
386        )?)),
387        other => Err(anyhow!("unknown compression: {other}")),
388    }
389}
390
391/// Read an encoding.
392fn encoding_of(name: &str) -> Result<Encoding> {
393    match name.to_lowercase().as_str() {
394        "plain" => Ok(Encoding::PLAIN),
395        "delta" | "delta_binary_packed" => Ok(Encoding::DELTA_BINARY_PACKED),
396        "delta-length-bytes" => Ok(Encoding::DELTA_LENGTH_BYTE_ARRAY),
397        other => Err(anyhow!("unknown encoding: {other}")),
398    }
399}
400
401/// Read one option the user gave, in either DuckDB's spelling or the short
402/// one.
403///
404/// DuckDB's spelling is `name=value` (`compression=zstd`). The short one is
405/// `name:value` (`zstd:19`), which is what the command line is nicer with.
406pub fn parse_option(option: &str) -> Result<Vec<(String, String)>> {
407    let option = option.trim();
408    if let Some((name, value)) = option.split_once('=') {
409        return Ok(vec![(name.trim().to_string(), value.trim().to_string())]);
410    }
411    if let Some((name, value)) = option.split_once(':') {
412        return Ok(match name.to_lowercase().as_str() {
413            "row-group" | "row_group" | "rowgroup" => {
414                vec![("row_group_size".to_string(), value.trim().to_string())]
415            }
416            "page-size" | "page_size" => {
417                vec![("data_page_size_limit".to_string(), value.trim().to_string())]
418            }
419            "dictionary" => vec![("dictionary".to_string(), value.trim().to_string())],
420            "encoding" => vec![("encoding".to_string(), value.trim().to_string())],
421            "data-page" | "data_page" => {
422                vec![("parquet_version".to_string(), value.trim().to_string())]
423            }
424            _ => {
425                // A compression with its level: `zstd:19`.
426                vec![
427                    ("compression".to_string(), name.trim().to_string()),
428                    ("compression_level".to_string(), value.trim().to_string()),
429                ]
430            }
431        });
432    }
433    // A bare compression: `snappy`.
434    Ok(vec![("compression".to_string(), option.to_string())])
435}