Skip to main content

datafusion_common/
parquet_config.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::fmt::{self, Display};
6use std::str::FromStr;
7
8use crate::config::{ConfigField, Visit};
9use crate::error::{DataFusionError, Result};
10
11/// Parquet writer version options for controlling the Parquet file format version
12///
13/// This enum validates parquet writer version values at configuration time,
14/// ensuring only valid versions ("1.0" or "2.0") can be set via `SET` commands
15/// or proto deserialization.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum DFParquetWriterVersion {
18    /// Parquet format version 1.0
19    #[default]
20    V1_0,
21    /// Parquet format version 2.0
22    V2_0,
23}
24
25/// Implement parsing strings to `DFParquetWriterVersion`
26impl FromStr for DFParquetWriterVersion {
27    type Err = DataFusionError;
28
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        match s.to_lowercase().as_str() {
31            "1.0" => Ok(DFParquetWriterVersion::V1_0),
32            "2.0" => Ok(DFParquetWriterVersion::V2_0),
33            other => Err(DataFusionError::Configuration(format!(
34                "Invalid parquet writer version: {other}. Expected one of: 1.0, 2.0"
35            ))),
36        }
37    }
38}
39
40impl Display for DFParquetWriterVersion {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        let s = match self {
43            DFParquetWriterVersion::V1_0 => "1.0",
44            DFParquetWriterVersion::V2_0 => "2.0",
45        };
46        write!(f, "{s}")
47    }
48}
49
50impl ConfigField for DFParquetWriterVersion {
51    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
52        v.some(key, self, description)
53    }
54
55    fn set(&mut self, _: &str, value: &str) -> Result<()> {
56        *self = DFParquetWriterVersion::from_str(value)?;
57        Ok(())
58    }
59}
60
61/// Convert `DFParquetWriterVersion` to parquet crate's `WriterVersion`
62///
63/// This conversion is infallible since `DFParquetWriterVersion` only contains
64/// valid values that have been validated at configuration time.
65#[cfg(feature = "parquet")]
66impl From<DFParquetWriterVersion> for parquet::file::properties::WriterVersion {
67    fn from(value: DFParquetWriterVersion) -> Self {
68        match value {
69            DFParquetWriterVersion::V1_0 => {
70                parquet::file::properties::WriterVersion::PARQUET_1_0
71            }
72            DFParquetWriterVersion::V2_0 => {
73                parquet::file::properties::WriterVersion::PARQUET_2_0
74            }
75        }
76    }
77}
78
79/// Convert parquet crate's `WriterVersion` to `DFParquetWriterVersion`
80///
81/// This is used when converting from existing parquet writer properties,
82/// such as when reading from proto or test code.
83#[cfg(feature = "parquet")]
84impl From<parquet::file::properties::WriterVersion> for DFParquetWriterVersion {
85    fn from(version: parquet::file::properties::WriterVersion) -> Self {
86        match version {
87            parquet::file::properties::WriterVersion::PARQUET_1_0 => {
88                DFParquetWriterVersion::V1_0
89            }
90            parquet::file::properties::WriterVersion::PARQUET_2_0 => {
91                DFParquetWriterVersion::V2_0
92            }
93        }
94    }
95}
96
97/// Which byte range of a split Parquet file reads each row group
98///
99/// Each row group maps to one offset, so ranges that cover a file read every
100/// row group exactly once.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
102pub enum RowGroupRangeAssignment {
103    /// The start of the row group's first column chunk
104    #[default]
105    StartOffset,
106    /// That start plus half of the row group's compressed size, as parquet-java
107    /// (and therefore Spark) computes it
108    Midpoint,
109}
110
111impl FromStr for RowGroupRangeAssignment {
112    type Err = DataFusionError;
113
114    fn from_str(s: &str) -> Result<Self, Self::Err> {
115        match s.to_lowercase().as_str() {
116            "start_offset" => Ok(Self::StartOffset),
117            "midpoint" => Ok(Self::Midpoint),
118            other => Err(DataFusionError::Configuration(format!(
119                "Invalid parquet row group range assignment: {other}. Expected one of: start_offset, midpoint"
120            ))),
121        }
122    }
123}
124
125impl Display for RowGroupRangeAssignment {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        let s = match self {
128            Self::StartOffset => "start_offset",
129            Self::Midpoint => "midpoint",
130        };
131        f.write_str(s)
132    }
133}
134
135impl RowGroupRangeAssignment {
136    /// Parses the protobuf form, where an empty string (options encoded before
137    /// this setting existed) means the default
138    pub fn from_proto_str(s: &str) -> Result<Self> {
139        if s.is_empty() {
140            Ok(Self::default())
141        } else {
142            s.parse()
143        }
144    }
145}
146
147crate::config_field!(RowGroupRangeAssignment, value => RowGroupRangeAssignment::from_str(value)?);
148
149/// Parquet statistics levels supported by the writer
150///
151/// This enum validates statistics settings at configuration time, ensuring only
152/// `none`, `chunk`, or `page` can be set via `SET` commands or deserialization.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum DFParquetStatistics {
155    /// Do not write statistics
156    None,
157    /// Write chunk-level statistics
158    Chunk,
159    /// Write page-level statistics
160    Page,
161}
162
163impl FromStr for DFParquetStatistics {
164    type Err = DataFusionError;
165
166    fn from_str(s: &str) -> Result<Self, Self::Err> {
167        match s.to_lowercase().as_str() {
168            "none" => Ok(Self::None),
169            "chunk" => Ok(Self::Chunk),
170            "page" => Ok(Self::Page),
171            other => Err(DataFusionError::Configuration(format!(
172                "Invalid parquet statistics setting: {other}. Expected one of: none, chunk, page"
173            ))),
174        }
175    }
176}
177
178impl Display for DFParquetStatistics {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        let s = match self {
181            Self::None => "none",
182            Self::Chunk => "chunk",
183            Self::Page => "page",
184        };
185        f.write_str(s)
186    }
187}
188
189impl ConfigField for DFParquetStatistics {
190    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
191        v.some(key, self, description)
192    }
193
194    fn set(&mut self, key: &str, value: &str) -> Result<()> {
195        if !key.is_empty() {
196            return crate::error::_config_err!(
197                "Config field parquet.statistics_enabled is a scalar DFParquetStatistics and does not have nested field \"{}\"",
198                key
199            );
200        }
201
202        *self = Self::from_str(value)?;
203        Ok(())
204    }
205}
206
207/// `ConfigField` for `Option<DFParquetStatistics>` parses before assigning so
208/// an invalid value does not turn an unset option into the default.
209impl ConfigField for Option<DFParquetStatistics> {
210    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
211        match self {
212            Some(statistics) => statistics.visit(v, key, description),
213            None => v.none(key, description),
214        }
215    }
216
217    fn set(&mut self, key: &str, value: &str) -> Result<()> {
218        if !key.is_empty() {
219            return crate::error::_config_err!(
220                "Config field parquet.statistics_enabled is a scalar Option<DFParquetStatistics> and does not have nested field \"{}\"",
221                key
222            );
223        }
224
225        *self = Some(DFParquetStatistics::from_str(value)?);
226        Ok(())
227    }
228
229    fn reset(&mut self, key: &str) -> Result<()> {
230        if key.is_empty() {
231            *self = None;
232            Ok(())
233        } else {
234            crate::error::_config_err!(
235                "Config field parquet.statistics_enabled is a scalar Option<DFParquetStatistics> and does not have nested field \"{}\"",
236                key
237            )
238        }
239    }
240}
241
242#[cfg(feature = "parquet")]
243impl From<DFParquetStatistics> for parquet::file::properties::EnabledStatistics {
244    fn from(value: DFParquetStatistics) -> Self {
245        match value {
246            DFParquetStatistics::None => Self::None,
247            DFParquetStatistics::Chunk => Self::Chunk,
248            DFParquetStatistics::Page => Self::Page,
249        }
250    }
251}
252
253#[cfg(feature = "parquet")]
254impl From<parquet::file::properties::EnabledStatistics> for DFParquetStatistics {
255    fn from(value: parquet::file::properties::EnabledStatistics) -> Self {
256        match value {
257            parquet::file::properties::EnabledStatistics::None => Self::None,
258            parquet::file::properties::EnabledStatistics::Chunk => Self::Chunk,
259            parquet::file::properties::EnabledStatistics::Page => Self::Page,
260        }
261    }
262}
263
264/// Parquet encodings accepted by the writer.
265///
266/// Parsing the encoding when it is configured rejects unsupported values before
267/// a Parquet write begins.
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub enum DFParquetEncoding {
270    /// Plain encoding
271    Plain,
272    /// Deprecated plain dictionary encoding
273    PlainDictionary,
274    /// Run-length encoding
275    Rle,
276    /// Deprecated bit-packed encoding
277    BitPacked,
278    /// Delta encoding for integers
279    DeltaBinaryPacked,
280    /// Delta length encoding for byte arrays
281    DeltaLengthByteArray,
282    /// Delta encoding for byte arrays
283    DeltaByteArray,
284    /// Run-length dictionary encoding
285    RleDictionary,
286    /// Byte stream split encoding
287    ByteStreamSplit,
288    /// Adaptive Lossless Floating-Point Encoding
289    Alp,
290}
291
292impl FromStr for DFParquetEncoding {
293    type Err = DataFusionError;
294
295    fn from_str(s: &str) -> Result<Self, Self::Err> {
296        match s.to_ascii_lowercase().as_str() {
297            "plain" => Ok(Self::Plain),
298            "plain_dictionary" => Ok(Self::PlainDictionary),
299            "rle" => Ok(Self::Rle),
300            "bit_packed" => Ok(Self::BitPacked),
301            "delta_binary_packed" => Ok(Self::DeltaBinaryPacked),
302            "delta_length_byte_array" => Ok(Self::DeltaLengthByteArray),
303            "delta_byte_array" => Ok(Self::DeltaByteArray),
304            "rle_dictionary" => Ok(Self::RleDictionary),
305            "byte_stream_split" => Ok(Self::ByteStreamSplit),
306            "alp" => Ok(Self::Alp),
307            _ => Err(DataFusionError::Configuration(format!(
308                "Unknown or unsupported parquet encoding: \
309                {s}. Valid values are: plain, plain_dictionary, rle, \
310                bit_packed, delta_binary_packed, delta_length_byte_array, \
311                delta_byte_array, rle_dictionary, byte_stream_split, and alp."
312            ))),
313        }
314    }
315}
316
317impl Display for DFParquetEncoding {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        f.write_str(match self {
320            Self::Plain => "plain",
321            Self::PlainDictionary => "plain_dictionary",
322            Self::Rle => "rle",
323            Self::BitPacked => "bit_packed",
324            Self::DeltaBinaryPacked => "delta_binary_packed",
325            Self::DeltaLengthByteArray => "delta_length_byte_array",
326            Self::DeltaByteArray => "delta_byte_array",
327            Self::RleDictionary => "rle_dictionary",
328            Self::ByteStreamSplit => "byte_stream_split",
329            Self::Alp => "alp",
330        })
331    }
332}
333
334impl ConfigField for Option<DFParquetEncoding> {
335    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
336        match self {
337            Some(encoding) => v.some(key, encoding, description),
338            None => v.none(key, description),
339        }
340    }
341
342    fn set(&mut self, key: &str, value: &str) -> Result<()> {
343        if !key.is_empty() {
344            return crate::error::_config_err!(
345                "Config field parquet.encoding is a scalar Option<DFParquetEncoding> and does not have nested field \"{}\"",
346                key
347            );
348        }
349
350        *self = Some(value.parse()?);
351        Ok(())
352    }
353
354    fn reset(&mut self, key: &str) -> Result<()> {
355        if key.is_empty() {
356            *self = None;
357            Ok(())
358        } else {
359            crate::error::_config_err!(
360                "Config field parquet.encoding is a scalar Option<DFParquetEncoding> and does not have nested field \"{}\"",
361                key
362            )
363        }
364    }
365}
366
367#[cfg(feature = "parquet")]
368impl From<DFParquetEncoding> for parquet::basic::Encoding {
369    fn from(value: DFParquetEncoding) -> Self {
370        match value {
371            DFParquetEncoding::Plain => Self::PLAIN,
372            DFParquetEncoding::PlainDictionary => Self::PLAIN_DICTIONARY,
373            DFParquetEncoding::Rle => Self::RLE,
374            #[expect(deprecated)]
375            DFParquetEncoding::BitPacked => Self::BIT_PACKED,
376            DFParquetEncoding::DeltaBinaryPacked => Self::DELTA_BINARY_PACKED,
377            DFParquetEncoding::DeltaLengthByteArray => Self::DELTA_LENGTH_BYTE_ARRAY,
378            DFParquetEncoding::DeltaByteArray => Self::DELTA_BYTE_ARRAY,
379            DFParquetEncoding::RleDictionary => Self::RLE_DICTIONARY,
380            DFParquetEncoding::ByteStreamSplit => Self::BYTE_STREAM_SPLIT,
381            DFParquetEncoding::Alp => Self::ALP,
382        }
383    }
384}
385
386/// Parquet compression codec, with a level for the codecs that take one
387///
388/// This enum validates compression settings at configuration time. An unknown
389/// codec, a level on a codec that does not take one, a missing level on a codec
390/// that requires one, or a level out of range is rejected by `SET` and by
391/// deserialization instead of when the first file is written.
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub enum DFParquetCompression {
394    /// No compression
395    Uncompressed,
396    /// Snappy
397    Snappy,
398    /// Gzip with a level from [`GZIP_LEVELS`]
399    Gzip(u32),
400    /// Brotli with a level from [`BROTLI_LEVELS`]
401    Brotli(u32),
402    /// LZ4 (Hadoop framed)
403    Lz4,
404    /// Zstd with a level from [`ZSTD_LEVELS`]
405    Zstd(u32),
406    /// LZ4 raw block format
407    Lz4Raw,
408}
409
410/// Valid gzip levels, the same range as `parquet::basic::GzipLevel`
411pub const GZIP_LEVELS: std::ops::RangeInclusive<u32> = 0..=9;
412/// Valid brotli levels, the same range as `parquet::basic::BrotliLevel`
413pub const BROTLI_LEVELS: std::ops::RangeInclusive<u32> = 0..=11;
414/// Valid zstd levels. `parquet::basic::ZstdLevel` also accepts negative levels,
415/// which the string form of this setting has never allowed.
416pub const ZSTD_LEVELS: std::ops::RangeInclusive<u32> = 0..=22;
417
418impl DFParquetCompression {
419    /// Splits `gzip(2)` into `("gzip", Some(2))` and `snappy` into `("snappy", None)`
420    fn split(setting: &str) -> Result<(&str, Option<u32>)> {
421        let Some((codec, rest)) = setting.split_once('(') else {
422            return Ok((setting, None));
423        };
424        let level = rest
425            .strip_suffix(')')
426            .and_then(|level| level.parse::<u32>().ok())
427            .ok_or_else(|| {
428                DataFusionError::Configuration(format!(
429                    "Could not parse compression string. \
430                    Got codec: {codec} and unknown level from {setting}"
431                ))
432            })?;
433        Ok((codec, Some(level)))
434    }
435
436    fn without_level(codec: &str, level: Option<u32>) -> Result<()> {
437        if level.is_some() {
438            return Err(DataFusionError::Configuration(format!(
439                "Compression {codec} does not support specifying a level"
440            )));
441        }
442        Ok(())
443    }
444
445    fn level_in(
446        codec: &str,
447        level: Option<u32>,
448        valid: std::ops::RangeInclusive<u32>,
449    ) -> Result<u32> {
450        let level = level.ok_or_else(|| {
451            DataFusionError::Configuration(format!(
452                "{codec} compression requires specifying a level such as {codec}(4)"
453            ))
454        })?;
455        if !valid.contains(&level) {
456            return Err(DataFusionError::Configuration(format!(
457                "Invalid compression level {level} for {codec}. \
458                Expected a level between {} and {}",
459                valid.start(),
460                valid.end()
461            )));
462        }
463        Ok(level)
464    }
465}
466
467impl FromStr for DFParquetCompression {
468    type Err = DataFusionError;
469
470    fn from_str(s: &str) -> Result<Self, Self::Err> {
471        // ignore string literal chars passed from sqlparser i.e. remove single quotes
472        let setting = s.replace('\'', "").to_lowercase();
473        let (codec, level) = Self::split(&setting)?;
474        match codec {
475            "uncompressed" => {
476                Self::without_level(codec, level)?;
477                Ok(Self::Uncompressed)
478            }
479            "snappy" => {
480                Self::without_level(codec, level)?;
481                Ok(Self::Snappy)
482            }
483            "gzip" => Ok(Self::Gzip(Self::level_in(codec, level, GZIP_LEVELS)?)),
484            "brotli" => Ok(Self::Brotli(Self::level_in(codec, level, BROTLI_LEVELS)?)),
485            "lz4" => {
486                Self::without_level(codec, level)?;
487                Ok(Self::Lz4)
488            }
489            "zstd" => Ok(Self::Zstd(Self::level_in(codec, level, ZSTD_LEVELS)?)),
490            "lz4_raw" => {
491                Self::without_level(codec, level)?;
492                Ok(Self::Lz4Raw)
493            }
494            _ => Err(DataFusionError::Configuration(format!(
495                "Unknown or unsupported parquet compression: \
496                {s}. Valid values are: uncompressed, snappy, gzip(level), \
497                brotli(level), lz4, zstd(level), and lz4_raw."
498            ))),
499        }
500    }
501}
502
503impl Display for DFParquetCompression {
504    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505        match self {
506            Self::Uncompressed => f.write_str("uncompressed"),
507            Self::Snappy => f.write_str("snappy"),
508            Self::Gzip(level) => write!(f, "gzip({level})"),
509            Self::Brotli(level) => write!(f, "brotli({level})"),
510            Self::Lz4 => f.write_str("lz4"),
511            Self::Zstd(level) => write!(f, "zstd({level})"),
512            Self::Lz4Raw => f.write_str("lz4_raw"),
513        }
514    }
515}
516
517impl ConfigField for DFParquetCompression {
518    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
519        v.some(key, self, description)
520    }
521
522    fn set(&mut self, key: &str, value: &str) -> Result<()> {
523        if !key.is_empty() {
524            return crate::error::_config_err!(
525                "Config field parquet.compression is a scalar DFParquetCompression and does not have nested field \"{}\"",
526                key
527            );
528        }
529
530        *self = Self::from_str(value)?;
531        Ok(())
532    }
533}
534
535/// `ConfigField` for `Option<DFParquetCompression>` parses before assigning so
536/// an invalid value does not turn an unset option into the default.
537impl ConfigField for Option<DFParquetCompression> {
538    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
539        match self {
540            Some(compression) => compression.visit(v, key, description),
541            None => v.none(key, description),
542        }
543    }
544
545    fn set(&mut self, key: &str, value: &str) -> Result<()> {
546        if !key.is_empty() {
547            return crate::error::_config_err!(
548                "Config field parquet.compression is a scalar Option<DFParquetCompression> and does not have nested field \"{}\"",
549                key
550            );
551        }
552
553        *self = Some(DFParquetCompression::from_str(value)?);
554        Ok(())
555    }
556
557    fn reset(&mut self, key: &str) -> Result<()> {
558        if key.is_empty() {
559            *self = None;
560            Ok(())
561        } else {
562            crate::error::_config_err!(
563                "Config field parquet.compression is a scalar Option<DFParquetCompression> and does not have nested field \"{}\"",
564                key
565            )
566        }
567    }
568}
569
570#[cfg(feature = "parquet")]
571impl From<DFParquetCompression> for parquet::basic::Compression {
572    fn from(value: DFParquetCompression) -> Self {
573        use parquet::basic::{BrotliLevel, GzipLevel, ZstdLevel};
574        // The levels were checked against the same ranges when the value was parsed.
575        match value {
576            DFParquetCompression::Uncompressed => Self::UNCOMPRESSED,
577            DFParquetCompression::Snappy => Self::SNAPPY,
578            DFParquetCompression::Gzip(level) => {
579                Self::GZIP(GzipLevel::try_new(level).expect("gzip level was validated"))
580            }
581            DFParquetCompression::Brotli(level) => Self::BROTLI(
582                BrotliLevel::try_new(level).expect("brotli level was validated"),
583            ),
584            DFParquetCompression::Lz4 => Self::LZ4,
585            DFParquetCompression::Zstd(level) => Self::ZSTD(
586                ZstdLevel::try_new(level as i32).expect("zstd level was validated"),
587            ),
588            DFParquetCompression::Lz4Raw => Self::LZ4_RAW,
589        }
590    }
591}
592
593/// Time unit for reading Parquet INT96 timestamps
594///
595/// This enum validates `coerce_int96` at configuration time, so only `ns`,
596/// `us`, `ms` or `s` can be set via `SET` commands or deserialization.
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
598pub enum DFTimeUnit {
599    Nanosecond,
600    Microsecond,
601    Millisecond,
602    Second,
603}
604
605impl FromStr for DFTimeUnit {
606    type Err = DataFusionError;
607
608    fn from_str(s: &str) -> Result<Self, Self::Err> {
609        match s.to_lowercase().as_str() {
610            "ns" => Ok(Self::Nanosecond),
611            "us" => Ok(Self::Microsecond),
612            "ms" => Ok(Self::Millisecond),
613            "s" => Ok(Self::Second),
614            other => Err(DataFusionError::Configuration(format!(
615                "Invalid parquet coerce_int96 setting: {other}. Expected one of: ns, us, ms, s"
616            ))),
617        }
618    }
619}
620
621impl Display for DFTimeUnit {
622    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623        let s = match self {
624            Self::Nanosecond => "ns",
625            Self::Microsecond => "us",
626            Self::Millisecond => "ms",
627            Self::Second => "s",
628        };
629        f.write_str(s)
630    }
631}
632
633impl ConfigField for DFTimeUnit {
634    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
635        v.some(key, self, description)
636    }
637
638    fn set(&mut self, key: &str, value: &str) -> Result<()> {
639        if !key.is_empty() {
640            return crate::error::_config_err!(
641                "Config field parquet.coerce_int96 is a scalar DFTimeUnit and does not have nested field \"{}\"",
642                key
643            );
644        }
645
646        *self = Self::from_str(value)?;
647        Ok(())
648    }
649}
650
651/// `ConfigField` for `Option<DFTimeUnit>` parses before assigning so an
652/// invalid value does not turn an unset option into the default.
653impl ConfigField for Option<DFTimeUnit> {
654    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
655        match self {
656            Some(time_unit) => time_unit.visit(v, key, description),
657            None => v.none(key, description),
658        }
659    }
660
661    fn set(&mut self, key: &str, value: &str) -> Result<()> {
662        if !key.is_empty() {
663            return crate::error::_config_err!(
664                "Config field parquet.coerce_int96 is a scalar Option<DFTimeUnit> and does not have nested field \"{}\"",
665                key
666            );
667        }
668
669        *self = Some(DFTimeUnit::from_str(value)?);
670        Ok(())
671    }
672
673    fn reset(&mut self, key: &str) -> Result<()> {
674        if key.is_empty() {
675            *self = None;
676            Ok(())
677        } else {
678            crate::error::_config_err!(
679                "Config field parquet.coerce_int96 is a scalar Option<DFTimeUnit> and does not have nested field \"{}\"",
680                key
681            )
682        }
683    }
684}
685
686impl From<DFTimeUnit> for arrow::datatypes::TimeUnit {
687    fn from(value: DFTimeUnit) -> Self {
688        match value {
689            DFTimeUnit::Nanosecond => Self::Nanosecond,
690            DFTimeUnit::Microsecond => Self::Microsecond,
691            DFTimeUnit::Millisecond => Self::Millisecond,
692            DFTimeUnit::Second => Self::Second,
693        }
694    }
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700
701    #[cfg(feature = "parquet")]
702    #[test]
703    fn parquet_encoding_parses_displays_and_converts() {
704        use parquet::basic::Encoding;
705
706        for (input, expected, parquet_encoding) in [
707            ("PLAIN", DFParquetEncoding::Plain, Encoding::PLAIN),
708            (
709                "plain_dictionary",
710                DFParquetEncoding::PlainDictionary,
711                Encoding::PLAIN_DICTIONARY,
712            ),
713            ("rle", DFParquetEncoding::Rle, Encoding::RLE),
714            #[expect(deprecated)]
715            (
716                "bit_packed",
717                DFParquetEncoding::BitPacked,
718                Encoding::BIT_PACKED,
719            ),
720            (
721                "delta_binary_packed",
722                DFParquetEncoding::DeltaBinaryPacked,
723                Encoding::DELTA_BINARY_PACKED,
724            ),
725            (
726                "delta_length_byte_array",
727                DFParquetEncoding::DeltaLengthByteArray,
728                Encoding::DELTA_LENGTH_BYTE_ARRAY,
729            ),
730            (
731                "delta_byte_array",
732                DFParquetEncoding::DeltaByteArray,
733                Encoding::DELTA_BYTE_ARRAY,
734            ),
735            (
736                "rle_dictionary",
737                DFParquetEncoding::RleDictionary,
738                Encoding::RLE_DICTIONARY,
739            ),
740            (
741                "byte_stream_split",
742                DFParquetEncoding::ByteStreamSplit,
743                Encoding::BYTE_STREAM_SPLIT,
744            ),
745            ("alp", DFParquetEncoding::Alp, Encoding::ALP),
746        ] {
747            let parsed: DFParquetEncoding = input.parse().unwrap();
748            assert_eq!(parsed, expected, "input: {input}");
749            assert_eq!(parsed.to_string(), input.to_ascii_lowercase());
750            assert_eq!(Encoding::from(parsed), parquet_encoding);
751        }
752
753        for input in ["", "invalid", "zstd"] {
754            let err = input.parse::<DFParquetEncoding>().unwrap_err();
755            assert!(
756                err.to_string()
757                    .contains("Unknown or unsupported parquet encoding"),
758                "input {input:?}: {err}"
759            );
760        }
761    }
762
763    #[test]
764    fn parquet_compression_parses_and_displays() {
765        for (input, expected, displayed) in [
766            (
767                "uncompressed",
768                DFParquetCompression::Uncompressed,
769                "uncompressed",
770            ),
771            ("SNAPPY", DFParquetCompression::Snappy, "snappy"),
772            ("gzip(6)", DFParquetCompression::Gzip(6), "gzip(6)"),
773            ("Brotli(11)", DFParquetCompression::Brotli(11), "brotli(11)"),
774            ("lz4", DFParquetCompression::Lz4, "lz4"),
775            ("'zstd(3)'", DFParquetCompression::Zstd(3), "zstd(3)"),
776            ("lz4_raw", DFParquetCompression::Lz4Raw, "lz4_raw"),
777            ("zstd(0)", DFParquetCompression::Zstd(0), "zstd(0)"),
778        ] {
779            let parsed: DFParquetCompression = input.parse().unwrap();
780            assert_eq!(parsed, expected, "input: {input}");
781            assert_eq!(parsed.to_string(), displayed, "input: {input}");
782            assert_eq!(displayed.parse::<DFParquetCompression>().unwrap(), parsed);
783        }
784    }
785
786    #[test]
787    fn parquet_compression_rejects_invalid_settings() {
788        for (input, message) in [
789            (
790                "zstdd(3)",
791                "Unknown or unsupported parquet compression: zstdd(3)",
792            ),
793            (
794                "zstd",
795                "zstd compression requires specifying a level such as zstd(4)",
796            ),
797            (
798                "snappy(2)",
799                "Compression snappy does not support specifying a level",
800            ),
801            ("zstd(x)", "Could not parse compression string"),
802            ("zstd(3", "Could not parse compression string"),
803            (
804                "zstd(23)",
805                "Invalid compression level 23 for zstd. Expected a level between 0 and 22",
806            ),
807            (
808                "gzip(10)",
809                "Invalid compression level 10 for gzip. Expected a level between 0 and 9",
810            ),
811            ("brotli(12)", "Invalid compression level 12 for brotli"),
812            ("", "Unknown or unsupported parquet compression: "),
813        ] {
814            let err = input
815                .parse::<DFParquetCompression>()
816                .unwrap_err()
817                .to_string();
818            assert!(err.contains(message), "input {input:?}: {err}");
819        }
820    }
821
822    /// The level ranges above must stay equal to the ones parquet enforces, or
823    /// the infallible conversion would panic on a level parquet rejects.
824    #[cfg(feature = "parquet")]
825    #[test]
826    fn parquet_compression_level_ranges_match_parquet() {
827        use parquet::basic::{BrotliLevel, GzipLevel, ZstdLevel};
828
829        for level in GZIP_LEVELS {
830            assert!(GzipLevel::try_new(level).is_ok(), "gzip({level})");
831        }
832        assert!(GzipLevel::try_new(GZIP_LEVELS.end() + 1).is_err());
833
834        for level in BROTLI_LEVELS {
835            assert!(BrotliLevel::try_new(level).is_ok(), "brotli({level})");
836        }
837        assert!(BrotliLevel::try_new(BROTLI_LEVELS.end() + 1).is_err());
838
839        for level in ZSTD_LEVELS {
840            assert!(ZstdLevel::try_new(level as i32).is_ok(), "zstd({level})");
841        }
842        assert!(ZstdLevel::try_new(*ZSTD_LEVELS.end() as i32 + 1).is_err());
843    }
844
845    #[test]
846    fn time_unit_parses_and_displays() {
847        for (input, expected, displayed) in [
848            ("ns", DFTimeUnit::Nanosecond, "ns"),
849            ("US", DFTimeUnit::Microsecond, "us"),
850            ("ms", DFTimeUnit::Millisecond, "ms"),
851            ("s", DFTimeUnit::Second, "s"),
852        ] {
853            let parsed: DFTimeUnit = input.parse().unwrap();
854            assert_eq!(parsed, expected, "input: {input}");
855            assert_eq!(parsed.to_string(), displayed);
856        }
857        for input in ["nanos", "", "ns "] {
858            let err = input.parse::<DFTimeUnit>().unwrap_err().to_string();
859            assert!(
860                err.contains("Invalid parquet coerce_int96 setting"),
861                "input {input:?}: {err}"
862            );
863        }
864    }
865}