Skip to main content

datafusion_proto_common/to_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::protobuf_common as protobuf;
9use crate::protobuf_common::{
10    EmptyMessage, arrow_type::ArrowTypeEnum, scalar_value::Value,
11};
12use arrow::array::{ArrayRef, RecordBatch};
13use arrow::csv::QuoteStyle;
14use arrow::csv::writer::Terminator;
15use arrow::datatypes::{
16    DataType, Field, IntervalDayTimeType, IntervalMonthDayNanoType, IntervalUnit, Schema,
17    SchemaRef, TimeUnit, UnionMode,
18};
19use arrow::ipc::writer::{
20    DictionaryTracker, IpcDataGenerator, IpcWriteContext, IpcWriteOptions,
21};
22use datafusion_common::parsers::CsvQuoteStyle;
23use datafusion_common::{
24    Column, ColumnStatistics, Constraint, Constraints, DFSchema, DFSchemaRef,
25    DataFusionError, JoinSide, ScalarValue, Statistics,
26    config::{
27        CsvOptions, JsonOptions, ParquetCdcOptions, ParquetColumnOptions, ParquetOptions,
28        TableParquetOptions,
29    },
30    file_options::{csv_writer::CsvWriterOptions, json_writer::JsonWriterOptions},
31    parsers::CompressionTypeVariant,
32    plan_datafusion_err,
33    stats::Precision,
34};
35
36#[derive(Debug)]
37pub enum Error {
38    General(String),
39
40    InvalidScalarValue(ScalarValue),
41
42    InvalidScalarType(DataType),
43
44    InvalidTimeUnit(TimeUnit),
45
46    NotImplemented(String),
47}
48
49impl std::error::Error for Error {}
50
51impl std::fmt::Display for Error {
52    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
53        match self {
54            Self::General(desc) => write!(f, "General error: {desc}"),
55            Self::InvalidScalarValue(value) => {
56                write!(f, "{value:?} is invalid as a DataFusion scalar value")
57            }
58            Self::InvalidScalarType(data_type) => {
59                write!(f, "{data_type} is invalid as a DataFusion scalar type")
60            }
61            Self::InvalidTimeUnit(time_unit) => {
62                write!(
63                    f,
64                    "Only TimeUnit::Microsecond and TimeUnit::Nanosecond are valid time units, found: {time_unit:?}"
65                )
66            }
67            Self::NotImplemented(s) => {
68                write!(f, "Not implemented: {s}")
69            }
70        }
71    }
72}
73
74impl From<Error> for DataFusionError {
75    fn from(e: Error) -> Self {
76        plan_datafusion_err!("{}", e)
77    }
78}
79
80impl TryFrom<&Field> for protobuf::Field {
81    type Error = Error;
82
83    fn try_from(field: &Field) -> Result<Self, Self::Error> {
84        let arrow_type = field.data_type().try_into()?;
85        Ok(Self {
86            name: field.name().to_owned(),
87            arrow_type: Some(Box::new(arrow_type)),
88            nullable: field.is_nullable(),
89            children: Vec::new(),
90            metadata: field.metadata().into(),
91        })
92    }
93}
94
95impl TryFrom<&DataType> for protobuf::ArrowType {
96    type Error = Error;
97
98    fn try_from(val: &DataType) -> Result<Self, Self::Error> {
99        let arrow_type_enum: ArrowTypeEnum = val.try_into()?;
100        Ok(Self {
101            arrow_type_enum: Some(arrow_type_enum),
102        })
103    }
104}
105
106impl TryFrom<&DataType> for ArrowTypeEnum {
107    type Error = Error;
108
109    fn try_from(val: &DataType) -> Result<Self, Self::Error> {
110        let res = match val {
111            DataType::Null => Self::None(EmptyMessage {}),
112            DataType::Boolean => Self::Bool(EmptyMessage {}),
113            DataType::Int8 => Self::Int8(EmptyMessage {}),
114            DataType::Int16 => Self::Int16(EmptyMessage {}),
115            DataType::Int32 => Self::Int32(EmptyMessage {}),
116            DataType::Int64 => Self::Int64(EmptyMessage {}),
117            DataType::UInt8 => Self::Uint8(EmptyMessage {}),
118            DataType::UInt16 => Self::Uint16(EmptyMessage {}),
119            DataType::UInt32 => Self::Uint32(EmptyMessage {}),
120            DataType::UInt64 => Self::Uint64(EmptyMessage {}),
121            DataType::Float16 => Self::Float16(EmptyMessage {}),
122            DataType::Float32 => Self::Float32(EmptyMessage {}),
123            DataType::Float64 => Self::Float64(EmptyMessage {}),
124            DataType::Timestamp(time_unit, timezone) => {
125                Self::Timestamp(protobuf::Timestamp {
126                    time_unit: protobuf::TimeUnit::from(time_unit) as i32,
127                    timezone: timezone.as_deref().unwrap_or("").to_string(),
128                })
129            }
130            DataType::Date32 => Self::Date32(EmptyMessage {}),
131            DataType::Date64 => Self::Date64(EmptyMessage {}),
132            DataType::Time32(time_unit) => {
133                Self::Time32(protobuf::TimeUnit::from(time_unit) as i32)
134            }
135            DataType::Time64(time_unit) => {
136                Self::Time64(protobuf::TimeUnit::from(time_unit) as i32)
137            }
138            DataType::Duration(time_unit) => {
139                Self::Duration(protobuf::TimeUnit::from(time_unit) as i32)
140            }
141            DataType::Interval(interval_unit) => {
142                Self::Interval(protobuf::IntervalUnit::from(interval_unit) as i32)
143            }
144            DataType::Binary => Self::Binary(EmptyMessage {}),
145            DataType::BinaryView => Self::BinaryView(EmptyMessage {}),
146            DataType::FixedSizeBinary(size) => Self::FixedSizeBinary(*size),
147            DataType::LargeBinary => Self::LargeBinary(EmptyMessage {}),
148            DataType::Utf8 => Self::Utf8(EmptyMessage {}),
149            DataType::Utf8View => Self::Utf8View(EmptyMessage {}),
150            DataType::LargeUtf8 => Self::LargeUtf8(EmptyMessage {}),
151            DataType::List(item_type) => Self::List(Box::new(protobuf::List {
152                field_type: Some(Box::new(item_type.as_ref().try_into()?)),
153            })),
154            DataType::FixedSizeList(item_type, size) => {
155                Self::FixedSizeList(Box::new(protobuf::FixedSizeList {
156                    field_type: Some(Box::new(item_type.as_ref().try_into()?)),
157                    list_size: *size,
158                }))
159            }
160            DataType::LargeList(item_type) => Self::LargeList(Box::new(protobuf::List {
161                field_type: Some(Box::new(item_type.as_ref().try_into()?)),
162            })),
163            DataType::ListView(item_type) => Self::ListView(Box::new(protobuf::List {
164                field_type: Some(Box::new(item_type.as_ref().try_into()?)),
165            })),
166            DataType::LargeListView(item_type) => {
167                Self::LargeListView(Box::new(protobuf::List {
168                    field_type: Some(Box::new(item_type.as_ref().try_into()?)),
169                }))
170            }
171            DataType::Struct(struct_fields) => Self::Struct(protobuf::Struct {
172                sub_field_types: convert_arc_fields_to_proto_fields(struct_fields)?,
173            }),
174            DataType::Union(fields, union_mode) => {
175                let union_mode = match union_mode {
176                    UnionMode::Sparse => protobuf::UnionMode::Sparse,
177                    UnionMode::Dense => protobuf::UnionMode::Dense,
178                };
179                Self::Union(protobuf::Union {
180                    union_types: convert_arc_fields_to_proto_fields(
181                        fields.iter().map(|(_, item)| item),
182                    )?,
183                    union_mode: union_mode.into(),
184                    type_ids: fields.iter().map(|(x, _)| x as i32).collect(),
185                })
186            }
187            DataType::Dictionary(key_type, value_type) => {
188                Self::Dictionary(Box::new(protobuf::Dictionary {
189                    key: Some(Box::new(key_type.as_ref().try_into()?)),
190                    value: Some(Box::new(value_type.as_ref().try_into()?)),
191                }))
192            }
193            DataType::Decimal32(precision, scale) => {
194                Self::Decimal32(protobuf::Decimal32Type {
195                    precision: *precision as u32,
196                    scale: *scale as i32,
197                })
198            }
199            DataType::Decimal64(precision, scale) => {
200                Self::Decimal64(protobuf::Decimal64Type {
201                    precision: *precision as u32,
202                    scale: *scale as i32,
203                })
204            }
205            DataType::Decimal128(precision, scale) => {
206                Self::Decimal128(protobuf::Decimal128Type {
207                    precision: *precision as u32,
208                    scale: *scale as i32,
209                })
210            }
211            DataType::Decimal256(precision, scale) => {
212                Self::Decimal256(protobuf::Decimal256Type {
213                    precision: *precision as u32,
214                    scale: *scale as i32,
215                })
216            }
217            DataType::Map(field, sorted) => Self::Map(Box::new(protobuf::Map {
218                field_type: Some(Box::new(field.as_ref().try_into()?)),
219                keys_sorted: *sorted,
220            })),
221            DataType::RunEndEncoded(run_ends_field, values_field) => {
222                Self::RunEndEncoded(Box::new(protobuf::RunEndEncoded {
223                    run_ends_field: Some(Box::new(run_ends_field.as_ref().try_into()?)),
224                    values_field: Some(Box::new(values_field.as_ref().try_into()?)),
225                }))
226            }
227        };
228
229        Ok(res)
230    }
231}
232
233impl From<Column> for protobuf::Column {
234    fn from(c: Column) -> Self {
235        Self {
236            relation: c.relation.map(|relation| protobuf::ColumnRelation {
237                relation: relation.to_string(),
238                parts: relation.to_vec(),
239            }),
240            name: c.name,
241        }
242    }
243}
244
245impl From<&Column> for protobuf::Column {
246    fn from(c: &Column) -> Self {
247        c.clone().into()
248    }
249}
250
251impl TryFrom<&Schema> for protobuf::Schema {
252    type Error = Error;
253
254    fn try_from(schema: &Schema) -> Result<Self, Self::Error> {
255        Ok(Self {
256            columns: convert_arc_fields_to_proto_fields(schema.fields())?,
257            metadata: schema.metadata().into(),
258        })
259    }
260}
261
262impl TryFrom<SchemaRef> for protobuf::Schema {
263    type Error = Error;
264
265    fn try_from(schema: SchemaRef) -> Result<Self, Self::Error> {
266        Ok(Self {
267            columns: convert_arc_fields_to_proto_fields(schema.fields())?,
268            metadata: schema.metadata().into(),
269        })
270    }
271}
272
273impl TryFrom<&DFSchema> for protobuf::DfSchema {
274    type Error = Error;
275
276    fn try_from(s: &DFSchema) -> Result<Self, Self::Error> {
277        let columns = s
278            .iter()
279            .map(|(qualifier, field)| {
280                Ok(protobuf::DfField {
281                    field: Some(field.as_ref().try_into()?),
282                    qualifier: qualifier.map(|r| protobuf::ColumnRelation {
283                        relation: r.to_string(),
284                        parts: r.to_vec(),
285                    }),
286                })
287            })
288            .collect::<Result<Vec<_>, Error>>()?;
289        Ok(Self {
290            columns,
291            metadata: s.metadata().into(),
292        })
293    }
294}
295
296impl TryFrom<&DFSchemaRef> for protobuf::DfSchema {
297    type Error = Error;
298
299    fn try_from(s: &DFSchemaRef) -> Result<Self, Self::Error> {
300        s.as_ref().try_into()
301    }
302}
303
304impl TryFrom<&ScalarValue> for protobuf::ScalarValue {
305    type Error = Error;
306
307    fn try_from(val: &ScalarValue) -> Result<Self, Self::Error> {
308        let data_type = val.data_type();
309        match val {
310            ScalarValue::Boolean(val) => {
311                create_proto_scalar(val.as_ref(), &data_type, |s| Value::BoolValue(*s))
312            }
313            ScalarValue::Float16(val) => {
314                create_proto_scalar(val.as_ref(), &data_type, |s| {
315                    Value::Float32Value((*s).into())
316                })
317            }
318            ScalarValue::Float32(val) => {
319                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Float32Value(*s))
320            }
321            ScalarValue::Float64(val) => {
322                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Float64Value(*s))
323            }
324            ScalarValue::Int8(val) => {
325                create_proto_scalar(val.as_ref(), &data_type, |s| {
326                    Value::Int8Value(*s as i32)
327                })
328            }
329            ScalarValue::Int16(val) => {
330                create_proto_scalar(val.as_ref(), &data_type, |s| {
331                    Value::Int16Value(*s as i32)
332                })
333            }
334            ScalarValue::Int32(val) => {
335                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Int32Value(*s))
336            }
337            ScalarValue::Int64(val) => {
338                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Int64Value(*s))
339            }
340            ScalarValue::UInt8(val) => {
341                create_proto_scalar(val.as_ref(), &data_type, |s| {
342                    Value::Uint8Value(*s as u32)
343                })
344            }
345            ScalarValue::UInt16(val) => {
346                create_proto_scalar(val.as_ref(), &data_type, |s| {
347                    Value::Uint16Value(*s as u32)
348                })
349            }
350            ScalarValue::UInt32(val) => {
351                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Uint32Value(*s))
352            }
353            ScalarValue::UInt64(val) => {
354                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Uint64Value(*s))
355            }
356            ScalarValue::Utf8(val) => {
357                create_proto_scalar(val.as_ref(), &data_type, |s| {
358                    Value::Utf8Value(s.to_owned())
359                })
360            }
361            ScalarValue::LargeUtf8(val) => {
362                create_proto_scalar(val.as_ref(), &data_type, |s| {
363                    Value::LargeUtf8Value(s.to_owned())
364                })
365            }
366            ScalarValue::Utf8View(val) => {
367                create_proto_scalar(val.as_ref(), &data_type, |s| {
368                    Value::Utf8ViewValue(s.to_owned())
369                })
370            }
371            ScalarValue::List(arr) => {
372                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
373            }
374            ScalarValue::LargeList(arr) => {
375                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
376            }
377            ScalarValue::FixedSizeList(arr) => {
378                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
379            }
380            ScalarValue::ListView(arr) => {
381                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
382            }
383            ScalarValue::LargeListView(arr) => {
384                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
385            }
386            ScalarValue::Struct(arr) => {
387                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
388            }
389            ScalarValue::Map(arr) => {
390                encode_scalar_nested_value(arr.to_owned() as ArrayRef, val)
391            }
392            ScalarValue::Date32(val) => {
393                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Date32Value(*s))
394            }
395            ScalarValue::TimestampMicrosecond(val, tz) => {
396                create_proto_scalar(val.as_ref(), &data_type, |s| {
397                    Value::TimestampValue(protobuf::ScalarTimestampValue {
398                        timezone: tz.as_deref().unwrap_or("").to_string(),
399                        value: Some(
400                            protobuf::scalar_timestamp_value::Value::TimeMicrosecondValue(
401                                *s,
402                            ),
403                        ),
404                    })
405                })
406            }
407            ScalarValue::TimestampNanosecond(val, tz) => {
408                create_proto_scalar(val.as_ref(), &data_type, |s| {
409                    Value::TimestampValue(protobuf::ScalarTimestampValue {
410                        timezone: tz.as_deref().unwrap_or("").to_string(),
411                        value: Some(
412                            protobuf::scalar_timestamp_value::Value::TimeNanosecondValue(
413                                *s,
414                            ),
415                        ),
416                    })
417                })
418            }
419            ScalarValue::Decimal32(val, p, s) => match *val {
420                Some(v) => {
421                    let array = v.to_be_bytes();
422                    let vec_val: Vec<u8> = array.to_vec();
423                    Ok(protobuf::ScalarValue {
424                        value: Some(Value::Decimal32Value(protobuf::Decimal32 {
425                            value: vec_val,
426                            p: *p as i64,
427                            s: *s as i64,
428                        })),
429                    })
430                }
431                None => Ok(protobuf::ScalarValue {
432                    value: Some(Value::NullValue((&data_type).try_into()?)),
433                }),
434            },
435            ScalarValue::Decimal64(val, p, s) => match *val {
436                Some(v) => {
437                    let array = v.to_be_bytes();
438                    let vec_val: Vec<u8> = array.to_vec();
439                    Ok(protobuf::ScalarValue {
440                        value: Some(Value::Decimal64Value(protobuf::Decimal64 {
441                            value: vec_val,
442                            p: *p as i64,
443                            s: *s as i64,
444                        })),
445                    })
446                }
447                None => Ok(protobuf::ScalarValue {
448                    value: Some(Value::NullValue((&data_type).try_into()?)),
449                }),
450            },
451            ScalarValue::Decimal128(val, p, s) => match *val {
452                Some(v) => {
453                    let array = v.to_be_bytes();
454                    let vec_val: Vec<u8> = array.to_vec();
455                    Ok(protobuf::ScalarValue {
456                        value: Some(Value::Decimal128Value(protobuf::Decimal128 {
457                            value: vec_val,
458                            p: *p as i64,
459                            s: *s as i64,
460                        })),
461                    })
462                }
463                None => Ok(protobuf::ScalarValue {
464                    value: Some(Value::NullValue((&data_type).try_into()?)),
465                }),
466            },
467            ScalarValue::Decimal256(val, p, s) => match *val {
468                Some(v) => {
469                    let array = v.to_be_bytes();
470                    let vec_val: Vec<u8> = array.to_vec();
471                    Ok(protobuf::ScalarValue {
472                        value: Some(Value::Decimal256Value(protobuf::Decimal256 {
473                            value: vec_val,
474                            p: *p as i64,
475                            s: *s as i64,
476                        })),
477                    })
478                }
479                None => Ok(protobuf::ScalarValue {
480                    value: Some(Value::NullValue((&data_type).try_into()?)),
481                }),
482            },
483            ScalarValue::Date64(val) => {
484                create_proto_scalar(val.as_ref(), &data_type, |s| Value::Date64Value(*s))
485            }
486            ScalarValue::TimestampSecond(val, tz) => {
487                create_proto_scalar(val.as_ref(), &data_type, |s| {
488                    Value::TimestampValue(protobuf::ScalarTimestampValue {
489                        timezone: tz.as_deref().unwrap_or("").to_string(),
490                        value: Some(
491                            protobuf::scalar_timestamp_value::Value::TimeSecondValue(*s),
492                        ),
493                    })
494                })
495            }
496            ScalarValue::TimestampMillisecond(val, tz) => {
497                create_proto_scalar(val.as_ref(), &data_type, |s| {
498                    Value::TimestampValue(protobuf::ScalarTimestampValue {
499                        timezone: tz.as_deref().unwrap_or("").to_string(),
500                        value: Some(
501                            protobuf::scalar_timestamp_value::Value::TimeMillisecondValue(
502                                *s,
503                            ),
504                        ),
505                    })
506                })
507            }
508            ScalarValue::IntervalYearMonth(val) => {
509                create_proto_scalar(val.as_ref(), &data_type, |s| {
510                    Value::IntervalYearmonthValue(*s)
511                })
512            }
513            ScalarValue::Null => Ok(protobuf::ScalarValue {
514                value: Some(Value::NullValue((&data_type).try_into()?)),
515            }),
516
517            ScalarValue::Binary(val) => {
518                create_proto_scalar(val.as_ref(), &data_type, |s| {
519                    Value::BinaryValue(s.to_owned())
520                })
521            }
522            ScalarValue::BinaryView(val) => {
523                create_proto_scalar(val.as_ref(), &data_type, |s| {
524                    Value::BinaryViewValue(s.to_owned())
525                })
526            }
527            ScalarValue::LargeBinary(val) => {
528                create_proto_scalar(val.as_ref(), &data_type, |s| {
529                    Value::LargeBinaryValue(s.to_owned())
530                })
531            }
532            ScalarValue::FixedSizeBinary(length, val) => {
533                create_proto_scalar(val.as_ref(), &data_type, |s| {
534                    Value::FixedSizeBinaryValue(protobuf::ScalarFixedSizeBinary {
535                        values: s.to_owned(),
536                        length: *length,
537                    })
538                })
539            }
540
541            ScalarValue::Time32Second(v) => {
542                create_proto_scalar(v.as_ref(), &data_type, |v| {
543                    Value::Time32Value(protobuf::ScalarTime32Value {
544                        value: Some(
545                            protobuf::scalar_time32_value::Value::Time32SecondValue(*v),
546                        ),
547                    })
548                })
549            }
550
551            ScalarValue::Time32Millisecond(v) => {
552                create_proto_scalar(v.as_ref(), &data_type, |v| {
553                    Value::Time32Value(protobuf::ScalarTime32Value {
554                        value: Some(
555                            protobuf::scalar_time32_value::Value::Time32MillisecondValue(
556                                *v,
557                            ),
558                        ),
559                    })
560                })
561            }
562
563            ScalarValue::Time64Microsecond(v) => {
564                create_proto_scalar(v.as_ref(), &data_type, |v| {
565                    Value::Time64Value(protobuf::ScalarTime64Value {
566                        value: Some(
567                            protobuf::scalar_time64_value::Value::Time64MicrosecondValue(
568                                *v,
569                            ),
570                        ),
571                    })
572                })
573            }
574
575            ScalarValue::Time64Nanosecond(v) => {
576                create_proto_scalar(v.as_ref(), &data_type, |v| {
577                    Value::Time64Value(protobuf::ScalarTime64Value {
578                        value: Some(
579                            protobuf::scalar_time64_value::Value::Time64NanosecondValue(
580                                *v,
581                            ),
582                        ),
583                    })
584                })
585            }
586
587            ScalarValue::IntervalDayTime(val) => {
588                let value = if let Some(v) = val {
589                    let (days, milliseconds) = IntervalDayTimeType::to_parts(*v);
590                    Value::IntervalDaytimeValue(protobuf::IntervalDayTimeValue {
591                        days,
592                        milliseconds,
593                    })
594                } else {
595                    Value::NullValue((&data_type).try_into()?)
596                };
597
598                Ok(protobuf::ScalarValue { value: Some(value) })
599            }
600
601            ScalarValue::IntervalMonthDayNano(v) => {
602                let value = if let Some(v) = v {
603                    let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(*v);
604                    Value::IntervalMonthDayNano(protobuf::IntervalMonthDayNanoValue {
605                        months,
606                        days,
607                        nanos,
608                    })
609                } else {
610                    Value::NullValue((&data_type).try_into()?)
611                };
612
613                Ok(protobuf::ScalarValue { value: Some(value) })
614            }
615
616            ScalarValue::DurationSecond(v) => {
617                let value = match v {
618                    Some(v) => Value::DurationSecondValue(*v),
619                    None => Value::NullValue((&data_type).try_into()?),
620                };
621                Ok(protobuf::ScalarValue { value: Some(value) })
622            }
623            ScalarValue::DurationMillisecond(v) => {
624                let value = match v {
625                    Some(v) => Value::DurationMillisecondValue(*v),
626                    None => Value::NullValue((&data_type).try_into()?),
627                };
628                Ok(protobuf::ScalarValue { value: Some(value) })
629            }
630            ScalarValue::DurationMicrosecond(v) => {
631                let value = match v {
632                    Some(v) => Value::DurationMicrosecondValue(*v),
633                    None => Value::NullValue((&data_type).try_into()?),
634                };
635                Ok(protobuf::ScalarValue { value: Some(value) })
636            }
637            ScalarValue::DurationNanosecond(v) => {
638                let value = match v {
639                    Some(v) => Value::DurationNanosecondValue(*v),
640                    None => Value::NullValue((&data_type).try_into()?),
641                };
642                Ok(protobuf::ScalarValue { value: Some(value) })
643            }
644
645            ScalarValue::Union(val, df_fields, mode) => {
646                let mut fields =
647                    Vec::<protobuf::UnionField>::with_capacity(df_fields.len());
648                for (id, field) in df_fields.iter() {
649                    let field_id = id as i32;
650                    let field = Some(field.as_ref().try_into()?);
651                    let field = protobuf::UnionField { field_id, field };
652                    fields.push(field);
653                }
654                let mode = match mode {
655                    UnionMode::Sparse => 0,
656                    UnionMode::Dense => 1,
657                };
658                let value = match val {
659                    None => None,
660                    Some((_id, v)) => Some(Box::new(v.as_ref().try_into()?)),
661                };
662                let val = protobuf::UnionValue {
663                    value_id: val.as_ref().map(|(id, _v)| *id as i32).unwrap_or(0),
664                    value,
665                    fields,
666                    mode,
667                };
668                let val = Value::UnionValue(Box::new(val));
669                let val = protobuf::ScalarValue { value: Some(val) };
670                Ok(val)
671            }
672
673            ScalarValue::Dictionary(index_type, val) => {
674                let value: protobuf::ScalarValue = val.as_ref().try_into()?;
675                Ok(protobuf::ScalarValue {
676                    value: Some(Value::DictionaryValue(Box::new(
677                        protobuf::ScalarDictionaryValue {
678                            index_type: Some(index_type.as_ref().try_into()?),
679                            value: Some(Box::new(value)),
680                        },
681                    ))),
682                })
683            }
684
685            ScalarValue::RunEndEncoded(run_ends_field, values_field, val) => {
686                Ok(protobuf::ScalarValue {
687                    value: Some(Value::RunEndEncodedValue(Box::new(
688                        protobuf::ScalarRunEndEncodedValue {
689                            run_ends_field: Some(run_ends_field.as_ref().try_into()?),
690                            values_field: Some(values_field.as_ref().try_into()?),
691                            value: Some(Box::new(val.as_ref().try_into()?)),
692                        },
693                    ))),
694                })
695            }
696        }
697    }
698}
699
700impl From<&TimeUnit> for protobuf::TimeUnit {
701    fn from(val: &TimeUnit) -> Self {
702        match val {
703            TimeUnit::Second => protobuf::TimeUnit::Second,
704            TimeUnit::Millisecond => protobuf::TimeUnit::Millisecond,
705            TimeUnit::Microsecond => protobuf::TimeUnit::Microsecond,
706            TimeUnit::Nanosecond => protobuf::TimeUnit::Nanosecond,
707        }
708    }
709}
710
711impl From<&IntervalUnit> for protobuf::IntervalUnit {
712    fn from(interval_unit: &IntervalUnit) -> Self {
713        match interval_unit {
714            IntervalUnit::YearMonth => protobuf::IntervalUnit::YearMonth,
715            IntervalUnit::DayTime => protobuf::IntervalUnit::DayTime,
716            IntervalUnit::MonthDayNano => protobuf::IntervalUnit::MonthDayNano,
717        }
718    }
719}
720
721impl From<Constraints> for protobuf::Constraints {
722    fn from(value: Constraints) -> Self {
723        let constraints = value.into_iter().map(|item| item.into()).collect();
724        protobuf::Constraints { constraints }
725    }
726}
727
728impl From<Constraint> for protobuf::Constraint {
729    fn from(value: Constraint) -> Self {
730        let res = match value {
731            Constraint::PrimaryKey(indices) => {
732                let indices = indices.into_iter().map(|item| item as u64).collect();
733                protobuf::constraint::ConstraintMode::PrimaryKey(
734                    protobuf::PrimaryKeyConstraint { indices },
735                )
736            }
737            Constraint::Unique(indices) => {
738                let indices = indices.into_iter().map(|item| item as u64).collect();
739                protobuf::constraint::ConstraintMode::PrimaryKey(
740                    protobuf::PrimaryKeyConstraint { indices },
741                )
742            }
743        };
744        protobuf::Constraint {
745            constraint_mode: Some(res),
746        }
747    }
748}
749
750impl From<&Precision<usize>> for protobuf::Precision {
751    fn from(s: &Precision<usize>) -> protobuf::Precision {
752        match s {
753            Precision::Exact(val) => protobuf::Precision {
754                precision_info: protobuf::PrecisionInfo::Exact.into(),
755                val: Some(crate::protobuf_common::ScalarValue {
756                    value: Some(Value::Uint64Value(*val as u64)),
757                }),
758            },
759            Precision::Inexact(val) => protobuf::Precision {
760                precision_info: protobuf::PrecisionInfo::Inexact.into(),
761                val: Some(crate::protobuf_common::ScalarValue {
762                    value: Some(Value::Uint64Value(*val as u64)),
763                }),
764            },
765            Precision::Absent => protobuf::Precision {
766                precision_info: protobuf::PrecisionInfo::Absent.into(),
767                val: Some(crate::protobuf_common::ScalarValue { value: None }),
768            },
769        }
770    }
771}
772
773impl From<&Precision<ScalarValue>> for protobuf::Precision {
774    fn from(s: &Precision<ScalarValue>) -> protobuf::Precision {
775        match s {
776            Precision::Exact(val) => protobuf::Precision {
777                precision_info: protobuf::PrecisionInfo::Exact.into(),
778                val: val.try_into().ok(),
779            },
780            Precision::Inexact(val) => protobuf::Precision {
781                precision_info: protobuf::PrecisionInfo::Inexact.into(),
782                val: val.try_into().ok(),
783            },
784            Precision::Absent => protobuf::Precision {
785                precision_info: protobuf::PrecisionInfo::Absent.into(),
786                val: Some(crate::protobuf_common::ScalarValue { value: None }),
787            },
788        }
789    }
790}
791
792impl From<&Statistics> for protobuf::Statistics {
793    fn from(s: &Statistics) -> protobuf::Statistics {
794        let column_stats = s.column_statistics.iter().map(|s| s.into()).collect();
795        protobuf::Statistics {
796            num_rows: Some(protobuf::Precision::from(&s.num_rows)),
797            total_byte_size: Some(protobuf::Precision::from(&s.total_byte_size)),
798            column_stats,
799        }
800    }
801}
802
803impl From<&ColumnStatistics> for protobuf::ColumnStats {
804    fn from(s: &ColumnStatistics) -> protobuf::ColumnStats {
805        protobuf::ColumnStats {
806            min_value: Some(protobuf::Precision::from(&s.min_value)),
807            max_value: Some(protobuf::Precision::from(&s.max_value)),
808            sum_value: Some(protobuf::Precision::from(&s.sum_value)),
809            null_count: Some(protobuf::Precision::from(&s.null_count)),
810            distinct_count: Some(protobuf::Precision::from(&s.distinct_count)),
811            byte_size: Some(protobuf::Precision::from(&s.byte_size)),
812        }
813    }
814}
815
816impl From<JoinSide> for protobuf::JoinSide {
817    fn from(t: JoinSide) -> Self {
818        match t {
819            JoinSide::Left => protobuf::JoinSide::LeftSide,
820            JoinSide::Right => protobuf::JoinSide::RightSide,
821            JoinSide::None => protobuf::JoinSide::None,
822        }
823    }
824}
825
826impl From<&CompressionTypeVariant> for protobuf::CompressionTypeVariant {
827    fn from(value: &CompressionTypeVariant) -> Self {
828        match value {
829            CompressionTypeVariant::GZIP => Self::Gzip,
830            CompressionTypeVariant::BZIP2 => Self::Bzip2,
831            CompressionTypeVariant::XZ => Self::Xz,
832            CompressionTypeVariant::ZSTD => Self::Zstd,
833            CompressionTypeVariant::UNCOMPRESSED => Self::Uncompressed,
834        }
835    }
836}
837
838impl From<CsvQuoteStyle> for protobuf::CsvQuoteStyle {
839    fn from(value: CsvQuoteStyle) -> Self {
840        match value {
841            CsvQuoteStyle::Necessary => Self::Necessary,
842            CsvQuoteStyle::Always => Self::Always,
843            CsvQuoteStyle::NonNumeric => Self::NonNumeric,
844            CsvQuoteStyle::Never => Self::Never,
845        }
846    }
847}
848
849impl From<QuoteStyle> for protobuf::CsvQuoteStyle {
850    fn from(value: QuoteStyle) -> Self {
851        match value {
852            QuoteStyle::Necessary => Self::Necessary,
853            QuoteStyle::Always => Self::Always,
854            QuoteStyle::NonNumeric => Self::NonNumeric,
855            QuoteStyle::Never => Self::Never,
856            _ => Self::Necessary,
857        }
858    }
859}
860
861impl TryFrom<&CsvWriterOptions> for protobuf::CsvWriterOptions {
862    type Error = DataFusionError;
863
864    fn try_from(opts: &CsvWriterOptions) -> datafusion_common::Result<Self, Self::Error> {
865        let CsvWriterOptions {
866            writer_options,
867            compression,
868            compression_level,
869        } = opts;
870        let compression: protobuf::CompressionTypeVariant = compression.into();
871        let quote_style: protobuf::CsvQuoteStyle = writer_options.quote_style().into();
872        let terminator = match writer_options.line_terminator() {
873            Terminator::CRLF => b"\r\n".to_vec(),
874            Terminator::Any(byte) => vec![*byte],
875        };
876
877        Ok(protobuf::CsvWriterOptions {
878            compression: compression.into(),
879            delimiter: (writer_options.delimiter() as char).to_string(),
880            has_header: writer_options.header(),
881            date_format: writer_options.date_format().map(str::to_owned),
882            datetime_format: writer_options.datetime_format().map(str::to_owned),
883            timestamp_format: writer_options.timestamp_format().map(str::to_owned),
884            time_format: writer_options.time_format().map(str::to_owned),
885            null_value: writer_options.null().to_owned(),
886            quote: (writer_options.quote() as char).to_string(),
887            escape: (writer_options.escape() as char).to_string(),
888            double_quote: writer_options.double_quote(),
889            quote_style: quote_style.into(),
890            ignore_leading_whitespace: writer_options.ignore_leading_whitespace(),
891            ignore_trailing_whitespace: writer_options.ignore_trailing_whitespace(),
892            compression_level: *compression_level,
893            timestamp_tz_format: writer_options.timestamp_tz_format().map(str::to_owned),
894            terminator,
895        })
896    }
897}
898
899impl TryFrom<&JsonWriterOptions> for protobuf::JsonWriterOptions {
900    type Error = DataFusionError;
901
902    fn try_from(
903        opts: &JsonWriterOptions,
904    ) -> datafusion_common::Result<Self, Self::Error> {
905        // Exhaustive destructure: new writer options must be explicitly
906        // included in the wire representation.
907        let JsonWriterOptions {
908            compression,
909            compression_level,
910        } = opts;
911        let compression: protobuf::CompressionTypeVariant = (*compression).into();
912        Ok(protobuf::JsonWriterOptions {
913            compression: compression.into(),
914            compression_level: *compression_level,
915        })
916    }
917}
918
919impl TryFrom<&ParquetOptions> for protobuf::ParquetOptions {
920    type Error = DataFusionError;
921
922    fn try_from(value: &ParquetOptions) -> datafusion_common::Result<Self, Self::Error> {
923        Ok(protobuf::ParquetOptions {
924            enable_page_index: value.enable_page_index,
925            pruning: value.pruning,
926            skip_metadata: value.skip_metadata,
927            metadata_size_hint_opt: value.metadata_size_hint.map(|v| protobuf::parquet_options::MetadataSizeHintOpt::MetadataSizeHint(v as u64)),
928            pushdown_filters: value.pushdown_filters,
929            reorder_filters: value.reorder_filters,
930            force_filter_selections: value.force_filter_selections,
931            data_pagesize_limit: value.data_pagesize_limit as u64,
932            write_batch_size: value.write_batch_size as u64,
933            writer_version: value.writer_version.to_string(),
934            compression_opt: value.compression.map(|v| protobuf::parquet_options::CompressionOpt::Compression(v.to_string())),
935            dictionary_enabled_opt: value.dictionary_enabled.map(protobuf::parquet_options::DictionaryEnabledOpt::DictionaryEnabled),
936            dictionary_page_size_limit: value.dictionary_page_size_limit as u64,
937            statistics_enabled_opt: value.statistics_enabled.map(|v| protobuf::parquet_options::StatisticsEnabledOpt::StatisticsEnabled(v.to_string())),
938            max_row_group_size: value.max_row_group_size as u64,
939            max_in_list_size: value.max_in_list_size as u64,
940            row_group_range_assignment: value.row_group_range_assignment.to_string(),
941            created_by: value.created_by.clone(),
942            column_index_truncate_length_opt: value.column_index_truncate_length.map(|v| protobuf::parquet_options::ColumnIndexTruncateLengthOpt::ColumnIndexTruncateLength(v as u64)),
943            statistics_truncate_length_opt: value.statistics_truncate_length.map(|v| protobuf::parquet_options::StatisticsTruncateLengthOpt::StatisticsTruncateLength(v as u64)),
944            data_page_row_count_limit: value.data_page_row_count_limit as u64,
945            encoding_opt: value.encoding.map(|encoding| protobuf::parquet_options::EncodingOpt::Encoding(encoding.to_string())),
946            bloom_filter_on_read: value.bloom_filter_on_read,
947            bloom_filter_on_write: value.bloom_filter_on_write,
948            bloom_filter_fpp_opt: value.bloom_filter_fpp.map(protobuf::parquet_options::BloomFilterFppOpt::BloomFilterFpp),
949            bloom_filter_ndv_opt: value.bloom_filter_ndv.map(protobuf::parquet_options::BloomFilterNdvOpt::BloomFilterNdv),
950            allow_single_file_parallelism: value.allow_single_file_parallelism,
951            maximum_parallel_row_group_writers: value.maximum_parallel_row_group_writers as u64,
952            maximum_buffered_record_batches_per_stream: value.maximum_buffered_record_batches_per_stream as u64,
953            schema_force_view_types: value.schema_force_view_types,
954            binary_as_string: value.binary_as_string,
955            skip_arrow_metadata: value.skip_arrow_metadata,
956            write_row_group_number_distinct_values: value.write_row_group_number_distinct_values,
957            coerce_int96_opt: value.coerce_int96.map(|v| protobuf::parquet_options::CoerceInt96Opt::CoerceInt96(v.to_string())),
958            coerce_int96_tz_opt: value.coerce_int96_tz.as_ref().map(|v| protobuf::parquet_options::CoerceInt96TzOpt::CoerceInt96Tz(v.to_string())),
959            max_predicate_cache_size_opt: value.max_predicate_cache_size.map(|v| protobuf::parquet_options::MaxPredicateCacheSizeOpt::MaxPredicateCacheSize(v as u64)),
960            max_row_group_bytes_opt: value.max_row_group_bytes.map(|v| protobuf::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(v.get() as u64)),
961            content_defined_chunking: Some((&value.content_defined_chunking).into()),
962            enable_rle_to_dictionary: value.enable_rle_to_dictionary,
963        })
964    }
965}
966
967impl From<&ParquetCdcOptions> for protobuf::ParquetCdcOptions {
968    fn from(value: &ParquetCdcOptions) -> Self {
969        protobuf::ParquetCdcOptions {
970            enabled: value.enabled,
971            min_chunk_size: value.min_chunk_size as u64,
972            max_chunk_size: value.max_chunk_size as u64,
973            norm_level: value.norm_level,
974        }
975    }
976}
977
978impl TryFrom<&ParquetColumnOptions> for protobuf::ParquetColumnOptions {
979    type Error = DataFusionError;
980
981    fn try_from(
982        value: &ParquetColumnOptions,
983    ) -> datafusion_common::Result<Self, Self::Error> {
984        Ok(protobuf::ParquetColumnOptions {
985            compression_opt: value
986                .compression
987                .clone()
988                .map(protobuf::parquet_column_options::CompressionOpt::Compression),
989            dictionary_enabled_opt: value
990                .dictionary_enabled
991                .map(protobuf::parquet_column_options::DictionaryEnabledOpt::DictionaryEnabled),
992            statistics_enabled_opt: value
993                .statistics_enabled
994                .clone()
995                .map(protobuf::parquet_column_options::StatisticsEnabledOpt::StatisticsEnabled),
996            encoding_opt: value
997                .encoding
998                .clone()
999                .map(protobuf::parquet_column_options::EncodingOpt::Encoding),
1000            bloom_filter_enabled_opt: value
1001                .bloom_filter_enabled
1002                .map(protobuf::parquet_column_options::BloomFilterEnabledOpt::BloomFilterEnabled),
1003            bloom_filter_fpp_opt: value
1004                .bloom_filter_fpp
1005                .map(protobuf::parquet_column_options::BloomFilterFppOpt::BloomFilterFpp),
1006            bloom_filter_ndv_opt: value
1007                .bloom_filter_ndv
1008                .map(protobuf::parquet_column_options::BloomFilterNdvOpt::BloomFilterNdv),
1009        })
1010    }
1011}
1012
1013impl TryFrom<&TableParquetOptions> for protobuf::TableParquetOptions {
1014    type Error = DataFusionError;
1015    fn try_from(
1016        value: &TableParquetOptions,
1017    ) -> datafusion_common::Result<Self, Self::Error> {
1018        let column_specific_options = value
1019            .column_specific_options
1020            .iter()
1021            .map(|(k, v)| {
1022                Ok(protobuf::ParquetColumnSpecificOptions {
1023                    column_name: k.into(),
1024                    options: Some(v.try_into()?),
1025                })
1026            })
1027            .collect::<datafusion_common::Result<Vec<_>>>()?;
1028        let key_value_metadata = value
1029            .key_value_metadata
1030            .iter()
1031            .filter_map(|(k, v)| v.as_ref().map(|v| (k.clone(), v.clone())))
1032            .collect::<HashMap<String, String>>();
1033
1034        let global: protobuf::ParquetOptions = (&value.global).try_into()?;
1035
1036        Ok(protobuf::TableParquetOptions {
1037            global: Some(global),
1038            column_specific_options,
1039            key_value_metadata,
1040        })
1041    }
1042}
1043
1044impl TryFrom<&CsvOptions> for protobuf::CsvOptions {
1045    type Error = DataFusionError; // Define or use an appropriate error type
1046
1047    fn try_from(opts: &CsvOptions) -> datafusion_common::Result<Self, Self::Error> {
1048        let compression: protobuf::CompressionTypeVariant = opts.compression.into();
1049        let quote_style: protobuf::CsvQuoteStyle = opts.quote_style.into();
1050        Ok(protobuf::CsvOptions {
1051            has_header: opts.has_header.map_or_else(Vec::new, |h| vec![h as u8]),
1052            delimiter: vec![opts.delimiter],
1053            quote: vec![opts.quote],
1054            terminator: opts.terminator.map_or_else(Vec::new, |e| vec![e]),
1055            escape: opts.escape.map_or_else(Vec::new, |e| vec![e]),
1056            double_quote: opts.double_quote.map_or_else(Vec::new, |h| vec![h as u8]),
1057            newlines_in_values: opts
1058                .newlines_in_values
1059                .map_or_else(Vec::new, |h| vec![h as u8]),
1060            compression: compression.into(),
1061            schema_infer_max_rec: opts.schema_infer_max_rec.map(|h| h as u64),
1062            date_format: opts.date_format.clone().unwrap_or_default(),
1063            datetime_format: opts.datetime_format.clone().unwrap_or_default(),
1064            timestamp_format: opts.timestamp_format.clone().unwrap_or_default(),
1065            timestamp_tz_format: opts.timestamp_tz_format.clone().unwrap_or_default(),
1066            time_format: opts.time_format.clone().unwrap_or_default(),
1067            null_value: opts.null_value.clone().unwrap_or_default(),
1068            null_regex: opts.null_regex.clone().unwrap_or_default(),
1069            comment: opts.comment.map_or_else(Vec::new, |h| vec![h]),
1070            truncated_rows: opts.truncated_rows.map_or_else(Vec::new, |h| vec![h as u8]),
1071            compression_level: opts.compression_level,
1072            quote_style: quote_style.into(),
1073            ignore_leading_whitespace: opts
1074                .ignore_leading_whitespace
1075                .map_or_else(Vec::new, |h| vec![h as u8]),
1076            ignore_trailing_whitespace: opts
1077                .ignore_trailing_whitespace
1078                .map_or_else(Vec::new, |h| vec![h as u8]),
1079        })
1080    }
1081}
1082
1083impl TryFrom<&JsonOptions> for protobuf::JsonOptions {
1084    type Error = DataFusionError;
1085
1086    fn try_from(opts: &JsonOptions) -> datafusion_common::Result<Self, Self::Error> {
1087        let compression: protobuf::CompressionTypeVariant = opts.compression.into();
1088        Ok(protobuf::JsonOptions {
1089            compression: compression.into(),
1090            schema_infer_max_rec: opts.schema_infer_max_rec.map(|h| h as u64),
1091            compression_level: opts.compression_level,
1092            newline_delimited: Some(opts.newline_delimited),
1093        })
1094    }
1095}
1096
1097/// Creates a scalar protobuf value from an optional value (T), and
1098/// encoding None as the appropriate datatype
1099fn create_proto_scalar<I, T: FnOnce(&I) -> Value>(
1100    v: Option<&I>,
1101    null_arrow_type: &DataType,
1102    constructor: T,
1103) -> Result<protobuf::ScalarValue, Error> {
1104    let value = v
1105        .map(constructor)
1106        .unwrap_or(Value::NullValue(null_arrow_type.try_into()?));
1107
1108    Ok(protobuf::ScalarValue { value: Some(value) })
1109}
1110
1111// Nested ScalarValue types (List / FixedSizeList / LargeList / ListView / LargeListView / Struct / Map)
1112// are serialized using Arrow IPC messages as a single column RecordBatch
1113fn encode_scalar_nested_value(
1114    arr: ArrayRef,
1115    val: &ScalarValue,
1116) -> Result<protobuf::ScalarValue, Error> {
1117    let batch = RecordBatch::try_from_iter(vec![("field_name", arr)]).map_err(|e| {
1118        Error::General(format!(
1119            "Error creating temporary batch while encoding nested ScalarValue: {e}"
1120        ))
1121    })?;
1122
1123    let ipc_gen = IpcDataGenerator {};
1124    let mut dict_tracker = DictionaryTracker::new(false);
1125    let write_options = IpcWriteOptions::default();
1126    // The IPC writer requires pre-allocated dictionary IDs (normally assigned when
1127    // serializing the schema). Populate `dict_tracker` by encoding the schema first.
1128    ipc_gen.schema_to_bytes_with_dictionary_tracker(
1129        batch.schema().as_ref(),
1130        &mut dict_tracker,
1131        &write_options,
1132    );
1133    let mut compression_context = IpcWriteContext::default();
1134    let (encoded_dictionaries, encoded_message) = ipc_gen
1135        .encode(
1136            &batch,
1137            &mut dict_tracker,
1138            &write_options,
1139            &mut compression_context,
1140        )
1141        .map_err(|e| {
1142            Error::General(format!("Error encoding nested ScalarValue as IPC: {e}"))
1143        })?;
1144
1145    let schema: protobuf::Schema = batch.schema().try_into()?;
1146
1147    let scalar_list_value = protobuf::ScalarNestedValue {
1148        ipc_message: encoded_message.ipc_message,
1149        arrow_data: encoded_message.arrow_data,
1150        dictionaries: encoded_dictionaries
1151            .into_iter()
1152            .map(|data| protobuf::scalar_nested_value::Dictionary {
1153                ipc_message: data.ipc_message,
1154                arrow_data: data.arrow_data,
1155            })
1156            .collect(),
1157        schema: Some(schema),
1158    };
1159
1160    match val {
1161        ScalarValue::List(_) => Ok(protobuf::ScalarValue {
1162            value: Some(Value::ListValue(scalar_list_value)),
1163        }),
1164        ScalarValue::LargeList(_) => Ok(protobuf::ScalarValue {
1165            value: Some(Value::LargeListValue(scalar_list_value)),
1166        }),
1167        ScalarValue::FixedSizeList(_) => Ok(protobuf::ScalarValue {
1168            value: Some(Value::FixedSizeListValue(scalar_list_value)),
1169        }),
1170        ScalarValue::ListView(_) => Ok(protobuf::ScalarValue {
1171            value: Some(Value::ListViewValue(scalar_list_value)),
1172        }),
1173        ScalarValue::LargeListView(_) => Ok(protobuf::ScalarValue {
1174            value: Some(Value::LargeListViewValue(scalar_list_value)),
1175        }),
1176        ScalarValue::Struct(_) => Ok(protobuf::ScalarValue {
1177            value: Some(Value::StructValue(scalar_list_value)),
1178        }),
1179        ScalarValue::Map(_) => Ok(protobuf::ScalarValue {
1180            value: Some(Value::MapValue(scalar_list_value)),
1181        }),
1182        _ => unreachable!(),
1183    }
1184}
1185
1186/// Converts a vector of `Arc<arrow::Field>`s to `protobuf::Field`s
1187fn convert_arc_fields_to_proto_fields<'a, I>(
1188    fields: I,
1189) -> Result<Vec<protobuf::Field>, Error>
1190where
1191    I: IntoIterator<Item = &'a Arc<Field>>,
1192{
1193    fields
1194        .into_iter()
1195        .map(|field| field.as_ref().try_into())
1196        .collect::<Result<Vec<_>, Error>>()
1197}