Skip to main content

datafusion_proto_common/from_proto/
mod.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::collections::HashMap;
6use std::sync::Arc;
7
8use crate::common::proto_error;
9use crate::protobuf_common as protobuf;
10use arrow::array::{ArrayRef, AsArray};
11use arrow::buffer::Buffer;
12use arrow::csv::writer::Terminator;
13use arrow::csv::{QuoteStyle, WriterBuilder};
14use arrow::datatypes::{
15    DataType, Field, IntervalDayTimeType, IntervalMonthDayNanoType, IntervalUnit, Schema,
16    TimeUnit, UnionFields, UnionMode, i256,
17};
18use arrow::ipc::{
19    convert::try_fb_to_schema,
20    reader::{read_dictionary, read_record_batch},
21    root_as_message,
22    writer::{DictionaryTracker, IpcDataGenerator, IpcWriteOptions},
23};
24
25use datafusion_common::{
26    Column, ColumnStatistics, Constraint, Constraints, DFSchema, DFSchemaRef,
27    DataFusionError, JoinSide, ScalarValue, Statistics, TableReference,
28    arrow_datafusion_err,
29    config::{
30        CsvOptions, JsonOptions, MaxRowGroupBytes, ParquetCdcOptions,
31        ParquetColumnOptions, ParquetOptions, TableParquetOptions,
32    },
33    file_options::{csv_writer::CsvWriterOptions, json_writer::JsonWriterOptions},
34    parquet_config::RowGroupRangeAssignment,
35    parsers::CompressionTypeVariant,
36    plan_datafusion_err,
37    stats::Precision,
38    utils::usize_from_wire,
39};
40
41#[derive(Debug)]
42pub enum Error {
43    General(String),
44
45    DataFusionError(DataFusionError),
46
47    MissingRequiredField(String),
48
49    AtLeastOneValue(String),
50
51    UnknownEnumVariant { name: String, value: i32 },
52}
53
54impl std::fmt::Display for Error {
55    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
56        match self {
57            Self::General(desc) => write!(f, "General error: {desc}"),
58
59            Self::DataFusionError(desc) => {
60                write!(f, "DataFusion error: {desc:?}")
61            }
62
63            Self::MissingRequiredField(name) => {
64                write!(f, "Missing required field {name}")
65            }
66            Self::AtLeastOneValue(name) => {
67                write!(f, "Must have at least one {name}, found 0")
68            }
69            Self::UnknownEnumVariant { name, value } => {
70                write!(f, "Unknown i32 value for {name} enum: {value}")
71            }
72        }
73    }
74}
75
76impl std::error::Error for Error {}
77
78impl From<DataFusionError> for Error {
79    fn from(e: DataFusionError) -> Self {
80        Error::DataFusionError(e)
81    }
82}
83
84impl Error {
85    pub fn required(field: impl Into<String>) -> Error {
86        Error::MissingRequiredField(field.into())
87    }
88
89    pub fn unknown(name: impl Into<String>, value: i32) -> Error {
90        Error::UnknownEnumVariant {
91            name: name.into(),
92            value,
93        }
94    }
95}
96
97impl From<Error> for DataFusionError {
98    fn from(e: Error) -> Self {
99        plan_datafusion_err!("{}", e)
100    }
101}
102
103/// An extension trait that adds the methods `optional` and `required` to any
104/// Option containing a type implementing `TryInto<U, Error = Error>`
105pub trait FromOptionalField<T> {
106    /// Converts an optional protobuf field to an option of a different type
107    ///
108    /// Returns None if the option is None, otherwise calls [`TryInto::try_into`]
109    /// on the contained data, returning any error encountered
110    fn optional(self) -> datafusion_common::Result<Option<T>, Error>;
111
112    /// Converts an optional protobuf field to a different type, returning an error if None
113    ///
114    /// Returns `Error::MissingRequiredField` if None, otherwise calls [`TryInto::try_into`]
115    /// on the contained data, returning any error encountered
116    fn required(self, field: impl Into<String>) -> datafusion_common::Result<T, Error>;
117}
118
119impl<T, U> FromOptionalField<U> for Option<T>
120where
121    T: TryInto<U, Error = Error>,
122{
123    fn optional(self) -> datafusion_common::Result<Option<U>, Error> {
124        self.map(|t| t.try_into()).transpose()
125    }
126
127    fn required(self, field: impl Into<String>) -> datafusion_common::Result<U, Error> {
128        match self {
129            None => Err(Error::required(field)),
130            Some(t) => t.try_into(),
131        }
132    }
133}
134
135impl From<protobuf::ColumnRelation> for TableReference {
136    fn from(rel: protobuf::ColumnRelation) -> Self {
137        match rel.parts.as_slice() {
138            [table] => Self::bare(table.as_str()),
139            [schema, table] => Self::partial(schema.as_str(), table.as_str()),
140            [catalog, schema, table] => {
141                Self::full(catalog.as_str(), schema.as_str(), table.as_str())
142            }
143            _ => Self::parse_str_normalized(rel.relation.as_str(), true),
144        }
145    }
146}
147
148impl From<protobuf::Column> for Column {
149    fn from(c: protobuf::Column) -> Self {
150        let protobuf::Column { relation, name } = c;
151
152        Self::new(relation, name)
153    }
154}
155
156impl From<&protobuf::Column> for Column {
157    fn from(c: &protobuf::Column) -> Self {
158        c.clone().into()
159    }
160}
161
162impl TryFrom<&protobuf::DfSchema> for DFSchema {
163    type Error = Error;
164
165    fn try_from(
166        df_schema: &protobuf::DfSchema,
167    ) -> datafusion_common::Result<Self, Self::Error> {
168        let df_fields = df_schema.columns.clone();
169        let qualifiers_and_fields: Vec<(Option<TableReference>, Arc<Field>)> = df_fields
170            .iter()
171            .map(|df_field| {
172                let field: Field = df_field.field.as_ref().required("field")?;
173                Ok((
174                    df_field.qualifier.as_ref().map(|q| q.clone().into()),
175                    Arc::new(field),
176                ))
177            })
178            .collect::<datafusion_common::Result<Vec<_>, Error>>()?;
179
180        Ok(DFSchema::new_with_metadata(
181            qualifiers_and_fields,
182            df_schema.metadata.clone(),
183        )?)
184    }
185}
186
187impl TryFrom<protobuf::DfSchema> for DFSchemaRef {
188    type Error = Error;
189
190    fn try_from(
191        df_schema: protobuf::DfSchema,
192    ) -> datafusion_common::Result<Self, Self::Error> {
193        let dfschema: DFSchema = (&df_schema).try_into()?;
194        Ok(Arc::new(dfschema))
195    }
196}
197
198impl TryFrom<&protobuf::ArrowType> for DataType {
199    type Error = Error;
200
201    fn try_from(
202        arrow_type: &protobuf::ArrowType,
203    ) -> datafusion_common::Result<Self, Self::Error> {
204        arrow_type
205            .arrow_type_enum
206            .as_ref()
207            .required("arrow_type_enum")
208    }
209}
210
211impl TryFrom<&protobuf::arrow_type::ArrowTypeEnum> for DataType {
212    type Error = Error;
213    fn try_from(
214        arrow_type_enum: &protobuf::arrow_type::ArrowTypeEnum,
215    ) -> datafusion_common::Result<Self, Self::Error> {
216        use protobuf::arrow_type;
217        Ok(match arrow_type_enum {
218            arrow_type::ArrowTypeEnum::None(_) => DataType::Null,
219            arrow_type::ArrowTypeEnum::Bool(_) => DataType::Boolean,
220            arrow_type::ArrowTypeEnum::Uint8(_) => DataType::UInt8,
221            arrow_type::ArrowTypeEnum::Int8(_) => DataType::Int8,
222            arrow_type::ArrowTypeEnum::Uint16(_) => DataType::UInt16,
223            arrow_type::ArrowTypeEnum::Int16(_) => DataType::Int16,
224            arrow_type::ArrowTypeEnum::Uint32(_) => DataType::UInt32,
225            arrow_type::ArrowTypeEnum::Int32(_) => DataType::Int32,
226            arrow_type::ArrowTypeEnum::Uint64(_) => DataType::UInt64,
227            arrow_type::ArrowTypeEnum::Int64(_) => DataType::Int64,
228            arrow_type::ArrowTypeEnum::Float16(_) => DataType::Float16,
229            arrow_type::ArrowTypeEnum::Float32(_) => DataType::Float32,
230            arrow_type::ArrowTypeEnum::Float64(_) => DataType::Float64,
231            arrow_type::ArrowTypeEnum::Utf8(_) => DataType::Utf8,
232            arrow_type::ArrowTypeEnum::Utf8View(_) => DataType::Utf8View,
233            arrow_type::ArrowTypeEnum::LargeUtf8(_) => DataType::LargeUtf8,
234            arrow_type::ArrowTypeEnum::Binary(_) => DataType::Binary,
235            arrow_type::ArrowTypeEnum::BinaryView(_) => DataType::BinaryView,
236            arrow_type::ArrowTypeEnum::FixedSizeBinary(size) => {
237                DataType::FixedSizeBinary(*size)
238            }
239            arrow_type::ArrowTypeEnum::LargeBinary(_) => DataType::LargeBinary,
240            arrow_type::ArrowTypeEnum::Date32(_) => DataType::Date32,
241            arrow_type::ArrowTypeEnum::Date64(_) => DataType::Date64,
242            arrow_type::ArrowTypeEnum::Duration(time_unit) => {
243                DataType::Duration(parse_i32_to_time_unit(time_unit)?)
244            }
245            arrow_type::ArrowTypeEnum::Timestamp(protobuf::Timestamp {
246                time_unit,
247                timezone,
248            }) => DataType::Timestamp(
249                parse_i32_to_time_unit(time_unit)?,
250                match timezone.len() {
251                    0 => None,
252                    _ => Some(timezone.as_str().into()),
253                },
254            ),
255            arrow_type::ArrowTypeEnum::Time32(time_unit) => {
256                DataType::Time32(parse_i32_to_time_unit(time_unit)?)
257            }
258            arrow_type::ArrowTypeEnum::Time64(time_unit) => {
259                DataType::Time64(parse_i32_to_time_unit(time_unit)?)
260            }
261            arrow_type::ArrowTypeEnum::Interval(interval_unit) => {
262                DataType::Interval(parse_i32_to_interval_unit(interval_unit)?)
263            }
264            arrow_type::ArrowTypeEnum::Decimal32(protobuf::Decimal32Type {
265                precision,
266                scale,
267            }) => DataType::Decimal32(*precision as u8, *scale as i8),
268            arrow_type::ArrowTypeEnum::Decimal64(protobuf::Decimal64Type {
269                precision,
270                scale,
271            }) => DataType::Decimal64(*precision as u8, *scale as i8),
272            arrow_type::ArrowTypeEnum::Decimal128(protobuf::Decimal128Type {
273                precision,
274                scale,
275            }) => DataType::Decimal128(*precision as u8, *scale as i8),
276            arrow_type::ArrowTypeEnum::Decimal256(protobuf::Decimal256Type {
277                precision,
278                scale,
279            }) => DataType::Decimal256(*precision as u8, *scale as i8),
280            arrow_type::ArrowTypeEnum::List(list) => {
281                let list_type =
282                    list.as_ref().field_type.as_deref().required("field_type")?;
283                DataType::List(Arc::new(list_type))
284            }
285            arrow_type::ArrowTypeEnum::LargeList(list) => {
286                let list_type =
287                    list.as_ref().field_type.as_deref().required("field_type")?;
288                DataType::LargeList(Arc::new(list_type))
289            }
290            arrow_type::ArrowTypeEnum::FixedSizeList(list) => {
291                let list_type =
292                    list.as_ref().field_type.as_deref().required("field_type")?;
293                let list_size = list.list_size;
294                DataType::FixedSizeList(Arc::new(list_type), list_size)
295            }
296            arrow_type::ArrowTypeEnum::ListView(list) => {
297                let list_type =
298                    list.as_ref().field_type.as_deref().required("field_type")?;
299                DataType::ListView(Arc::new(list_type))
300            }
301            arrow_type::ArrowTypeEnum::LargeListView(list) => {
302                let list_type =
303                    list.as_ref().field_type.as_deref().required("field_type")?;
304                DataType::LargeListView(Arc::new(list_type))
305            }
306            arrow_type::ArrowTypeEnum::Struct(strct) => DataType::Struct(
307                parse_proto_fields_to_fields(&strct.sub_field_types)?.into(),
308            ),
309            arrow_type::ArrowTypeEnum::Union(union) => {
310                let union_mode = protobuf::UnionMode::try_from(union.union_mode)
311                    .map_err(|_| Error::unknown("UnionMode", union.union_mode))?;
312                let union_mode = match union_mode {
313                    protobuf::UnionMode::Dense => UnionMode::Dense,
314                    protobuf::UnionMode::Sparse => UnionMode::Sparse,
315                };
316                let union_fields = parse_proto_fields_to_fields(&union.union_types)?;
317
318                // Default to index based type ids if not explicitly provided
319                let union_fields = if union.type_ids.is_empty() {
320                    UnionFields::from_fields(union_fields)
321                } else {
322                    let type_ids = union.type_ids.iter().map(|i| *i as i8);
323                    UnionFields::try_new(type_ids, union_fields).map_err(|e| {
324                        DataFusionError::from(e).context("Deserializing Union DataType")
325                    })?
326                };
327                DataType::Union(union_fields, union_mode)
328            }
329            arrow_type::ArrowTypeEnum::Dictionary(dict) => {
330                let key_datatype = dict.as_ref().key.as_deref().required("key")?;
331                let value_datatype = dict.as_ref().value.as_deref().required("value")?;
332                DataType::Dictionary(Box::new(key_datatype), Box::new(value_datatype))
333            }
334            arrow_type::ArrowTypeEnum::Map(map) => {
335                let field: Field =
336                    map.as_ref().field_type.as_deref().required("field_type")?;
337                let keys_sorted = map.keys_sorted;
338                DataType::Map(Arc::new(field), keys_sorted)
339            }
340            arrow_type::ArrowTypeEnum::RunEndEncoded(run_end_encoded) => {
341                let run_ends_field: Field = run_end_encoded
342                    .as_ref()
343                    .run_ends_field
344                    .as_deref()
345                    .required("run_ends_field")?;
346                let value_field: Field = run_end_encoded
347                    .as_ref()
348                    .values_field
349                    .as_deref()
350                    .required("values_field")?;
351                DataType::RunEndEncoded(run_ends_field.into(), value_field.into())
352            }
353        })
354    }
355}
356
357impl TryFrom<&protobuf::Field> for Field {
358    type Error = Error;
359    fn try_from(field: &protobuf::Field) -> Result<Self, Self::Error> {
360        let datatype = field.arrow_type.as_deref().required("arrow_type")?;
361        let field = Self::new(field.name.as_str(), datatype, field.nullable)
362            .with_metadata(field.metadata.clone());
363        Ok(field)
364    }
365}
366
367impl TryFrom<&protobuf::Schema> for Schema {
368    type Error = Error;
369
370    fn try_from(
371        schema: &protobuf::Schema,
372    ) -> datafusion_common::Result<Self, Self::Error> {
373        let fields = schema
374            .columns
375            .iter()
376            .map(Field::try_from)
377            .collect::<datafusion_common::Result<Vec<_>, _>>()?;
378        Ok(Self::new_with_metadata(fields, schema.metadata.clone()))
379    }
380}
381
382impl TryFrom<&protobuf::ScalarValue> for ScalarValue {
383    type Error = Error;
384
385    fn try_from(
386        scalar: &protobuf::ScalarValue,
387    ) -> datafusion_common::Result<Self, Self::Error> {
388        use protobuf::scalar_value::Value;
389
390        let value = scalar
391            .value
392            .as_ref()
393            .ok_or_else(|| Error::required("value"))?;
394
395        Ok(match value {
396            Value::BoolValue(v) => Self::Boolean(Some(*v)),
397            Value::Utf8Value(v) => Self::Utf8(Some(v.to_owned())),
398            Value::Utf8ViewValue(v) => Self::Utf8View(Some(v.to_owned())),
399            Value::LargeUtf8Value(v) => Self::LargeUtf8(Some(v.to_owned())),
400            Value::Int8Value(v) => Self::Int8(Some(*v as i8)),
401            Value::Int16Value(v) => Self::Int16(Some(*v as i16)),
402            Value::Int32Value(v) => Self::Int32(Some(*v)),
403            Value::Int64Value(v) => Self::Int64(Some(*v)),
404            Value::Uint8Value(v) => Self::UInt8(Some(*v as u8)),
405            Value::Uint16Value(v) => Self::UInt16(Some(*v as u16)),
406            Value::Uint32Value(v) => Self::UInt32(Some(*v)),
407            Value::Uint64Value(v) => Self::UInt64(Some(*v)),
408            Value::Float32Value(v) => Self::Float32(Some(*v)),
409            Value::Float64Value(v) => Self::Float64(Some(*v)),
410            Value::Date32Value(v) => Self::Date32(Some(*v)),
411            // Nested ScalarValue types are serialized using arrow IPC format
412            Value::ListValue(v)
413            | Value::FixedSizeListValue(v)
414            | Value::LargeListValue(v)
415            | Value::ListViewValue(v)
416            | Value::LargeListViewValue(v)
417            | Value::StructValue(v)
418            | Value::MapValue(v) => {
419                let protobuf::ScalarNestedValue {
420                    ipc_message,
421                    arrow_data,
422                    dictionaries,
423                    schema,
424                } = &v;
425
426                let schema: Schema = if let Some(schema_ref) = schema {
427                    schema_ref.try_into()?
428                } else {
429                    return Err(Error::General(
430                        "Invalid schema while deserializing nested ScalarValue"
431                            .to_string(),
432                    ));
433                };
434
435                // IPC dictionary batch IDs are assigned when encoding the schema, but our protobuf
436                // `Schema` doesn't preserve those IDs. Reconstruct them deterministically by
437                // round-tripping the schema through IPC.
438                let schema: Schema = {
439                    let ipc_gen = IpcDataGenerator {};
440                    let write_options = IpcWriteOptions::default();
441                    let mut dict_tracker = DictionaryTracker::new(false);
442                    let encoded_schema = ipc_gen.schema_to_bytes_with_dictionary_tracker(
443                        &schema,
444                        &mut dict_tracker,
445                        &write_options,
446                    );
447                    let message =
448                        root_as_message(encoded_schema.ipc_message.as_slice()).map_err(
449                            |e| {
450                                Error::General(format!(
451                                    "Error IPC schema message while deserializing nested ScalarValue: {e}"
452                                ))
453                            },
454                        )?;
455                    let ipc_schema = message.header_as_schema().ok_or_else(|| {
456                        Error::General(
457                            "Unexpected message type deserializing nested ScalarValue schema"
458                                .to_string(),
459                        )
460                    })?;
461                    try_fb_to_schema(ipc_schema).map_err(|e| {
462                        Error::General(format!(
463                            "Error converting IPC schema while deserializing nested ScalarValue: {e}"
464                        ))
465                    })?
466                };
467
468                let message = root_as_message(ipc_message.as_slice()).map_err(|e| {
469                    Error::General(format!(
470                        "Error IPC message while deserializing nested ScalarValue: {e}"
471                    ))
472                })?;
473                let buffer = Buffer::from(arrow_data.as_slice());
474
475                let ipc_batch = message.header_as_record_batch().ok_or_else(|| {
476                    Error::General(
477                        "Unexpected message type deserializing nested ScalarValue"
478                            .to_string(),
479                    )
480                })?;
481
482                let mut dict_by_id: HashMap<i64, ArrayRef> =
483                    HashMap::with_capacity(dictionaries.len());
484                for protobuf::scalar_nested_value::Dictionary {
485                    ipc_message,
486                    arrow_data,
487                } in dictionaries
488                {
489                    let message = root_as_message(ipc_message.as_slice()).map_err(|e| {
490                        Error::General(format!(
491                            "Error IPC message while deserializing nested ScalarValue dictionary message: {e}"
492                        ))
493                    })?;
494                    let buffer = Buffer::from(arrow_data.as_slice());
495
496                    let dict_batch = message.header_as_dictionary_batch().ok_or_else(|| {
497                        Error::General(
498                            "Unexpected message type deserializing nested ScalarValue dictionary message"
499                                .to_string(),
500                        )
501                    })?;
502                    read_dictionary(
503                        &buffer,
504                        dict_batch,
505                        &schema,
506                        &mut dict_by_id,
507                        &message.version(),
508                    )
509                    .map_err(|e| arrow_datafusion_err!(e))
510                    .map_err(|e| e.context("Decoding nested ScalarValue dictionary"))?;
511                }
512
513                let record_batch = read_record_batch(
514                    &buffer,
515                    ipc_batch,
516                    Arc::new(schema),
517                    &dict_by_id,
518                    None,
519                    &message.version(),
520                )
521                .map_err(|e| arrow_datafusion_err!(e))
522                .map_err(|e| e.context("Decoding nested ScalarValue value"))?;
523                let arr = record_batch.column(0);
524                match value {
525                    Value::ListValue(_) => {
526                        Self::List(arr.as_list::<i32>().to_owned().into())
527                    }
528                    Value::LargeListValue(_) => {
529                        Self::LargeList(arr.as_list::<i64>().to_owned().into())
530                    }
531                    Value::FixedSizeListValue(_) => {
532                        Self::FixedSizeList(arr.as_fixed_size_list().to_owned().into())
533                    }
534                    Value::ListViewValue(_) => {
535                        Self::ListView(arr.as_list_view::<i32>().to_owned().into())
536                    }
537                    Value::LargeListViewValue(_) => {
538                        Self::LargeListView(arr.as_list_view::<i64>().to_owned().into())
539                    }
540                    Value::StructValue(_) => {
541                        Self::Struct(arr.as_struct().to_owned().into())
542                    }
543                    Value::MapValue(_) => Self::Map(arr.as_map().to_owned().into()),
544                    _ => unreachable!(),
545                }
546            }
547            Value::NullValue(v) => {
548                let null_type: DataType = v.try_into()?;
549                null_type.try_into().map_err(Error::DataFusionError)?
550            }
551            Value::Decimal32Value(val) => {
552                let array = vec_to_array(val.value.clone());
553                Self::Decimal32(Some(i32::from_be_bytes(array)), val.p as u8, val.s as i8)
554            }
555            Value::Decimal64Value(val) => {
556                let array = vec_to_array(val.value.clone());
557                Self::Decimal64(Some(i64::from_be_bytes(array)), val.p as u8, val.s as i8)
558            }
559            Value::Decimal128Value(val) => {
560                let array = vec_to_array(val.value.clone());
561                Self::Decimal128(
562                    Some(i128::from_be_bytes(array)),
563                    val.p as u8,
564                    val.s as i8,
565                )
566            }
567            Value::Decimal256Value(val) => {
568                let array = vec_to_array(val.value.clone());
569                Self::Decimal256(
570                    Some(i256::from_be_bytes(array)),
571                    val.p as u8,
572                    val.s as i8,
573                )
574            }
575            Value::Date64Value(v) => Self::Date64(Some(*v)),
576            Value::Time32Value(v) => {
577                let time_value =
578                    v.value.as_ref().ok_or_else(|| Error::required("value"))?;
579                match time_value {
580                    protobuf::scalar_time32_value::Value::Time32SecondValue(t) => {
581                        Self::Time32Second(Some(*t))
582                    }
583                    protobuf::scalar_time32_value::Value::Time32MillisecondValue(t) => {
584                        Self::Time32Millisecond(Some(*t))
585                    }
586                }
587            }
588            Value::Time64Value(v) => {
589                let time_value =
590                    v.value.as_ref().ok_or_else(|| Error::required("value"))?;
591                match time_value {
592                    protobuf::scalar_time64_value::Value::Time64MicrosecondValue(t) => {
593                        Self::Time64Microsecond(Some(*t))
594                    }
595                    protobuf::scalar_time64_value::Value::Time64NanosecondValue(t) => {
596                        Self::Time64Nanosecond(Some(*t))
597                    }
598                }
599            }
600            Value::IntervalYearmonthValue(v) => Self::IntervalYearMonth(Some(*v)),
601            Value::DurationSecondValue(v) => Self::DurationSecond(Some(*v)),
602            Value::DurationMillisecondValue(v) => Self::DurationMillisecond(Some(*v)),
603            Value::DurationMicrosecondValue(v) => Self::DurationMicrosecond(Some(*v)),
604            Value::DurationNanosecondValue(v) => Self::DurationNanosecond(Some(*v)),
605            Value::TimestampValue(v) => {
606                let timezone = if v.timezone.is_empty() {
607                    None
608                } else {
609                    Some(v.timezone.as_str().into())
610                };
611
612                let ts_value =
613                    v.value.as_ref().ok_or_else(|| Error::required("value"))?;
614
615                match ts_value {
616                    protobuf::scalar_timestamp_value::Value::TimeMicrosecondValue(t) => {
617                        Self::TimestampMicrosecond(Some(*t), timezone)
618                    }
619                    protobuf::scalar_timestamp_value::Value::TimeNanosecondValue(t) => {
620                        Self::TimestampNanosecond(Some(*t), timezone)
621                    }
622                    protobuf::scalar_timestamp_value::Value::TimeSecondValue(t) => {
623                        Self::TimestampSecond(Some(*t), timezone)
624                    }
625                    protobuf::scalar_timestamp_value::Value::TimeMillisecondValue(t) => {
626                        Self::TimestampMillisecond(Some(*t), timezone)
627                    }
628                }
629            }
630            Value::DictionaryValue(v) => {
631                let index_type: DataType = v
632                    .index_type
633                    .as_ref()
634                    .ok_or_else(|| Error::required("index_type"))?
635                    .try_into()?;
636
637                let value: Self = v
638                    .value
639                    .as_ref()
640                    .ok_or_else(|| Error::required("value"))?
641                    .as_ref()
642                    .try_into()?;
643
644                Self::Dictionary(Box::new(index_type), Box::new(value))
645            }
646            Value::RunEndEncodedValue(v) => {
647                let run_ends_field: Field = v
648                    .run_ends_field
649                    .as_ref()
650                    .ok_or_else(|| Error::required("run_ends_field"))?
651                    .try_into()?;
652
653                let values_field: Field = v
654                    .values_field
655                    .as_ref()
656                    .ok_or_else(|| Error::required("values_field"))?
657                    .try_into()?;
658
659                let value: Self = v
660                    .value
661                    .as_ref()
662                    .ok_or_else(|| Error::required("value"))?
663                    .as_ref()
664                    .try_into()?;
665
666                Self::RunEndEncoded(
667                    run_ends_field.into(),
668                    values_field.into(),
669                    Box::new(value),
670                )
671            }
672            Value::BinaryValue(v) => Self::Binary(Some(v.clone())),
673            Value::BinaryViewValue(v) => Self::BinaryView(Some(v.clone())),
674            Value::LargeBinaryValue(v) => Self::LargeBinary(Some(v.clone())),
675            Value::IntervalDaytimeValue(v) => Self::IntervalDayTime(Some(
676                IntervalDayTimeType::make_value(v.days, v.milliseconds),
677            )),
678            Value::IntervalMonthDayNano(v) => Self::IntervalMonthDayNano(Some(
679                IntervalMonthDayNanoType::make_value(v.months, v.days, v.nanos),
680            )),
681            Value::UnionValue(val) => {
682                let mode = match val.mode {
683                    0 => UnionMode::Sparse,
684                    1 => UnionMode::Dense,
685                    id => Err(Error::unknown("UnionMode", id))?,
686                };
687                let ids = val
688                    .fields
689                    .iter()
690                    .map(|f| f.field_id as i8)
691                    .collect::<Vec<_>>();
692                let fields = val
693                    .fields
694                    .iter()
695                    .map(|f| f.field.clone())
696                    .collect::<Option<Vec<_>>>();
697                let fields = fields.ok_or_else(|| Error::required("UnionField"))?;
698                let fields = parse_proto_fields_to_fields(&fields)?;
699                let union_fields = UnionFields::try_new(ids, fields).map_err(|e| {
700                    DataFusionError::from(e).context("Deserializing Union ScalarValue")
701                })?;
702                let v_id = val.value_id as i8;
703                let val = match &val.value {
704                    None => None,
705                    Some(val) => {
706                        let val: ScalarValue = val
707                            .as_ref()
708                            .try_into()
709                            .map_err(|_| Error::General("Invalid Scalar".to_string()))?;
710                        Some((v_id, Box::new(val)))
711                    }
712                };
713                Self::Union(val, union_fields, mode)
714            }
715            Value::FixedSizeBinaryValue(v) => {
716                Self::FixedSizeBinary(v.length, Some(v.clone().values))
717            }
718        })
719    }
720}
721
722impl From<protobuf::TimeUnit> for TimeUnit {
723    fn from(time_unit: protobuf::TimeUnit) -> Self {
724        match time_unit {
725            protobuf::TimeUnit::Second => TimeUnit::Second,
726            protobuf::TimeUnit::Millisecond => TimeUnit::Millisecond,
727            protobuf::TimeUnit::Microsecond => TimeUnit::Microsecond,
728            protobuf::TimeUnit::Nanosecond => TimeUnit::Nanosecond,
729        }
730    }
731}
732
733impl From<protobuf::IntervalUnit> for IntervalUnit {
734    fn from(interval_unit: protobuf::IntervalUnit) -> Self {
735        match interval_unit {
736            protobuf::IntervalUnit::YearMonth => IntervalUnit::YearMonth,
737            protobuf::IntervalUnit::DayTime => IntervalUnit::DayTime,
738            protobuf::IntervalUnit::MonthDayNano => IntervalUnit::MonthDayNano,
739        }
740    }
741}
742
743impl TryFrom<protobuf::Constraints> for Constraints {
744    type Error = DataFusionError;
745
746    fn try_from(
747        constraints: protobuf::Constraints,
748    ) -> datafusion_common::Result<Self, Self::Error> {
749        Self::try_from(&constraints)
750    }
751}
752
753impl TryFrom<protobuf::Constraint> for Constraint {
754    type Error = DataFusionError;
755
756    fn try_from(
757        value: protobuf::Constraint,
758    ) -> datafusion_common::Result<Self, Self::Error> {
759        Constraint::try_from(&value)
760    }
761}
762
763impl From<&protobuf::ColumnStats> for ColumnStatistics {
764    fn from(cs: &protobuf::ColumnStats) -> ColumnStatistics {
765        ColumnStatistics {
766            null_count: if let Some(nc) = &cs.null_count {
767                nc.clone().into()
768            } else {
769                Precision::Absent
770            },
771            max_value: if let Some(max) = &cs.max_value {
772                max.clone().into()
773            } else {
774                Precision::Absent
775            },
776            min_value: if let Some(min) = &cs.min_value {
777                min.clone().into()
778            } else {
779                Precision::Absent
780            },
781            sum_value: if let Some(sum) = &cs.sum_value {
782                sum.clone().into()
783            } else {
784                Precision::Absent
785            },
786            distinct_count: if let Some(dc) = &cs.distinct_count {
787                dc.clone().into()
788            } else {
789                Precision::Absent
790            },
791            byte_size: if let Some(sbs) = &cs.byte_size {
792                sbs.clone().into()
793            } else {
794                Precision::Absent
795            },
796        }
797    }
798}
799
800impl From<protobuf::Precision> for Precision<usize> {
801    fn from(s: protobuf::Precision) -> Self {
802        let Ok(precision_type) = s.precision_info.try_into() else {
803            return Precision::Absent;
804        };
805        match precision_type {
806            protobuf::PrecisionInfo::Exact => {
807                if let Some(val) = s.val {
808                    if let Ok(ScalarValue::UInt64(Some(val))) =
809                        ScalarValue::try_from(&val)
810                    {
811                        // A value that does not fit in `usize` decodes as
812                        // unknown rather than a silently truncated statistic.
813                        usize::try_from(val).map_or(Precision::Absent, Precision::Exact)
814                    } else {
815                        Precision::Absent
816                    }
817                } else {
818                    Precision::Absent
819                }
820            }
821            protobuf::PrecisionInfo::Inexact => {
822                if let Some(val) = s.val {
823                    if let Ok(ScalarValue::UInt64(Some(val))) =
824                        ScalarValue::try_from(&val)
825                    {
826                        usize::try_from(val).map_or(Precision::Absent, Precision::Inexact)
827                    } else {
828                        Precision::Absent
829                    }
830                } else {
831                    Precision::Absent
832                }
833            }
834            protobuf::PrecisionInfo::Absent => Precision::Absent,
835        }
836    }
837}
838
839impl From<protobuf::Precision> for Precision<ScalarValue> {
840    fn from(s: protobuf::Precision) -> Self {
841        let Ok(precision_type) = s.precision_info.try_into() else {
842            return Precision::Absent;
843        };
844        match precision_type {
845            protobuf::PrecisionInfo::Exact => {
846                if let Some(val) = s.val {
847                    if let Ok(val) = ScalarValue::try_from(&val) {
848                        Precision::Exact(val)
849                    } else {
850                        Precision::Absent
851                    }
852                } else {
853                    Precision::Absent
854                }
855            }
856            protobuf::PrecisionInfo::Inexact => {
857                if let Some(val) = s.val {
858                    if let Ok(val) = ScalarValue::try_from(&val) {
859                        Precision::Inexact(val)
860                    } else {
861                        Precision::Absent
862                    }
863                } else {
864                    Precision::Absent
865                }
866            }
867            protobuf::PrecisionInfo::Absent => Precision::Absent,
868        }
869    }
870}
871
872impl From<protobuf::JoinSide> for JoinSide {
873    fn from(t: protobuf::JoinSide) -> Self {
874        match t {
875            protobuf::JoinSide::LeftSide => JoinSide::Left,
876            protobuf::JoinSide::RightSide => JoinSide::Right,
877            protobuf::JoinSide::None => JoinSide::None,
878        }
879    }
880}
881
882impl TryFrom<&protobuf::Constraint> for Constraint {
883    type Error = DataFusionError;
884
885    fn try_from(
886        value: &protobuf::Constraint,
887    ) -> datafusion_common::Result<Self, Self::Error> {
888        let decode_indices = |indices: &[u64]| {
889            indices
890                .iter()
891                .map(|&index| usize_from_wire(index, "Constraint", "indices"))
892                .collect::<datafusion_common::Result<Vec<_>>>()
893        };
894        match &value.constraint_mode {
895            Some(protobuf::constraint::ConstraintMode::PrimaryKey(elem)) => {
896                Ok(Constraint::PrimaryKey(decode_indices(&elem.indices)?))
897            }
898            Some(protobuf::constraint::ConstraintMode::Unique(elem)) => {
899                Ok(Constraint::Unique(decode_indices(&elem.indices)?))
900            }
901            None => Err(plan_datafusion_err!(
902                "Constraint: missing required field 'constraint_mode'"
903            )),
904        }
905    }
906}
907
908impl TryFrom<&protobuf::Constraints> for Constraints {
909    type Error = DataFusionError;
910
911    fn try_from(
912        constraints: &protobuf::Constraints,
913    ) -> datafusion_common::Result<Self, Self::Error> {
914        Ok(Constraints::new_unverified(
915            constraints
916                .constraints
917                .iter()
918                .map(Constraint::try_from)
919                .collect::<datafusion_common::Result<Vec<_>>>()?,
920        ))
921    }
922}
923
924impl TryFrom<&protobuf::Statistics> for Statistics {
925    type Error = DataFusionError;
926
927    fn try_from(
928        s: &protobuf::Statistics,
929    ) -> datafusion_common::Result<Self, Self::Error> {
930        // Keep it sync with Statistics::to_proto
931        Ok(Statistics {
932            num_rows: if let Some(nr) = &s.num_rows {
933                nr.clone().into()
934            } else {
935                Precision::Absent
936            },
937            total_byte_size: if let Some(tbs) = &s.total_byte_size {
938                tbs.clone().into()
939            } else {
940                Precision::Absent
941            },
942            // No column statistic (None) is encoded with empty array
943            column_statistics: s.column_stats.iter().map(|s| s.into()).collect(),
944        })
945    }
946}
947
948impl From<protobuf::CompressionTypeVariant> for CompressionTypeVariant {
949    fn from(value: protobuf::CompressionTypeVariant) -> Self {
950        match value {
951            protobuf::CompressionTypeVariant::Gzip => Self::GZIP,
952            protobuf::CompressionTypeVariant::Bzip2 => Self::BZIP2,
953            protobuf::CompressionTypeVariant::Xz => Self::XZ,
954            protobuf::CompressionTypeVariant::Zstd => Self::ZSTD,
955            protobuf::CompressionTypeVariant::Uncompressed => Self::UNCOMPRESSED,
956        }
957    }
958}
959
960impl From<CompressionTypeVariant> for protobuf::CompressionTypeVariant {
961    fn from(value: CompressionTypeVariant) -> Self {
962        match value {
963            CompressionTypeVariant::GZIP => Self::Gzip,
964            CompressionTypeVariant::BZIP2 => Self::Bzip2,
965            CompressionTypeVariant::XZ => Self::Xz,
966            CompressionTypeVariant::ZSTD => Self::Zstd,
967            CompressionTypeVariant::UNCOMPRESSED => Self::Uncompressed,
968        }
969    }
970}
971
972impl From<protobuf::CsvQuoteStyle> for datafusion_common::parsers::CsvQuoteStyle {
973    fn from(value: protobuf::CsvQuoteStyle) -> Self {
974        match value {
975            protobuf::CsvQuoteStyle::Necessary => Self::Necessary,
976            protobuf::CsvQuoteStyle::Always => Self::Always,
977            protobuf::CsvQuoteStyle::NonNumeric => Self::NonNumeric,
978            protobuf::CsvQuoteStyle::Never => Self::Never,
979        }
980    }
981}
982
983impl TryFrom<&protobuf::CsvWriterOptions> for CsvWriterOptions {
984    type Error = DataFusionError;
985
986    fn try_from(
987        opts: &protobuf::CsvWriterOptions,
988    ) -> datafusion_common::Result<Self, Self::Error> {
989        let protobuf::CsvWriterOptions {
990            compression,
991            delimiter,
992            has_header,
993            date_format,
994            datetime_format,
995            timestamp_format,
996            time_format,
997            null_value,
998            quote,
999            escape,
1000            double_quote,
1001            quote_style,
1002            ignore_leading_whitespace,
1003            ignore_trailing_whitespace,
1004            compression_level,
1005            timestamp_tz_format,
1006            terminator,
1007        } = opts;
1008
1009        let mut writer_options = WriterBuilder::new();
1010        if !delimiter.is_empty() {
1011            if let Some(delimiter) = delimiter.chars().next() {
1012                if delimiter.is_ascii() {
1013                    writer_options = writer_options.with_delimiter(delimiter as u8);
1014                } else {
1015                    return Err(proto_error("CSV Delimiter is not ASCII"));
1016                }
1017            } else {
1018                return Err(proto_error("Error parsing CSV Delimiter"));
1019            }
1020        }
1021        if !quote.is_empty() {
1022            if let Some(quote) = quote.chars().next() {
1023                if quote.is_ascii() {
1024                    writer_options = writer_options.with_quote(quote as u8);
1025                } else {
1026                    return Err(proto_error("CSV Quote is not ASCII"));
1027                }
1028            } else {
1029                return Err(proto_error("Error parsing CSV Quote"));
1030            }
1031        }
1032        if !escape.is_empty() {
1033            if let Some(escape) = escape.chars().next() {
1034                if escape.is_ascii() {
1035                    writer_options = writer_options.with_escape(escape as u8);
1036                } else {
1037                    return Err(proto_error("CSV Escape is not ASCII"));
1038                }
1039            } else {
1040                return Err(proto_error("Error parsing CSV Escape"));
1041            }
1042        }
1043        let quote_style = match protobuf::CsvQuoteStyle::try_from(*quote_style) {
1044            Ok(protobuf::CsvQuoteStyle::Always) => QuoteStyle::Always,
1045            Ok(protobuf::CsvQuoteStyle::NonNumeric) => QuoteStyle::NonNumeric,
1046            Ok(protobuf::CsvQuoteStyle::Never) => QuoteStyle::Never,
1047            Ok(protobuf::CsvQuoteStyle::Necessary) => QuoteStyle::Necessary,
1048            _ => {
1049                return Err(proto_error(
1050                    "Unknown quote style, must be one of: 'Always', 'NonNumeric', 'Never', 'Necessary'",
1051                ));
1052            }
1053        };
1054        writer_options = writer_options
1055            .with_header(*has_header)
1056            .with_null(null_value.clone())
1057            .with_double_quote(*double_quote)
1058            .with_quote_style(quote_style)
1059            .with_ignore_leading_whitespace(*ignore_leading_whitespace)
1060            .with_ignore_trailing_whitespace(*ignore_trailing_whitespace);
1061        // Presence-aware: `Some("")` is a valid format distinct from `None`.
1062        if let Some(date_format) = date_format {
1063            writer_options = writer_options.with_date_format(date_format.clone());
1064        }
1065        if let Some(datetime_format) = datetime_format {
1066            writer_options = writer_options.with_datetime_format(datetime_format.clone());
1067        }
1068        if let Some(timestamp_format) = timestamp_format {
1069            writer_options =
1070                writer_options.with_timestamp_format(timestamp_format.clone());
1071        }
1072        if let Some(timestamp_tz_format) = timestamp_tz_format {
1073            writer_options =
1074                writer_options.with_timestamp_tz_format(timestamp_tz_format.clone());
1075        }
1076        if let Some(time_format) = time_format {
1077            writer_options = writer_options.with_time_format(time_format.clone());
1078        }
1079        writer_options = match terminator.as_slice() {
1080            [] => writer_options,
1081            [byte] => writer_options.with_line_terminator(Terminator::Any(*byte)),
1082            [b'\r', b'\n'] => writer_options.with_line_terminator(Terminator::CRLF),
1083            _ => {
1084                return Err(proto_error("CSV line terminator must be one byte or CRLF"));
1085            }
1086        };
1087
1088        let compression = protobuf::CompressionTypeVariant::try_from(*compression)
1089            .unwrap_or_default()
1090            .into();
1091        Ok(CsvWriterOptions {
1092            writer_options,
1093            compression,
1094            compression_level: *compression_level,
1095        })
1096    }
1097}
1098
1099impl TryFrom<&protobuf::JsonWriterOptions> for JsonWriterOptions {
1100    type Error = DataFusionError;
1101
1102    fn try_from(
1103        opts: &protobuf::JsonWriterOptions,
1104    ) -> datafusion_common::Result<Self, Self::Error> {
1105        // Exhaustive destructure: new wire fields must be explicitly restored.
1106        let protobuf::JsonWriterOptions {
1107            compression,
1108            compression_level,
1109        } = opts;
1110        let compression: CompressionTypeVariant =
1111            protobuf::CompressionTypeVariant::try_from(*compression)
1112                .unwrap_or_default()
1113                .into();
1114        Ok(JsonWriterOptions {
1115            compression,
1116            compression_level: *compression_level,
1117        })
1118    }
1119}
1120
1121impl TryFrom<&protobuf::CsvOptions> for CsvOptions {
1122    type Error = DataFusionError;
1123
1124    fn try_from(
1125        proto_opts: &protobuf::CsvOptions,
1126    ) -> datafusion_common::Result<Self, Self::Error> {
1127        Ok(CsvOptions {
1128            has_header: proto_opts.has_header.first().map(|h| *h != 0),
1129            delimiter: proto_opts.delimiter[0],
1130            quote: proto_opts.quote[0],
1131            terminator: proto_opts.terminator.first().copied(),
1132            escape: proto_opts.escape.first().copied(),
1133            double_quote: proto_opts.double_quote.first().map(|h| *h != 0),
1134            newlines_in_values: proto_opts.newlines_in_values.first().map(|h| *h != 0),
1135            compression: proto_opts.compression().into(),
1136            compression_level: proto_opts.compression_level,
1137            schema_infer_max_rec: proto_opts
1138                .schema_infer_max_rec
1139                .map(|v| usize_from_wire(v, "CsvOptions", "schema_infer_max_rec"))
1140                .transpose()?,
1141            date_format: (!proto_opts.date_format.is_empty())
1142                .then(|| proto_opts.date_format.clone()),
1143            datetime_format: (!proto_opts.datetime_format.is_empty())
1144                .then(|| proto_opts.datetime_format.clone()),
1145            timestamp_format: (!proto_opts.timestamp_format.is_empty())
1146                .then(|| proto_opts.timestamp_format.clone()),
1147            timestamp_tz_format: (!proto_opts.timestamp_tz_format.is_empty())
1148                .then(|| proto_opts.timestamp_tz_format.clone()),
1149            time_format: (!proto_opts.time_format.is_empty())
1150                .then(|| proto_opts.time_format.clone()),
1151            null_value: (!proto_opts.null_value.is_empty())
1152                .then(|| proto_opts.null_value.clone()),
1153            null_regex: (!proto_opts.null_regex.is_empty())
1154                .then(|| proto_opts.null_regex.clone()),
1155            comment: proto_opts.comment.first().copied(),
1156            truncated_rows: proto_opts.truncated_rows.first().map(|h| *h != 0),
1157            quote_style: proto_opts.quote_style().into(),
1158            ignore_leading_whitespace: proto_opts
1159                .ignore_leading_whitespace
1160                .first()
1161                .map(|h| *h != 0),
1162            ignore_trailing_whitespace: proto_opts
1163                .ignore_trailing_whitespace
1164                .first()
1165                .map(|h| *h != 0),
1166        })
1167    }
1168}
1169
1170impl TryFrom<&protobuf::ParquetOptions> for ParquetOptions {
1171    type Error = DataFusionError;
1172
1173    fn try_from(
1174        value: &protobuf::ParquetOptions,
1175    ) -> datafusion_common::Result<Self, Self::Error> {
1176        let to_usize =
1177            |value: u64, field: &str| usize_from_wire(value, "ParquetOptions", field);
1178        Ok(ParquetOptions {
1179            enable_page_index: value.enable_page_index,
1180            pruning: value.pruning,
1181            skip_metadata: value.skip_metadata,
1182            metadata_size_hint: value
1183                .metadata_size_hint_opt
1184                .map(|opt| match opt {
1185                    protobuf::parquet_options::MetadataSizeHintOpt::MetadataSizeHint(v) => {
1186                        to_usize(v, "metadata_size_hint")
1187                    }
1188                })
1189                .transpose()?,
1190            pushdown_filters: value.pushdown_filters,
1191            reorder_filters: value.reorder_filters,
1192            force_filter_selections: value.force_filter_selections,
1193            data_pagesize_limit: to_usize(
1194                value.data_pagesize_limit,
1195                "data_pagesize_limit",
1196            )?,
1197            write_batch_size: to_usize(value.write_batch_size, "write_batch_size")?,
1198            writer_version: value.writer_version.parse().map_err(|e| {
1199                DataFusionError::Internal(format!("Failed to parse writer_version: {e}"))
1200            })?,
1201            compression: value.compression_opt.as_ref().map(|opt| match opt {
1202                protobuf::parquet_options::CompressionOpt::Compression(v) => v.parse(),
1203            }).transpose()?,
1204            dictionary_enabled: value.dictionary_enabled_opt.as_ref().map(|protobuf::parquet_options::DictionaryEnabledOpt::DictionaryEnabled(v)| *v),
1205            // Continuing from where we left off in the TryFrom implementation
1206            dictionary_page_size_limit: to_usize(
1207                value.dictionary_page_size_limit,
1208                "dictionary_page_size_limit",
1209            )?,
1210            statistics_enabled: value
1211                .statistics_enabled_opt.as_ref()
1212                .map(|opt| match opt {
1213                    protobuf::parquet_options::StatisticsEnabledOpt::StatisticsEnabled(v) => v.parse(),
1214                })
1215                .transpose()?,
1216            max_row_group_size: to_usize(value.max_row_group_size, "max_row_group_size")?,
1217            max_in_list_size: to_usize(value.max_in_list_size, "max_in_list_size")?,
1218            row_group_range_assignment: RowGroupRangeAssignment::from_proto_str(
1219                &value.row_group_range_assignment,
1220            )?,
1221            created_by: value.created_by.clone(),
1222            column_index_truncate_length: value
1223                .column_index_truncate_length_opt.as_ref()
1224                .map(|opt| match opt {
1225                    protobuf::parquet_options::ColumnIndexTruncateLengthOpt::ColumnIndexTruncateLength(v) => {
1226                        to_usize(*v, "column_index_truncate_length")
1227                    }
1228                })
1229                .transpose()?,
1230            statistics_truncate_length: value
1231                .statistics_truncate_length_opt.as_ref()
1232                .map(|opt| match opt {
1233                    protobuf::parquet_options::StatisticsTruncateLengthOpt::StatisticsTruncateLength(v) => {
1234                        to_usize(*v, "statistics_truncate_length")
1235                    }
1236                })
1237                .transpose()?,
1238            data_page_row_count_limit: to_usize(
1239                value.data_page_row_count_limit,
1240                "data_page_row_count_limit",
1241            )?,
1242            encoding: value
1243                .encoding_opt
1244                .as_ref()
1245                .map(|opt| match opt {
1246                    protobuf::parquet_options::EncodingOpt::Encoding(v) => v.parse(),
1247                })
1248                .transpose()?,
1249            bloom_filter_on_read: value.bloom_filter_on_read,
1250            bloom_filter_on_write: value.bloom_filter_on_write,
1251            bloom_filter_fpp: value.clone()
1252                .bloom_filter_fpp_opt
1253                .map(|opt| match opt {
1254                    protobuf::parquet_options::BloomFilterFppOpt::BloomFilterFpp(v) => Some(v),
1255                })
1256                .unwrap_or(None),
1257            bloom_filter_ndv: value.clone()
1258                .bloom_filter_ndv_opt
1259                .map(|opt| match opt {
1260                    protobuf::parquet_options::BloomFilterNdvOpt::BloomFilterNdv(v) => Some(v),
1261                })
1262                .unwrap_or(None),
1263            allow_single_file_parallelism: value.allow_single_file_parallelism,
1264            maximum_parallel_row_group_writers: to_usize(
1265                value.maximum_parallel_row_group_writers,
1266                "maximum_parallel_row_group_writers",
1267            )?,
1268            maximum_buffered_record_batches_per_stream: to_usize(
1269                value.maximum_buffered_record_batches_per_stream,
1270                "maximum_buffered_record_batches_per_stream",
1271            )?,
1272            schema_force_view_types: value.schema_force_view_types,
1273            binary_as_string: value.binary_as_string,
1274            coerce_int96: value.coerce_int96_opt.as_ref().map(|opt| match opt {
1275                protobuf::parquet_options::CoerceInt96Opt::CoerceInt96(v) => v.parse(),
1276            }).transpose()?,
1277            coerce_int96_tz: value.coerce_int96_tz_opt.as_ref().map(|opt| match opt {
1278                protobuf::parquet_options::CoerceInt96TzOpt::CoerceInt96Tz(v) => v.parse(),
1279            }).transpose()?,
1280            skip_arrow_metadata: value.skip_arrow_metadata,
1281            write_row_group_number_distinct_values: value.write_row_group_number_distinct_values,
1282            max_predicate_cache_size: value.max_predicate_cache_size_opt.map(|opt| match opt {
1283                protobuf::parquet_options::MaxPredicateCacheSizeOpt::MaxPredicateCacheSize(v) => {
1284                    to_usize(v, "max_predicate_cache_size")
1285                }
1286            }).transpose()?,
1287            max_row_group_bytes: value.max_row_group_bytes_opt.map(|opt| match opt {
1288                protobuf::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(v) => {
1289                    MaxRowGroupBytes::try_new(to_usize(v, "max_row_group_bytes")?)
1290                }
1291            }).transpose()?,
1292            content_defined_chunking: value.content_defined_chunking.map(ParquetCdcOptions::try_from).transpose()?.unwrap_or_default(),
1293            enable_rle_to_dictionary: value.enable_rle_to_dictionary,
1294        })
1295    }
1296}
1297
1298impl TryFrom<protobuf::ParquetCdcOptions> for ParquetCdcOptions {
1299    type Error = DataFusionError;
1300
1301    fn try_from(
1302        value: protobuf::ParquetCdcOptions,
1303    ) -> datafusion_common::Result<Self, Self::Error> {
1304        let to_usize =
1305            |value: u64, field: &str| usize_from_wire(value, "ParquetCdcOptions", field);
1306        Ok(ParquetCdcOptions {
1307            enabled: value.enabled,
1308            min_chunk_size: to_usize(value.min_chunk_size, "min_chunk_size")?,
1309            max_chunk_size: to_usize(value.max_chunk_size, "max_chunk_size")?,
1310            norm_level: value.norm_level,
1311        })
1312    }
1313}
1314
1315impl TryFrom<&protobuf::ParquetColumnOptions> for ParquetColumnOptions {
1316    type Error = DataFusionError;
1317    fn try_from(
1318        value: &protobuf::ParquetColumnOptions,
1319    ) -> datafusion_common::Result<Self, Self::Error> {
1320        Ok(ParquetColumnOptions {
1321            compression: value.compression_opt.clone().map(|opt| match opt {
1322                protobuf::parquet_column_options::CompressionOpt::Compression(v) => Some(v),
1323            }).unwrap_or(None),
1324            dictionary_enabled: value.dictionary_enabled_opt.as_ref().map(|protobuf::parquet_column_options::DictionaryEnabledOpt::DictionaryEnabled(v)| *v),
1325            statistics_enabled: value
1326                .statistics_enabled_opt.clone()
1327                .map(|opt| match opt {
1328                    protobuf::parquet_column_options::StatisticsEnabledOpt::StatisticsEnabled(v) => Some(v),
1329                })
1330                .unwrap_or(None),
1331            encoding: value
1332                .encoding_opt.clone()
1333                .map(|opt| match opt {
1334                    protobuf::parquet_column_options::EncodingOpt::Encoding(v) => Some(v),
1335                })
1336                .unwrap_or(None),
1337            bloom_filter_enabled: value.bloom_filter_enabled_opt.map(|opt| match opt {
1338                protobuf::parquet_column_options::BloomFilterEnabledOpt::BloomFilterEnabled(v) => Some(v),
1339            })
1340                .unwrap_or(None),
1341            bloom_filter_fpp: value
1342                .bloom_filter_fpp_opt
1343                .map(|opt| match opt {
1344                    protobuf::parquet_column_options::BloomFilterFppOpt::BloomFilterFpp(v) => Some(v),
1345                })
1346                .unwrap_or(None),
1347            bloom_filter_ndv: value
1348                .bloom_filter_ndv_opt
1349                .map(|opt| match opt {
1350                    protobuf::parquet_column_options::BloomFilterNdvOpt::BloomFilterNdv(v) => Some(v),
1351                })
1352                .unwrap_or(None),
1353        })
1354    }
1355}
1356
1357impl TryFrom<&protobuf::TableParquetOptions> for TableParquetOptions {
1358    type Error = DataFusionError;
1359    fn try_from(
1360        value: &protobuf::TableParquetOptions,
1361    ) -> datafusion_common::Result<Self, Self::Error> {
1362        let mut column_specific_options: HashMap<String, ParquetColumnOptions> =
1363            HashMap::with_capacity(value.column_specific_options.len());
1364        for protobuf::ParquetColumnSpecificOptions {
1365            column_name,
1366            options: maybe_options,
1367        } in &value.column_specific_options
1368        {
1369            if let Some(options) = maybe_options {
1370                column_specific_options.insert(column_name.clone(), options.try_into()?);
1371            }
1372        }
1373        let opts = TableParquetOptions {
1374            global: value
1375                .global
1376                .as_ref()
1377                .map(ParquetOptions::try_from)
1378                .transpose()?
1379                .unwrap_or_default(),
1380            column_specific_options,
1381            ..Default::default()
1382        };
1383        Ok(opts)
1384    }
1385}
1386
1387impl TryFrom<&protobuf::JsonOptions> for JsonOptions {
1388    type Error = DataFusionError;
1389
1390    fn try_from(
1391        proto_opts: &protobuf::JsonOptions,
1392    ) -> datafusion_common::Result<Self, Self::Error> {
1393        let compression: protobuf::CompressionTypeVariant = proto_opts.compression();
1394        Ok(JsonOptions {
1395            compression: compression.into(),
1396            compression_level: proto_opts.compression_level,
1397            schema_infer_max_rec: proto_opts
1398                .schema_infer_max_rec
1399                .map(|v| usize_from_wire(v, "JsonOptions", "schema_infer_max_rec"))
1400                .transpose()?,
1401            newline_delimited: proto_opts.newline_delimited.unwrap_or(true),
1402        })
1403    }
1404}
1405
1406pub fn parse_i32_to_time_unit(value: &i32) -> datafusion_common::Result<TimeUnit, Error> {
1407    protobuf::TimeUnit::try_from(*value)
1408        .map(|t| t.into())
1409        .map_err(|_| Error::unknown("TimeUnit", *value))
1410}
1411
1412pub fn parse_i32_to_interval_unit(
1413    value: &i32,
1414) -> datafusion_common::Result<IntervalUnit, Error> {
1415    protobuf::IntervalUnit::try_from(*value)
1416        .map(|t| t.into())
1417        .map_err(|_| Error::unknown("IntervalUnit", *value))
1418}
1419
1420// panic here because no better way to convert from Vec to Array
1421fn vec_to_array<T, const N: usize>(v: Vec<T>) -> [T; N] {
1422    v.try_into().unwrap_or_else(|v: Vec<T>| {
1423        panic!("Expected a Vec of length {} but it was {}", N, v.len())
1424    })
1425}
1426
1427/// Converts a vector of `protobuf::Field`s to `Arc<arrow::Field>`s.
1428pub fn parse_proto_fields_to_fields<'a, I>(fields: I) -> Result<Vec<Field>, Error>
1429where
1430    I: IntoIterator<Item = &'a protobuf::Field>,
1431{
1432    fields
1433        .into_iter()
1434        .map(Field::try_from)
1435        .collect::<datafusion_common::Result<_, _>>()
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440    use datafusion_common::TableReference;
1441    use datafusion_common::config::{
1442        MaxRowGroupBytes, ParquetCdcOptions, ParquetOptions, TableParquetOptions,
1443    };
1444    use datafusion_common::parquet_config::{
1445        DFParquetCompression, DFParquetEncoding, DFParquetStatistics, DFTimeUnit,
1446        RowGroupRangeAssignment,
1447    };
1448
1449    #[test]
1450    fn constraint_requires_mode() {
1451        let err = datafusion_common::Constraint::try_from(
1452            &crate::protobuf_common::Constraint {
1453                constraint_mode: None,
1454            },
1455        )
1456        .unwrap_err();
1457        assert!(
1458            err.to_string()
1459                .contains("Constraint: missing required field 'constraint_mode'")
1460        );
1461    }
1462
1463    #[test]
1464    fn column_relation_round_trip_preserves_dotted_bare_table() {
1465        let column = datafusion_common::Column::new(
1466            Some(TableReference::bare("has.dot")),
1467            "column",
1468        );
1469
1470        let proto: crate::protobuf_common::Column = (&column).into();
1471        let relation = proto.relation.expect("relation should be present");
1472
1473        assert_eq!(relation.relation, "has.dot");
1474        assert_eq!(relation.parts, vec!["has.dot".to_string()]);
1475
1476        let recovered = TableReference::from(relation);
1477        assert_eq!(recovered, TableReference::bare("has.dot"));
1478    }
1479
1480    #[test]
1481    fn column_relation_round_trip_preserves_dotted_partial_reference() {
1482        let column = datafusion_common::Column::new(
1483            Some(TableReference::partial("my.schema", "table")),
1484            "column",
1485        );
1486
1487        let proto: crate::protobuf_common::Column = (&column).into();
1488        let relation = proto.relation.expect("relation should be present");
1489
1490        assert_eq!(relation.relation, "my.schema.table");
1491        assert_eq!(
1492            relation.parts,
1493            vec!["my.schema".to_string(), "table".to_string()]
1494        );
1495
1496        let recovered = TableReference::from(relation);
1497        assert_eq!(recovered, TableReference::partial("my.schema", "table"));
1498    }
1499
1500    #[test]
1501    fn column_relation_round_trip_preserves_dotted_full_reference() {
1502        let column = datafusion_common::Column::new(
1503            Some(TableReference::full("catalog", "my.schema", "table")),
1504            "column",
1505        );
1506
1507        let proto: crate::protobuf_common::Column = (&column).into();
1508        let relation = proto.relation.expect("relation should be present");
1509
1510        assert_eq!(relation.relation, "catalog.my.schema.table");
1511        assert_eq!(
1512            relation.parts,
1513            vec![
1514                "catalog".to_string(),
1515                "my.schema".to_string(),
1516                "table".to_string()
1517            ]
1518        );
1519
1520        let recovered = TableReference::from(relation);
1521        assert_eq!(
1522            recovered,
1523            TableReference::full("catalog", "my.schema", "table")
1524        );
1525    }
1526
1527    #[test]
1528    fn df_schema_round_trip_preserves_dotted_qualifiers() {
1529        use std::sync::Arc;
1530
1531        use datafusion_common::DFSchema;
1532        use datafusion_common::arrow::datatypes::{DataType, Field};
1533
1534        let schema = DFSchema::new_with_metadata(
1535            vec![
1536                (
1537                    Some(TableReference::partial("my.schema", "table")),
1538                    Arc::new(Field::new("partial_col", DataType::Utf8, true)),
1539                ),
1540                (
1541                    Some(TableReference::full("catalog", "my.schema", "table")),
1542                    Arc::new(Field::new("full_col", DataType::Utf8, true)),
1543                ),
1544            ],
1545            std::collections::HashMap::<String, String>::new(),
1546        )
1547        .unwrap();
1548
1549        let proto: crate::protobuf_common::DfSchema = (&schema).try_into().unwrap();
1550        let recovered = DFSchema::try_from(&proto).unwrap();
1551
1552        let qualifiers = recovered
1553            .iter()
1554            .map(|(qualifier, _)| qualifier.cloned())
1555            .collect::<Vec<_>>();
1556
1557        assert_eq!(
1558            qualifiers,
1559            vec![
1560                Some(TableReference::partial("my.schema", "table")),
1561                Some(TableReference::full("catalog", "my.schema", "table")),
1562            ]
1563        );
1564    }
1565
1566    #[test]
1567    fn column_relation_decodes_legacy_relation() {
1568        let proto = crate::protobuf_common::ColumnRelation {
1569            relation: "schema.table".to_string(),
1570            parts: vec![],
1571        };
1572
1573        let recovered = TableReference::from(proto);
1574
1575        assert_eq!(recovered, TableReference::partial("schema", "table"));
1576    }
1577
1578    #[test]
1579    fn table_parquet_options_defaults_missing_global() {
1580        let recovered = TableParquetOptions::try_from(
1581            &crate::protobuf_common::TableParquetOptions::default(),
1582        )
1583        .expect("missing global should use defaults");
1584
1585        assert_eq!(recovered, TableParquetOptions::default());
1586    }
1587
1588    #[test]
1589    fn table_parquet_options_checks_nested_usize_conversion() {
1590        let proto = crate::protobuf_common::TableParquetOptions {
1591            global: Some(crate::protobuf_common::ParquetOptions {
1592                data_pagesize_limit: u64::MAX,
1593                writer_version: "1.0".to_string(),
1594                ..Default::default()
1595            }),
1596            ..Default::default()
1597        };
1598        let recovered = TableParquetOptions::try_from(&proto);
1599
1600        if usize::BITS >= u64::BITS {
1601            assert_eq!(recovered.unwrap().global.data_pagesize_limit, usize::MAX);
1602        } else {
1603            assert_eq!(
1604                recovered.unwrap_err().strip_backtrace(),
1605                "Error during planning: ParquetOptions: data_pagesize_limit wire value 18446744073709551615 is out of range for usize"
1606            );
1607        }
1608    }
1609
1610    #[test]
1611    fn table_parquet_options_propagates_nested_conversion_error() {
1612        let proto = crate::protobuf_common::TableParquetOptions {
1613            global: Some(crate::protobuf_common::ParquetOptions {
1614                writer_version: "1.0".to_string(),
1615                max_row_group_bytes_opt: Some(
1616                    crate::protobuf_common::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(0),
1617                ),
1618                ..Default::default()
1619            }),
1620            ..Default::default()
1621        };
1622
1623        let err = TableParquetOptions::try_from(&proto).unwrap_err();
1624        assert_eq!(
1625            err.strip_backtrace(),
1626            "Invalid or Unsupported Configuration: max_row_group_bytes must be greater than 0"
1627        );
1628    }
1629
1630    fn parquet_options_proto_round_trip(opts: ParquetOptions) -> ParquetOptions {
1631        let proto: crate::protobuf_common::ParquetOptions =
1632            (&opts).try_into().expect("to_proto");
1633        ParquetOptions::try_from(&proto).expect("from_proto")
1634    }
1635
1636    fn table_parquet_options_proto_round_trip(
1637        opts: TableParquetOptions,
1638    ) -> TableParquetOptions {
1639        let proto: crate::protobuf_common::TableParquetOptions =
1640            (&opts).try_into().expect("to_proto");
1641        TableParquetOptions::try_from(&proto).expect("from_proto")
1642    }
1643
1644    #[test]
1645    fn test_parquet_options_cdc_disabled_round_trip() {
1646        let opts = ParquetOptions::default();
1647        assert!(!opts.content_defined_chunking.enabled);
1648        let recovered = parquet_options_proto_round_trip(opts.clone());
1649        assert_eq!(opts, recovered);
1650    }
1651
1652    #[test]
1653    fn test_parquet_options_coerce_int96_tz_unset_round_trip() {
1654        let opts = ParquetOptions::default();
1655        assert!(opts.coerce_int96_tz.is_none());
1656        let recovered = parquet_options_proto_round_trip(opts.clone());
1657        assert_eq!(recovered.coerce_int96_tz, None);
1658    }
1659
1660    #[test]
1661    fn test_parquet_options_coerce_int96_tz_without_unit_round_trip() {
1662        let opts = ParquetOptions {
1663            coerce_int96_tz: Some("+08".parse().unwrap()),
1664            ..ParquetOptions::default()
1665        };
1666        let recovered = parquet_options_proto_round_trip(opts.clone());
1667        assert_eq!(recovered.coerce_int96, None);
1668        assert_eq!(recovered.coerce_int96_tz, opts.coerce_int96_tz);
1669    }
1670
1671    #[test]
1672    fn test_parquet_options_coerce_int96_tz_set_round_trip() {
1673        let opts = ParquetOptions {
1674            coerce_int96: Some(DFTimeUnit::Microsecond),
1675            coerce_int96_tz: Some("UTC".parse().unwrap()),
1676            ..ParquetOptions::default()
1677        };
1678        let recovered = parquet_options_proto_round_trip(opts.clone());
1679        assert_eq!(recovered.coerce_int96, Some(DFTimeUnit::Microsecond));
1680        assert_eq!(recovered.coerce_int96_tz, opts.coerce_int96_tz);
1681    }
1682
1683    #[test]
1684    fn test_parquet_options_row_group_range_assignment_round_trip() {
1685        let opts = ParquetOptions {
1686            row_group_range_assignment: RowGroupRangeAssignment::Midpoint,
1687            ..ParquetOptions::default()
1688        };
1689        let mut proto: crate::protobuf_common::ParquetOptions =
1690            (&opts).try_into().expect("to_proto");
1691        assert_eq!(ParquetOptions::try_from(&proto).unwrap(), opts);
1692
1693        // Options encoded before the field existed decode with the default
1694        proto.row_group_range_assignment.clear();
1695        assert_eq!(
1696            ParquetOptions::try_from(&proto).unwrap(),
1697            ParquetOptions::default()
1698        );
1699    }
1700
1701    #[test]
1702    fn test_parquet_statistics_round_trip() {
1703        let opts = ParquetOptions {
1704            statistics_enabled: Some(DFParquetStatistics::Chunk),
1705            ..ParquetOptions::default()
1706        };
1707        let recovered = parquet_options_proto_round_trip(opts);
1708        assert_eq!(
1709            recovered.statistics_enabled,
1710            Some(DFParquetStatistics::Chunk)
1711        );
1712    }
1713
1714    #[test]
1715    fn test_parquet_compression_round_trip() {
1716        let opts = ParquetOptions {
1717            compression: Some(DFParquetCompression::Gzip(6)),
1718            ..ParquetOptions::default()
1719        };
1720        let recovered = parquet_options_proto_round_trip(opts);
1721        assert_eq!(recovered.compression, Some(DFParquetCompression::Gzip(6)));
1722    }
1723
1724    #[test]
1725    fn test_parquet_encoding_round_trip() {
1726        for encoding in [
1727            None,
1728            Some(DFParquetEncoding::ByteStreamSplit),
1729            Some(DFParquetEncoding::Alp),
1730        ] {
1731            let opts = ParquetOptions {
1732                encoding,
1733                ..ParquetOptions::default()
1734            };
1735            let recovered = parquet_options_proto_round_trip(opts);
1736            assert_eq!(recovered.encoding, encoding);
1737        }
1738    }
1739
1740    #[test]
1741    fn test_invalid_parquet_encoding_rejected_from_proto() {
1742        let opts = ParquetOptions::default();
1743        let mut proto: crate::protobuf_common::ParquetOptions =
1744            (&opts).try_into().expect("to_proto");
1745        proto.encoding_opt = Some(
1746            crate::protobuf_common::parquet_options::EncodingOpt::Encoding(
1747                "invalid".to_string(),
1748            ),
1749        );
1750
1751        let err = ParquetOptions::try_from(&proto).unwrap_err();
1752        assert!(
1753            err.to_string()
1754                .contains("Unknown or unsupported parquet encoding: invalid"),
1755            "unexpected error: {err}"
1756        );
1757    }
1758
1759    #[test]
1760    fn test_invalid_parquet_compression_rejected_from_proto() {
1761        let opts = ParquetOptions::default();
1762        let mut proto: crate::protobuf_common::ParquetOptions =
1763            (&opts).try_into().expect("to_proto");
1764        proto.compression_opt = Some(
1765            crate::protobuf_common::parquet_options::CompressionOpt::Compression(
1766                "zstd".to_string(),
1767            ),
1768        );
1769
1770        let err = ParquetOptions::try_from(&proto).unwrap_err();
1771        assert!(
1772            err.to_string()
1773                .contains("zstd compression requires specifying a level such as zstd(4)"),
1774            "unexpected error: {err}"
1775        );
1776    }
1777
1778    #[test]
1779    fn test_invalid_parquet_coerce_int96_tz_rejected_from_proto() {
1780        // Rejected even when no coerce_int96 unit is set.
1781        let opts = ParquetOptions::default();
1782        let mut proto: crate::protobuf_common::ParquetOptions =
1783            (&opts).try_into().expect("to_proto");
1784        proto.coerce_int96_tz_opt = Some(
1785            crate::protobuf_common::parquet_options::CoerceInt96TzOpt::CoerceInt96Tz(
1786                "Not/A_Timezone".to_string(),
1787            ),
1788        );
1789
1790        let err = ParquetOptions::try_from(&proto).unwrap_err();
1791        assert!(
1792            err.to_string()
1793                .contains("Invalid time zone: Not/A_Timezone."),
1794            "unexpected error: {err}"
1795        );
1796    }
1797
1798    #[test]
1799    fn test_invalid_parquet_coerce_int96_rejected_from_proto() {
1800        let opts = ParquetOptions::default();
1801        let mut proto: crate::protobuf_common::ParquetOptions =
1802            (&opts).try_into().expect("to_proto");
1803        proto.coerce_int96_opt = Some(
1804            crate::protobuf_common::parquet_options::CoerceInt96Opt::CoerceInt96(
1805                "nanos".to_string(),
1806            ),
1807        );
1808
1809        let err = ParquetOptions::try_from(&proto).unwrap_err();
1810        assert!(
1811            err.to_string().contains(
1812                "Invalid parquet coerce_int96 setting: nanos. Expected one of: ns, us, ms, s"
1813            ),
1814            "unexpected error: {err}"
1815        );
1816    }
1817
1818    #[test]
1819    fn test_invalid_parquet_statistics_rejected_from_proto() {
1820        let opts = ParquetOptions::default();
1821        let mut proto: crate::protobuf_common::ParquetOptions =
1822            (&opts).try_into().expect("to_proto");
1823        proto.statistics_enabled_opt = Some(
1824            crate::protobuf_common::parquet_options::StatisticsEnabledOpt::StatisticsEnabled(
1825                "invalid".to_string(),
1826            ),
1827        );
1828
1829        let err = ParquetOptions::try_from(&proto).unwrap_err();
1830        assert!(
1831            err.to_string().contains(
1832                "Invalid parquet statistics setting: invalid. Expected one of: none, chunk, page"
1833            ),
1834            "unexpected error: {err}"
1835        );
1836    }
1837
1838    #[test]
1839    fn test_parquet_options_max_row_group_bytes_round_trip() {
1840        let opts = ParquetOptions {
1841            max_row_group_bytes: Some(
1842                MaxRowGroupBytes::try_new(64 * 1024 * 1024).unwrap(),
1843            ),
1844            ..ParquetOptions::default()
1845        };
1846        let recovered = parquet_options_proto_round_trip(opts.clone());
1847        assert_eq!(
1848            recovered.max_row_group_bytes.map(|v| v.get()),
1849            Some(64 * 1024 * 1024)
1850        );
1851    }
1852
1853    #[test]
1854    fn test_table_parquet_options_coerce_int96_tz_round_trip() {
1855        let mut opts = TableParquetOptions::default();
1856        opts.global.coerce_int96 = Some(DFTimeUnit::Microsecond);
1857        opts.global.coerce_int96_tz = Some("America/Los_Angeles".parse().unwrap());
1858        let recovered = table_parquet_options_proto_round_trip(opts.clone());
1859        assert_eq!(recovered.global.coerce_int96, Some(DFTimeUnit::Microsecond));
1860        assert_eq!(
1861            recovered.global.coerce_int96_tz,
1862            opts.global.coerce_int96_tz
1863        );
1864    }
1865
1866    #[test]
1867    fn test_parquet_options_cdc_enabled_round_trip() {
1868        let opts = ParquetOptions {
1869            content_defined_chunking: ParquetCdcOptions {
1870                enabled: true,
1871                min_chunk_size: 128 * 1024,
1872                max_chunk_size: 512 * 1024,
1873                norm_level: 2,
1874            },
1875            ..ParquetOptions::default()
1876        };
1877        let recovered = parquet_options_proto_round_trip(opts.clone());
1878        let cdc = recovered.content_defined_chunking;
1879        assert!(cdc.enabled);
1880        assert_eq!(cdc.min_chunk_size, 128 * 1024);
1881        assert_eq!(cdc.max_chunk_size, 512 * 1024);
1882        assert_eq!(cdc.norm_level, 2);
1883    }
1884
1885    #[test]
1886    fn test_parquet_options_cdc_negative_norm_level_round_trip() {
1887        let opts = ParquetOptions {
1888            content_defined_chunking: ParquetCdcOptions {
1889                enabled: true,
1890                norm_level: -3,
1891                ..ParquetCdcOptions::default()
1892            },
1893            ..ParquetOptions::default()
1894        };
1895        let recovered = parquet_options_proto_round_trip(opts);
1896        assert_eq!(recovered.content_defined_chunking.norm_level, -3);
1897    }
1898
1899    #[test]
1900    fn test_table_parquet_options_cdc_round_trip() {
1901        let mut opts = TableParquetOptions::default();
1902        opts.global.content_defined_chunking = ParquetCdcOptions {
1903            enabled: true,
1904            min_chunk_size: 64 * 1024,
1905            max_chunk_size: 2 * 1024 * 1024,
1906            norm_level: -1,
1907        };
1908
1909        let recovered = table_parquet_options_proto_round_trip(opts.clone());
1910        let cdc = recovered.global.content_defined_chunking;
1911        assert!(cdc.enabled);
1912        assert_eq!(cdc.min_chunk_size, 64 * 1024);
1913        assert_eq!(cdc.max_chunk_size, 2 * 1024 * 1024);
1914        assert_eq!(cdc.norm_level, -1);
1915    }
1916
1917    #[test]
1918    fn test_table_parquet_options_cdc_disabled_round_trip() {
1919        let opts = TableParquetOptions::default();
1920        assert!(!opts.global.content_defined_chunking.enabled);
1921        let recovered = table_parquet_options_proto_round_trip(opts.clone());
1922        assert!(!recovered.global.content_defined_chunking.enabled);
1923    }
1924}