use std::fmt::{self, Display};
use std::str::FromStr;
use crate::config::{ConfigField, Visit};
use crate::error::{DataFusionError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DFParquetWriterVersion {
#[default]
V1_0,
V2_0,
}
impl FromStr for DFParquetWriterVersion {
type Err = DataFusionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"1.0" => Ok(DFParquetWriterVersion::V1_0),
"2.0" => Ok(DFParquetWriterVersion::V2_0),
other => Err(DataFusionError::Configuration(format!(
"Invalid parquet writer version: {other}. Expected one of: 1.0, 2.0"
))),
}
}
}
impl Display for DFParquetWriterVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
DFParquetWriterVersion::V1_0 => "1.0",
DFParquetWriterVersion::V2_0 => "2.0",
};
write!(f, "{s}")
}
}
impl ConfigField for DFParquetWriterVersion {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, _: &str, value: &str) -> Result<()> {
*self = DFParquetWriterVersion::from_str(value)?;
Ok(())
}
}
#[cfg(feature = "parquet")]
impl From<DFParquetWriterVersion> for parquet::file::properties::WriterVersion {
fn from(value: DFParquetWriterVersion) -> Self {
match value {
DFParquetWriterVersion::V1_0 => {
parquet::file::properties::WriterVersion::PARQUET_1_0
}
DFParquetWriterVersion::V2_0 => {
parquet::file::properties::WriterVersion::PARQUET_2_0
}
}
}
}
#[cfg(feature = "parquet")]
impl From<parquet::file::properties::WriterVersion> for DFParquetWriterVersion {
fn from(version: parquet::file::properties::WriterVersion) -> Self {
match version {
parquet::file::properties::WriterVersion::PARQUET_1_0 => {
DFParquetWriterVersion::V1_0
}
parquet::file::properties::WriterVersion::PARQUET_2_0 => {
DFParquetWriterVersion::V2_0
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RowGroupRangeAssignment {
#[default]
StartOffset,
Midpoint,
}
impl FromStr for RowGroupRangeAssignment {
type Err = DataFusionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"start_offset" => Ok(Self::StartOffset),
"midpoint" => Ok(Self::Midpoint),
other => Err(DataFusionError::Configuration(format!(
"Invalid parquet row group range assignment: {other}. Expected one of: start_offset, midpoint"
))),
}
}
}
impl Display for RowGroupRangeAssignment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::StartOffset => "start_offset",
Self::Midpoint => "midpoint",
};
f.write_str(s)
}
}
impl RowGroupRangeAssignment {
pub fn from_proto_str(s: &str) -> Result<Self> {
if s.is_empty() {
Ok(Self::default())
} else {
s.parse()
}
}
}
crate::config_field!(RowGroupRangeAssignment, value => RowGroupRangeAssignment::from_str(value)?);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DFParquetStatistics {
None,
Chunk,
Page,
}
impl FromStr for DFParquetStatistics {
type Err = DataFusionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"none" => Ok(Self::None),
"chunk" => Ok(Self::Chunk),
"page" => Ok(Self::Page),
other => Err(DataFusionError::Configuration(format!(
"Invalid parquet statistics setting: {other}. Expected one of: none, chunk, page"
))),
}
}
}
impl Display for DFParquetStatistics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::None => "none",
Self::Chunk => "chunk",
Self::Page => "page",
};
f.write_str(s)
}
}
impl ConfigField for DFParquetStatistics {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.statistics_enabled is a scalar DFParquetStatistics and does not have nested field \"{}\"",
key
);
}
*self = Self::from_str(value)?;
Ok(())
}
}
impl ConfigField for Option<DFParquetStatistics> {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
match self {
Some(statistics) => statistics.visit(v, key, description),
None => v.none(key, description),
}
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.statistics_enabled is a scalar Option<DFParquetStatistics> and does not have nested field \"{}\"",
key
);
}
*self = Some(DFParquetStatistics::from_str(value)?);
Ok(())
}
fn reset(&mut self, key: &str) -> Result<()> {
if key.is_empty() {
*self = None;
Ok(())
} else {
crate::error::_config_err!(
"Config field parquet.statistics_enabled is a scalar Option<DFParquetStatistics> and does not have nested field \"{}\"",
key
)
}
}
}
#[cfg(feature = "parquet")]
impl From<DFParquetStatistics> for parquet::file::properties::EnabledStatistics {
fn from(value: DFParquetStatistics) -> Self {
match value {
DFParquetStatistics::None => Self::None,
DFParquetStatistics::Chunk => Self::Chunk,
DFParquetStatistics::Page => Self::Page,
}
}
}
#[cfg(feature = "parquet")]
impl From<parquet::file::properties::EnabledStatistics> for DFParquetStatistics {
fn from(value: parquet::file::properties::EnabledStatistics) -> Self {
match value {
parquet::file::properties::EnabledStatistics::None => Self::None,
parquet::file::properties::EnabledStatistics::Chunk => Self::Chunk,
parquet::file::properties::EnabledStatistics::Page => Self::Page,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DFParquetEncoding {
Plain,
PlainDictionary,
Rle,
BitPacked,
DeltaBinaryPacked,
DeltaLengthByteArray,
DeltaByteArray,
RleDictionary,
ByteStreamSplit,
Alp,
}
impl FromStr for DFParquetEncoding {
type Err = DataFusionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"plain" => Ok(Self::Plain),
"plain_dictionary" => Ok(Self::PlainDictionary),
"rle" => Ok(Self::Rle),
"bit_packed" => Ok(Self::BitPacked),
"delta_binary_packed" => Ok(Self::DeltaBinaryPacked),
"delta_length_byte_array" => Ok(Self::DeltaLengthByteArray),
"delta_byte_array" => Ok(Self::DeltaByteArray),
"rle_dictionary" => Ok(Self::RleDictionary),
"byte_stream_split" => Ok(Self::ByteStreamSplit),
"alp" => Ok(Self::Alp),
_ => Err(DataFusionError::Configuration(format!(
"Unknown or unsupported parquet encoding: \
{s}. Valid values are: plain, plain_dictionary, rle, \
bit_packed, delta_binary_packed, delta_length_byte_array, \
delta_byte_array, rle_dictionary, byte_stream_split, and alp."
))),
}
}
}
impl Display for DFParquetEncoding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Plain => "plain",
Self::PlainDictionary => "plain_dictionary",
Self::Rle => "rle",
Self::BitPacked => "bit_packed",
Self::DeltaBinaryPacked => "delta_binary_packed",
Self::DeltaLengthByteArray => "delta_length_byte_array",
Self::DeltaByteArray => "delta_byte_array",
Self::RleDictionary => "rle_dictionary",
Self::ByteStreamSplit => "byte_stream_split",
Self::Alp => "alp",
})
}
}
impl ConfigField for Option<DFParquetEncoding> {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
match self {
Some(encoding) => v.some(key, encoding, description),
None => v.none(key, description),
}
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.encoding is a scalar Option<DFParquetEncoding> and does not have nested field \"{}\"",
key
);
}
*self = Some(value.parse()?);
Ok(())
}
fn reset(&mut self, key: &str) -> Result<()> {
if key.is_empty() {
*self = None;
Ok(())
} else {
crate::error::_config_err!(
"Config field parquet.encoding is a scalar Option<DFParquetEncoding> and does not have nested field \"{}\"",
key
)
}
}
}
#[cfg(feature = "parquet")]
impl From<DFParquetEncoding> for parquet::basic::Encoding {
fn from(value: DFParquetEncoding) -> Self {
match value {
DFParquetEncoding::Plain => Self::PLAIN,
DFParquetEncoding::PlainDictionary => Self::PLAIN_DICTIONARY,
DFParquetEncoding::Rle => Self::RLE,
#[expect(deprecated)]
DFParquetEncoding::BitPacked => Self::BIT_PACKED,
DFParquetEncoding::DeltaBinaryPacked => Self::DELTA_BINARY_PACKED,
DFParquetEncoding::DeltaLengthByteArray => Self::DELTA_LENGTH_BYTE_ARRAY,
DFParquetEncoding::DeltaByteArray => Self::DELTA_BYTE_ARRAY,
DFParquetEncoding::RleDictionary => Self::RLE_DICTIONARY,
DFParquetEncoding::ByteStreamSplit => Self::BYTE_STREAM_SPLIT,
DFParquetEncoding::Alp => Self::ALP,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DFParquetCompression {
Uncompressed,
Snappy,
Gzip(u32),
Brotli(u32),
Lz4,
Zstd(u32),
Lz4Raw,
}
pub const GZIP_LEVELS: std::ops::RangeInclusive<u32> = 0..=9;
pub const BROTLI_LEVELS: std::ops::RangeInclusive<u32> = 0..=11;
pub const ZSTD_LEVELS: std::ops::RangeInclusive<u32> = 0..=22;
impl DFParquetCompression {
fn split(setting: &str) -> Result<(&str, Option<u32>)> {
let Some((codec, rest)) = setting.split_once('(') else {
return Ok((setting, None));
};
let level = rest
.strip_suffix(')')
.and_then(|level| level.parse::<u32>().ok())
.ok_or_else(|| {
DataFusionError::Configuration(format!(
"Could not parse compression string. \
Got codec: {codec} and unknown level from {setting}"
))
})?;
Ok((codec, Some(level)))
}
fn without_level(codec: &str, level: Option<u32>) -> Result<()> {
if level.is_some() {
return Err(DataFusionError::Configuration(format!(
"Compression {codec} does not support specifying a level"
)));
}
Ok(())
}
fn level_in(
codec: &str,
level: Option<u32>,
valid: std::ops::RangeInclusive<u32>,
) -> Result<u32> {
let level = level.ok_or_else(|| {
DataFusionError::Configuration(format!(
"{codec} compression requires specifying a level such as {codec}(4)"
))
})?;
if !valid.contains(&level) {
return Err(DataFusionError::Configuration(format!(
"Invalid compression level {level} for {codec}. \
Expected a level between {} and {}",
valid.start(),
valid.end()
)));
}
Ok(level)
}
}
impl FromStr for DFParquetCompression {
type Err = DataFusionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let setting = s.replace('\'', "").to_lowercase();
let (codec, level) = Self::split(&setting)?;
match codec {
"uncompressed" => {
Self::without_level(codec, level)?;
Ok(Self::Uncompressed)
}
"snappy" => {
Self::without_level(codec, level)?;
Ok(Self::Snappy)
}
"gzip" => Ok(Self::Gzip(Self::level_in(codec, level, GZIP_LEVELS)?)),
"brotli" => Ok(Self::Brotli(Self::level_in(codec, level, BROTLI_LEVELS)?)),
"lz4" => {
Self::without_level(codec, level)?;
Ok(Self::Lz4)
}
"zstd" => Ok(Self::Zstd(Self::level_in(codec, level, ZSTD_LEVELS)?)),
"lz4_raw" => {
Self::without_level(codec, level)?;
Ok(Self::Lz4Raw)
}
_ => Err(DataFusionError::Configuration(format!(
"Unknown or unsupported parquet compression: \
{s}. Valid values are: uncompressed, snappy, gzip(level), \
brotli(level), lz4, zstd(level), and lz4_raw."
))),
}
}
}
impl Display for DFParquetCompression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Uncompressed => f.write_str("uncompressed"),
Self::Snappy => f.write_str("snappy"),
Self::Gzip(level) => write!(f, "gzip({level})"),
Self::Brotli(level) => write!(f, "brotli({level})"),
Self::Lz4 => f.write_str("lz4"),
Self::Zstd(level) => write!(f, "zstd({level})"),
Self::Lz4Raw => f.write_str("lz4_raw"),
}
}
}
impl ConfigField for DFParquetCompression {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.compression is a scalar DFParquetCompression and does not have nested field \"{}\"",
key
);
}
*self = Self::from_str(value)?;
Ok(())
}
}
impl ConfigField for Option<DFParquetCompression> {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
match self {
Some(compression) => compression.visit(v, key, description),
None => v.none(key, description),
}
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.compression is a scalar Option<DFParquetCompression> and does not have nested field \"{}\"",
key
);
}
*self = Some(DFParquetCompression::from_str(value)?);
Ok(())
}
fn reset(&mut self, key: &str) -> Result<()> {
if key.is_empty() {
*self = None;
Ok(())
} else {
crate::error::_config_err!(
"Config field parquet.compression is a scalar Option<DFParquetCompression> and does not have nested field \"{}\"",
key
)
}
}
}
#[cfg(feature = "parquet")]
impl From<DFParquetCompression> for parquet::basic::Compression {
fn from(value: DFParquetCompression) -> Self {
use parquet::basic::{BrotliLevel, GzipLevel, ZstdLevel};
match value {
DFParquetCompression::Uncompressed => Self::UNCOMPRESSED,
DFParquetCompression::Snappy => Self::SNAPPY,
DFParquetCompression::Gzip(level) => {
Self::GZIP(GzipLevel::try_new(level).expect("gzip level was validated"))
}
DFParquetCompression::Brotli(level) => Self::BROTLI(
BrotliLevel::try_new(level).expect("brotli level was validated"),
),
DFParquetCompression::Lz4 => Self::LZ4,
DFParquetCompression::Zstd(level) => Self::ZSTD(
ZstdLevel::try_new(level as i32).expect("zstd level was validated"),
),
DFParquetCompression::Lz4Raw => Self::LZ4_RAW,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DFTimeUnit {
Nanosecond,
Microsecond,
Millisecond,
Second,
}
impl FromStr for DFTimeUnit {
type Err = DataFusionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"ns" => Ok(Self::Nanosecond),
"us" => Ok(Self::Microsecond),
"ms" => Ok(Self::Millisecond),
"s" => Ok(Self::Second),
other => Err(DataFusionError::Configuration(format!(
"Invalid parquet coerce_int96 setting: {other}. Expected one of: ns, us, ms, s"
))),
}
}
}
impl Display for DFTimeUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Nanosecond => "ns",
Self::Microsecond => "us",
Self::Millisecond => "ms",
Self::Second => "s",
};
f.write_str(s)
}
}
impl ConfigField for DFTimeUnit {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
v.some(key, self, description)
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.coerce_int96 is a scalar DFTimeUnit and does not have nested field \"{}\"",
key
);
}
*self = Self::from_str(value)?;
Ok(())
}
}
impl ConfigField for Option<DFTimeUnit> {
fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
match self {
Some(time_unit) => time_unit.visit(v, key, description),
None => v.none(key, description),
}
}
fn set(&mut self, key: &str, value: &str) -> Result<()> {
if !key.is_empty() {
return crate::error::_config_err!(
"Config field parquet.coerce_int96 is a scalar Option<DFTimeUnit> and does not have nested field \"{}\"",
key
);
}
*self = Some(DFTimeUnit::from_str(value)?);
Ok(())
}
fn reset(&mut self, key: &str) -> Result<()> {
if key.is_empty() {
*self = None;
Ok(())
} else {
crate::error::_config_err!(
"Config field parquet.coerce_int96 is a scalar Option<DFTimeUnit> and does not have nested field \"{}\"",
key
)
}
}
}
impl From<DFTimeUnit> for arrow::datatypes::TimeUnit {
fn from(value: DFTimeUnit) -> Self {
match value {
DFTimeUnit::Nanosecond => Self::Nanosecond,
DFTimeUnit::Microsecond => Self::Microsecond,
DFTimeUnit::Millisecond => Self::Millisecond,
DFTimeUnit::Second => Self::Second,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "parquet")]
#[test]
fn parquet_encoding_parses_displays_and_converts() {
use parquet::basic::Encoding;
for (input, expected, parquet_encoding) in [
("PLAIN", DFParquetEncoding::Plain, Encoding::PLAIN),
(
"plain_dictionary",
DFParquetEncoding::PlainDictionary,
Encoding::PLAIN_DICTIONARY,
),
("rle", DFParquetEncoding::Rle, Encoding::RLE),
#[expect(deprecated)]
(
"bit_packed",
DFParquetEncoding::BitPacked,
Encoding::BIT_PACKED,
),
(
"delta_binary_packed",
DFParquetEncoding::DeltaBinaryPacked,
Encoding::DELTA_BINARY_PACKED,
),
(
"delta_length_byte_array",
DFParquetEncoding::DeltaLengthByteArray,
Encoding::DELTA_LENGTH_BYTE_ARRAY,
),
(
"delta_byte_array",
DFParquetEncoding::DeltaByteArray,
Encoding::DELTA_BYTE_ARRAY,
),
(
"rle_dictionary",
DFParquetEncoding::RleDictionary,
Encoding::RLE_DICTIONARY,
),
(
"byte_stream_split",
DFParquetEncoding::ByteStreamSplit,
Encoding::BYTE_STREAM_SPLIT,
),
("alp", DFParquetEncoding::Alp, Encoding::ALP),
] {
let parsed: DFParquetEncoding = input.parse().unwrap();
assert_eq!(parsed, expected, "input: {input}");
assert_eq!(parsed.to_string(), input.to_ascii_lowercase());
assert_eq!(Encoding::from(parsed), parquet_encoding);
}
for input in ["", "invalid", "zstd"] {
let err = input.parse::<DFParquetEncoding>().unwrap_err();
assert!(
err.to_string()
.contains("Unknown or unsupported parquet encoding"),
"input {input:?}: {err}"
);
}
}
#[test]
fn parquet_compression_parses_and_displays() {
for (input, expected, displayed) in [
(
"uncompressed",
DFParquetCompression::Uncompressed,
"uncompressed",
),
("SNAPPY", DFParquetCompression::Snappy, "snappy"),
("gzip(6)", DFParquetCompression::Gzip(6), "gzip(6)"),
("Brotli(11)", DFParquetCompression::Brotli(11), "brotli(11)"),
("lz4", DFParquetCompression::Lz4, "lz4"),
("'zstd(3)'", DFParquetCompression::Zstd(3), "zstd(3)"),
("lz4_raw", DFParquetCompression::Lz4Raw, "lz4_raw"),
("zstd(0)", DFParquetCompression::Zstd(0), "zstd(0)"),
] {
let parsed: DFParquetCompression = input.parse().unwrap();
assert_eq!(parsed, expected, "input: {input}");
assert_eq!(parsed.to_string(), displayed, "input: {input}");
assert_eq!(displayed.parse::<DFParquetCompression>().unwrap(), parsed);
}
}
#[test]
fn parquet_compression_rejects_invalid_settings() {
for (input, message) in [
(
"zstdd(3)",
"Unknown or unsupported parquet compression: zstdd(3)",
),
(
"zstd",
"zstd compression requires specifying a level such as zstd(4)",
),
(
"snappy(2)",
"Compression snappy does not support specifying a level",
),
("zstd(x)", "Could not parse compression string"),
("zstd(3", "Could not parse compression string"),
(
"zstd(23)",
"Invalid compression level 23 for zstd. Expected a level between 0 and 22",
),
(
"gzip(10)",
"Invalid compression level 10 for gzip. Expected a level between 0 and 9",
),
("brotli(12)", "Invalid compression level 12 for brotli"),
("", "Unknown or unsupported parquet compression: "),
] {
let err = input
.parse::<DFParquetCompression>()
.unwrap_err()
.to_string();
assert!(err.contains(message), "input {input:?}: {err}");
}
}
#[cfg(feature = "parquet")]
#[test]
fn parquet_compression_level_ranges_match_parquet() {
use parquet::basic::{BrotliLevel, GzipLevel, ZstdLevel};
for level in GZIP_LEVELS {
assert!(GzipLevel::try_new(level).is_ok(), "gzip({level})");
}
assert!(GzipLevel::try_new(GZIP_LEVELS.end() + 1).is_err());
for level in BROTLI_LEVELS {
assert!(BrotliLevel::try_new(level).is_ok(), "brotli({level})");
}
assert!(BrotliLevel::try_new(BROTLI_LEVELS.end() + 1).is_err());
for level in ZSTD_LEVELS {
assert!(ZstdLevel::try_new(level as i32).is_ok(), "zstd({level})");
}
assert!(ZstdLevel::try_new(*ZSTD_LEVELS.end() as i32 + 1).is_err());
}
#[test]
fn time_unit_parses_and_displays() {
for (input, expected, displayed) in [
("ns", DFTimeUnit::Nanosecond, "ns"),
("US", DFTimeUnit::Microsecond, "us"),
("ms", DFTimeUnit::Millisecond, "ms"),
("s", DFTimeUnit::Second, "s"),
] {
let parsed: DFTimeUnit = input.parse().unwrap();
assert_eq!(parsed, expected, "input: {input}");
assert_eq!(parsed.to_string(), displayed);
}
for input in ["nanos", "", "ns "] {
let err = input.parse::<DFTimeUnit>().unwrap_err().to_string();
assert!(
err.contains("Invalid parquet coerce_int96 setting"),
"input {input:?}: {err}"
);
}
}
}