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 share of rows that may have a different value before a column's
85/// dictionary stops paying for itself.
86///
87/// This is our approximation of what DuckDB's writer decides on its own (it
88/// keeps a dictionary per page and falls back to plain when the dictionary
89/// grows past the data). A column whose values are all different gains
90/// nothing from a dictionary and pays for it twice: once in the dictionary
91/// itself, once in the indices.
92pub const DEFAULT_DICTIONARY_THRESHOLD: f64 = 0.5;
93
94/// The options we know, and whether we can do them yet.
95pub fn known_options() -> Vec<(&'static str, bool)> {
96    KNOWN.to_vec()
97}
98
99/// One column, as far as a plan is concerned.
100#[derive(Clone, Debug)]
101pub struct Column {
102    /// The column's name.
103    pub name: String,
104    /// How many different values it has, when we know.
105    pub distinct: Option<u64>,
106    /// How many rows the file has.
107    pub rows: i64,
108}
109
110/// A plan: the options for writing a file.
111#[derive(Clone, Debug, Default)]
112pub struct Plan {
113    options: BTreeMap<String, String>,
114}
115
116impl Plan {
117    /// A plan with nothing in it.
118    pub fn new() -> Self {
119        Self::default()
120    }
121
122    /// Set an option. The name is checked, so a typo is an error and not a
123    /// setting that quietly does nothing.
124    pub fn set(&mut self, name: &str, value: &str) -> Result<()> {
125        let name = name.trim().to_lowercase();
126        let (name, column) = match name.split_once('.') {
127            Some((name, column)) => (name.to_string(), Some(column.to_string())),
128            None => (name, None),
129        };
130        let known = KNOWN.iter().find(|(option, _)| *option == name);
131        match known {
132            Some((_, true)) => {}
133            Some((_, false)) => return Err(anyhow!("{name} is a DuckDB option we do not do yet")),
134            None => {
135                return Err(anyhow!(
136                    "unknown option: {name} (the ones we know: {})",
137                    KNOWN
138                        .iter()
139                        .filter(|(_, supported)| *supported)
140                        .map(|(option, _)| *option)
141                        .collect::<Vec<_>>()
142                        .join(", ")
143                ))
144            }
145        }
146        let key = match column {
147            Some(column) => format!("{name}.{column}"),
148            None => name,
149        };
150        self.options.insert(key, value.to_string());
151        Ok(())
152    }
153
154    /// Take the options of another plan on top of this one.
155    pub fn merge(&mut self, other: &Plan) {
156        for (name, value) in &other.options {
157            self.options.insert(name.clone(), value.clone());
158        }
159    }
160
161    /// The value of an option.
162    pub fn get(&self, name: &str) -> Option<&str> {
163        self.options.get(name).map(|value| value.as_str())
164    }
165
166    /// The value of an option for one column.
167    pub fn get_for(&self, name: &str, column: &str) -> Option<&str> {
168        self.get(&format!("{name}.{column}"))
169    }
170
171    /// The options, for printing.
172    pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
173        self.options.iter()
174    }
175
176    /// Whether the plan needs to know how many distinct values each column
177    /// has.
178    ///
179    /// It does whenever the dictionary is not turned off for every column:
180    /// the whole point is to decide per column.
181    pub fn needs_distinct(&self) -> bool {
182        self.get("dictionary") != Some("off")
183    }
184
185    /// Turn the plan into the settings a writer takes.
186    ///
187    /// `columns` is what the plan needs to know about the data: the columns
188    /// and, where we counted them, how many different values they have.
189    pub fn writer_properties(&self, columns: &[Column]) -> Result<WriterProperties> {
190        let mut properties = WriterProperties::builder();
191
192        if let Some(codec) = self.get("compression").or_else(|| self.get("codec")) {
193            properties = properties.set_compression(compression_of(codec, self.level())?);
194        }
195        if let Some(rows) = self.get("row_group_size") {
196            properties =
197                properties.set_max_row_group_row_count(Some(number(rows, "row_group_size")?));
198        }
199        if let Some(bytes) = self.get("row_group_size_bytes") {
200            properties =
201                properties.set_max_row_group_bytes(Some(number(bytes, "row_group_size_bytes")?));
202        }
203        if let Some(size) = self.get("data_page_size_limit") {
204            properties = properties.set_data_page_size_limit(number(size, "data_page_size_limit")?);
205        }
206        if let Some(size) = self.get("dictionary_size_limit") {
207            properties =
208                properties.set_dictionary_page_size_limit(number(size, "dictionary_size_limit")?);
209        }
210        if let Some(on) = self.get("write_bloom_filter") {
211            properties = properties.set_bloom_filter_enabled(on_off(on, "write_bloom_filter")?);
212        }
213        if let Some(ratio) = self.get("bloom_filter_false_positive_ratio") {
214            properties = properties
215                .set_bloom_filter_fpp(decimal(ratio, "bloom_filter_false_positive_ratio")?);
216        }
217        if let Some(on) = self.get("write_page_index") {
218            let on = on_off(on, "write_page_index")?;
219            // The page index is the offset index plus the per-page statistics.
220            properties = properties.set_offset_index_disabled(!on);
221            properties = properties.set_statistics_enabled(if on {
222                EnabledStatistics::Page
223            } else {
224                EnabledStatistics::Chunk
225            });
226        }
227        if let Some(version) = self.get("parquet_version") {
228            properties = properties.set_writer_version(match version.to_lowercase().as_str() {
229                "v1" | "1" | "1.0" => WriterVersion::PARQUET_1_0,
230                "v2" | "2" | "2.0" => WriterVersion::PARQUET_2_0,
231                other => return Err(anyhow!("parquet_version takes v1 or v2, not {other}")),
232            });
233        }
234        if let Some(metadata) = self.get("kv_metadata") {
235            let entries: Vec<KeyValue> = metadata
236                .split(',')
237                .filter(|pair| !pair.is_empty())
238                .filter_map(|pair| {
239                    pair.split_once('=').map(|(key, value)| KeyValue {
240                        key: key.to_string(),
241                        value: Some(value.to_string()),
242                    })
243                })
244                .collect();
245            properties = properties.set_key_value_metadata(Some(entries));
246        }
247        if let Some(encoding) = self.get("encoding") {
248            properties = properties.set_encoding(encoding_of(encoding)?);
249        }
250        if let Some(length) = self.get("statistics_truncate_length") {
251            properties = properties.set_statistics_truncate_length(Some(number(
252                length,
253                "statistics_truncate_length",
254            )?));
255        }
256        if let Some(length) = self.get("column_index_truncate_length") {
257            properties = properties.set_column_index_truncate_length(Some(number(
258                length,
259                "column_index_truncate_length",
260            )?));
261        }
262        if let Some(on) = self.get("write_row_group_number_distinct_values") {
263            properties = properties.set_write_row_group_number_distinct_values(on_off(
264                on,
265                "write_row_group_number_distinct_values",
266            )?);
267        }
268        if let Some(rows) = self.get("data_page_row_count_limit") {
269            properties = properties
270                .set_data_page_row_count_limit(number(rows, "data_page_row_count_limit")?);
271        }
272        if let Some(on) = self.get("write_page_header_statistics") {
273            properties = properties
274                .set_write_page_header_statistics(on_off(on, "write_page_header_statistics")?);
275        }
276        if let Some(count) = self.get("bloom_filter_max_ndv") {
277            properties =
278                properties.set_bloom_filter_max_ndv(number(count, "bloom_filter_max_ndv")? as u64);
279        }
280        if let Some(position) = self.get("bloom_filter_position") {
281            properties =
282                properties.set_bloom_filter_position(match position.to_lowercase().as_str() {
283                    "after-row-group" => BloomFilterPosition::AfterRowGroup,
284                    "end" => BloomFilterPosition::End,
285                    other => {
286                        return Err(anyhow!(
287                            "bloom_filter_position takes after-row-group or end, not {other}"
288                        ))
289                    }
290                });
291        }
292        if let Some(on) = self.get("bloom_filter_for_dictionary_encoded_chunks") {
293            properties = properties.set_bloom_filter_for_dictionary_encoded_chunks(on_off(
294                on,
295                "bloom_filter_for_dictionary_encoded_chunks",
296            )?);
297        }
298        if let Some(name) = self.get("created_by") {
299            properties = properties.set_created_by(name.to_string());
300        }
301        if let Some(on) = self.get("dictionary") {
302            properties = properties.set_dictionary_enabled(on_off(on, "dictionary")?);
303        }
304
305        // The per-column knobs: a column's own setting wins over the global one.
306        for column in columns {
307            let path = ColumnPath::from(column.name.clone());
308            if let Some(codec) = self.get_for("compression", &column.name) {
309                properties = properties
310                    .set_column_compression(path.clone(), compression_of(codec, self.level())?);
311            }
312            if let Some(encoding) = self.get_for("encoding", &column.name) {
313                properties = properties.set_column_encoding(path.clone(), encoding_of(encoding)?);
314            }
315            if let Some(on) = self.get_for("dictionary", &column.name) {
316                properties = properties
317                    .set_column_dictionary_enabled(path.clone(), on_off(on, "dictionary")?);
318            }
319        }
320
321        // Our own: the dictionary only pays when the values repeat. The
322        // threshold is the share of rows that may have a different value; a
323        // column above it is written without a dictionary.
324        //
325        // This is on by default: a writer that always uses a dictionary makes
326        // a column of distinct values bigger, not smaller.
327        let threshold = match self.get("dictionary_compression_ratio_threshold") {
328            Some(value) => decimal(value, "dictionary_compression_ratio_threshold")?,
329            None => DEFAULT_DICTIONARY_THRESHOLD,
330        };
331        for column in columns {
332            if column.distinct.is_none() {
333                // We do not know how many different values it has, so we do
334                // not touch it.
335                continue;
336            }
337            properties = properties.set_column_dictionary_enabled(
338                ColumnPath::from(column.name.clone()),
339                dictionary_pays(column, threshold),
340            );
341        }
342
343        Ok(properties.build())
344    }
345
346    /// The compression level, if the plan has one.
347    fn level(&self) -> Option<i32> {
348        self.get("compression_level")
349            .and_then(|level| level.parse().ok())
350    }
351}
352
353/// How many different values each column of a batch has.
354pub fn distinct_of_batch(batch: &arrow_array::RecordBatch) -> Vec<usize> {
355    let mut sets: Vec<std::collections::HashSet<String>> = Vec::new();
356    for column in batch.columns() {
357        let mut set = std::collections::HashSet::new();
358        for row in 0..batch.num_rows() {
359            set.insert(crate::value::cell(column, row).to_string());
360        }
361        sets.push(set);
362    }
363    sets.iter().map(|set| set.len()).collect()
364}
365
366/// Whether a column's dictionary pays for itself.
367///
368/// The dictionary has to hold every different value, and every row still needs
369/// an index into it. So the dictionary pays when the values repeat: the
370/// threshold is the share of rows that may have a different value.
371fn dictionary_pays(column: &Column, threshold: f64) -> bool {
372    match column.distinct {
373        Some(distinct) => {
374            if column.rows <= 0 {
375                return true;
376            }
377            (distinct as f64) / (column.rows as f64) <= threshold
378        }
379        None => true,
380    }
381}
382
383/// Read a number.
384fn number(value: &str, name: &str) -> Result<usize> {
385    value
386        .parse()
387        .with_context(|| format!("{name} takes a number, not {value}"))
388}
389
390/// Read a decimal number.
391fn decimal(value: &str, name: &str) -> Result<f64> {
392    value
393        .parse()
394        .with_context(|| format!("{name} takes a number, not {value}"))
395}
396
397/// Read an on or off.
398fn on_off(value: &str, name: &str) -> Result<bool> {
399    match value.to_lowercase().as_str() {
400        "on" | "true" | "yes" | "1" => Ok(true),
401        "off" | "false" | "no" | "0" => Ok(false),
402        other => Err(anyhow!("{name} takes on or off, not {other}")),
403    }
404}
405
406/// Read a compression, with the level the plan gives.
407fn compression_of(name: &str, level: Option<i32>) -> Result<Compression> {
408    let level = level.unwrap_or(1);
409    match name.to_lowercase().as_str() {
410        "snappy" => Ok(Compression::SNAPPY),
411        "none" | "uncompressed" => Ok(Compression::UNCOMPRESSED),
412        "lz4" | "lz4_raw" => Ok(Compression::LZ4_RAW),
413        "gzip" => Ok(Compression::GZIP(parquet::basic::GzipLevel::try_new(
414            level.max(1) as u32,
415        )?)),
416        "brotli" => Ok(Compression::BROTLI(parquet::basic::BrotliLevel::try_new(
417            level.max(1) as u32,
418        )?)),
419        "zstd" => Ok(Compression::ZSTD(parquet::basic::ZstdLevel::try_new(
420            level,
421        )?)),
422        other => Err(anyhow!("unknown compression: {other}")),
423    }
424}
425
426/// Read an encoding.
427fn encoding_of(name: &str) -> Result<Encoding> {
428    match name.to_lowercase().as_str() {
429        "plain" => Ok(Encoding::PLAIN),
430        "delta" | "delta_binary_packed" => Ok(Encoding::DELTA_BINARY_PACKED),
431        "delta-length-bytes" => Ok(Encoding::DELTA_LENGTH_BYTE_ARRAY),
432        other => Err(anyhow!("unknown encoding: {other}")),
433    }
434}
435
436/// Read one option the user gave, in either DuckDB's spelling or the short
437/// one.
438///
439/// DuckDB's spelling is `name=value` (`compression=zstd`). The short one is
440/// `name:value` (`zstd:19`), which is what the command line is nicer with.
441pub fn parse_option(option: &str) -> Result<Vec<(String, String)>> {
442    let option = option.trim();
443    if let Some((name, value)) = option.split_once('=') {
444        return Ok(vec![(name.trim().to_string(), value.trim().to_string())]);
445    }
446    if let Some((name, value)) = option.split_once(':') {
447        return Ok(match name.to_lowercase().as_str() {
448            "row-group" | "row_group" | "rowgroup" => {
449                vec![("row_group_size".to_string(), value.trim().to_string())]
450            }
451            "page-size" | "page_size" => {
452                vec![("data_page_size_limit".to_string(), value.trim().to_string())]
453            }
454            "dictionary" => vec![("dictionary".to_string(), value.trim().to_string())],
455            "encoding" => vec![("encoding".to_string(), value.trim().to_string())],
456            "data-page" | "data_page" => {
457                vec![("parquet_version".to_string(), value.trim().to_string())]
458            }
459            _ => {
460                // A compression with its level: `zstd:19`.
461                vec![
462                    ("compression".to_string(), name.trim().to_string()),
463                    ("compression_level".to_string(), value.trim().to_string()),
464                ]
465            }
466        });
467    }
468    // A bare compression: `snappy`.
469    Ok(vec![("compression".to_string(), option.to_string())])
470}