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