1use 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
18const 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 ("dictionary_compression_ratio_threshold", true),
45 ("dictionary", true),
47 ("encoding", true),
49 ("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
62pub 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
84pub fn known_options() -> Vec<(&'static str, bool)> {
86 KNOWN.to_vec()
87}
88
89#[derive(Clone, Debug)]
91pub struct Column {
92 pub name: String,
94 pub distinct: Option<u64>,
96 pub rows: i64,
98}
99
100#[derive(Clone, Debug, Default)]
102pub struct Plan {
103 options: BTreeMap<String, String>,
104}
105
106impl Plan {
107 pub fn new() -> Self {
109 Self::default()
110 }
111
112 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 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 pub fn get(&self, name: &str) -> Option<&str> {
153 self.options.get(name).map(|value| value.as_str())
154 }
155
156 pub fn get_for(&self, name: &str, column: &str) -> Option<&str> {
158 self.get(&format!("{name}.{column}"))
159 }
160
161 pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
163 self.options.iter()
164 }
165
166 pub fn needs_distinct(&self) -> bool {
169 self.get("dictionary_compression_ratio_threshold").is_some()
170 }
171
172 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 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 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 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 fn level(&self) -> Option<i32> {
326 self.get("compression_level")
327 .and_then(|level| level.parse().ok())
328 }
329}
330
331fn 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
348fn number(value: &str, name: &str) -> Result<usize> {
350 value
351 .parse()
352 .with_context(|| format!("{name} takes a number, not {value}"))
353}
354
355fn decimal(value: &str, name: &str) -> Result<f64> {
357 value
358 .parse()
359 .with_context(|| format!("{name} takes a number, not {value}"))
360}
361
362fn 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
371fn 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
391fn 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
401pub 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 vec![
427 ("compression".to_string(), name.trim().to_string()),
428 ("compression_level".to_string(), value.trim().to_string()),
429 ]
430 }
431 });
432 }
433 Ok(vec![("compression".to_string(), option.to_string())])
435}