1use 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
16const 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 ("dictionary_compression_ratio_threshold", true),
43 ("dictionary", true),
45 ("encoding", true),
47];
48
49pub fn known_options() -> Vec<(&'static str, bool)> {
51 KNOWN.to_vec()
52}
53
54#[derive(Clone, Debug)]
56pub struct Column {
57 pub name: String,
59 pub distinct: Option<u64>,
61 pub rows: i64,
63}
64
65#[derive(Clone, Debug, Default)]
67pub struct Plan {
68 options: BTreeMap<String, String>,
69}
70
71impl Plan {
72 pub fn new() -> Self {
74 Self::default()
75 }
76
77 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 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 pub fn get(&self, name: &str) -> Option<&str> {
118 self.options.get(name).map(|value| value.as_str())
119 }
120
121 pub fn get_for(&self, name: &str, column: &str) -> Option<&str> {
123 self.get(&format!("{name}.{column}"))
124 }
125
126 pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
128 self.options.iter()
129 }
130
131 pub fn needs_distinct(&self) -> bool {
134 self.get("dictionary_compression_ratio_threshold").is_some()
135 }
136
137 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 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 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 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 fn level(&self) -> Option<i32> {
240 self.get("compression_level")
241 .and_then(|level| level.parse().ok())
242 }
243}
244
245fn 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
262fn number(value: &str, name: &str) -> Result<usize> {
264 value
265 .parse()
266 .with_context(|| format!("{name} takes a number, not {value}"))
267}
268
269fn decimal(value: &str, name: &str) -> Result<f64> {
271 value
272 .parse()
273 .with_context(|| format!("{name} takes a number, not {value}"))
274}
275
276fn 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
285fn 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
305fn 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
315pub 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 vec![
341 ("compression".to_string(), name.trim().to_string()),
342 ("compression_level".to_string(), value.trim().to_string()),
343 ]
344 }
345 });
346 }
347 Ok(vec![("compression".to_string(), option.to_string())])
349}