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 const DEFAULT_DICTIONARY_THRESHOLD: f64 = 0.5;
93
94pub fn known_options() -> Vec<(&'static str, bool)> {
96 KNOWN.to_vec()
97}
98
99#[derive(Clone, Debug)]
101pub struct Column {
102 pub name: String,
104 pub distinct: Option<u64>,
106 pub rows: i64,
108}
109
110#[derive(Clone, Debug, Default)]
112pub struct Plan {
113 options: BTreeMap<String, String>,
114}
115
116impl Plan {
117 pub fn new() -> Self {
119 Self::default()
120 }
121
122 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 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 pub fn get(&self, name: &str) -> Option<&str> {
163 self.options.get(name).map(|value| value.as_str())
164 }
165
166 pub fn get_for(&self, name: &str, column: &str) -> Option<&str> {
168 self.get(&format!("{name}.{column}"))
169 }
170
171 pub fn entries(&self) -> impl Iterator<Item = (&String, &String)> {
173 self.options.iter()
174 }
175
176 pub fn needs_distinct(&self) -> bool {
182 self.get("dictionary") != Some("off")
183 }
184
185 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 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 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 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 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 fn level(&self) -> Option<i32> {
348 self.get("compression_level")
349 .and_then(|level| level.parse().ok())
350 }
351}
352
353pub 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
366fn 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
383fn number(value: &str, name: &str) -> Result<usize> {
385 value
386 .parse()
387 .with_context(|| format!("{name} takes a number, not {value}"))
388}
389
390fn decimal(value: &str, name: &str) -> Result<f64> {
392 value
393 .parse()
394 .with_context(|| format!("{name} takes a number, not {value}"))
395}
396
397fn 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
406fn 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
426fn 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
436pub 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 vec![
462 ("compression".to_string(), name.trim().to_string()),
463 ("compression_level".to_string(), value.trim().to_string()),
464 ]
465 }
466 });
467 }
468 Ok(vec![("compression".to_string(), option.to_string())])
470}