use std::collections::HashMap;
use std::sync::Arc;
use crate::common::proto_error;
use crate::protobuf_common as protobuf;
use arrow::array::{ArrayRef, AsArray};
use arrow::buffer::Buffer;
use arrow::csv::writer::Terminator;
use arrow::csv::{QuoteStyle, WriterBuilder};
use arrow::datatypes::{
DataType, Field, IntervalDayTimeType, IntervalMonthDayNanoType, IntervalUnit, Schema,
TimeUnit, UnionFields, UnionMode, i256,
};
use arrow::ipc::{
convert::try_fb_to_schema,
reader::{read_dictionary, read_record_batch},
root_as_message,
writer::{DictionaryTracker, IpcDataGenerator, IpcWriteOptions},
};
use datafusion_common::{
Column, ColumnStatistics, Constraint, Constraints, DFSchema, DFSchemaRef,
DataFusionError, JoinSide, ScalarValue, Statistics, TableReference,
arrow_datafusion_err,
config::{
CsvOptions, JsonOptions, MaxRowGroupBytes, ParquetCdcOptions,
ParquetColumnOptions, ParquetOptions, TableParquetOptions,
},
file_options::{csv_writer::CsvWriterOptions, json_writer::JsonWriterOptions},
parquet_config::RowGroupRangeAssignment,
parsers::CompressionTypeVariant,
plan_datafusion_err,
stats::Precision,
utils::usize_from_wire,
};
#[derive(Debug)]
pub enum Error {
General(String),
DataFusionError(DataFusionError),
MissingRequiredField(String),
AtLeastOneValue(String),
UnknownEnumVariant { name: String, value: i32 },
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::General(desc) => write!(f, "General error: {desc}"),
Self::DataFusionError(desc) => {
write!(f, "DataFusion error: {desc:?}")
}
Self::MissingRequiredField(name) => {
write!(f, "Missing required field {name}")
}
Self::AtLeastOneValue(name) => {
write!(f, "Must have at least one {name}, found 0")
}
Self::UnknownEnumVariant { name, value } => {
write!(f, "Unknown i32 value for {name} enum: {value}")
}
}
}
}
impl std::error::Error for Error {}
impl From<DataFusionError> for Error {
fn from(e: DataFusionError) -> Self {
Error::DataFusionError(e)
}
}
impl Error {
pub fn required(field: impl Into<String>) -> Error {
Error::MissingRequiredField(field.into())
}
pub fn unknown(name: impl Into<String>, value: i32) -> Error {
Error::UnknownEnumVariant {
name: name.into(),
value,
}
}
}
impl From<Error> for DataFusionError {
fn from(e: Error) -> Self {
plan_datafusion_err!("{}", e)
}
}
pub trait FromOptionalField<T> {
fn optional(self) -> datafusion_common::Result<Option<T>, Error>;
fn required(self, field: impl Into<String>) -> datafusion_common::Result<T, Error>;
}
impl<T, U> FromOptionalField<U> for Option<T>
where
T: TryInto<U, Error = Error>,
{
fn optional(self) -> datafusion_common::Result<Option<U>, Error> {
self.map(|t| t.try_into()).transpose()
}
fn required(self, field: impl Into<String>) -> datafusion_common::Result<U, Error> {
match self {
None => Err(Error::required(field)),
Some(t) => t.try_into(),
}
}
}
impl From<protobuf::ColumnRelation> for TableReference {
fn from(rel: protobuf::ColumnRelation) -> Self {
match rel.parts.as_slice() {
[table] => Self::bare(table.as_str()),
[schema, table] => Self::partial(schema.as_str(), table.as_str()),
[catalog, schema, table] => {
Self::full(catalog.as_str(), schema.as_str(), table.as_str())
}
_ => Self::parse_str_normalized(rel.relation.as_str(), true),
}
}
}
impl From<protobuf::Column> for Column {
fn from(c: protobuf::Column) -> Self {
let protobuf::Column { relation, name } = c;
Self::new(relation, name)
}
}
impl From<&protobuf::Column> for Column {
fn from(c: &protobuf::Column) -> Self {
c.clone().into()
}
}
impl TryFrom<&protobuf::DfSchema> for DFSchema {
type Error = Error;
fn try_from(
df_schema: &protobuf::DfSchema,
) -> datafusion_common::Result<Self, Self::Error> {
let df_fields = df_schema.columns.clone();
let qualifiers_and_fields: Vec<(Option<TableReference>, Arc<Field>)> = df_fields
.iter()
.map(|df_field| {
let field: Field = df_field.field.as_ref().required("field")?;
Ok((
df_field.qualifier.as_ref().map(|q| q.clone().into()),
Arc::new(field),
))
})
.collect::<datafusion_common::Result<Vec<_>, Error>>()?;
Ok(DFSchema::new_with_metadata(
qualifiers_and_fields,
df_schema.metadata.clone(),
)?)
}
}
impl TryFrom<protobuf::DfSchema> for DFSchemaRef {
type Error = Error;
fn try_from(
df_schema: protobuf::DfSchema,
) -> datafusion_common::Result<Self, Self::Error> {
let dfschema: DFSchema = (&df_schema).try_into()?;
Ok(Arc::new(dfschema))
}
}
impl TryFrom<&protobuf::ArrowType> for DataType {
type Error = Error;
fn try_from(
arrow_type: &protobuf::ArrowType,
) -> datafusion_common::Result<Self, Self::Error> {
arrow_type
.arrow_type_enum
.as_ref()
.required("arrow_type_enum")
}
}
impl TryFrom<&protobuf::arrow_type::ArrowTypeEnum> for DataType {
type Error = Error;
fn try_from(
arrow_type_enum: &protobuf::arrow_type::ArrowTypeEnum,
) -> datafusion_common::Result<Self, Self::Error> {
use protobuf::arrow_type;
Ok(match arrow_type_enum {
arrow_type::ArrowTypeEnum::None(_) => DataType::Null,
arrow_type::ArrowTypeEnum::Bool(_) => DataType::Boolean,
arrow_type::ArrowTypeEnum::Uint8(_) => DataType::UInt8,
arrow_type::ArrowTypeEnum::Int8(_) => DataType::Int8,
arrow_type::ArrowTypeEnum::Uint16(_) => DataType::UInt16,
arrow_type::ArrowTypeEnum::Int16(_) => DataType::Int16,
arrow_type::ArrowTypeEnum::Uint32(_) => DataType::UInt32,
arrow_type::ArrowTypeEnum::Int32(_) => DataType::Int32,
arrow_type::ArrowTypeEnum::Uint64(_) => DataType::UInt64,
arrow_type::ArrowTypeEnum::Int64(_) => DataType::Int64,
arrow_type::ArrowTypeEnum::Float16(_) => DataType::Float16,
arrow_type::ArrowTypeEnum::Float32(_) => DataType::Float32,
arrow_type::ArrowTypeEnum::Float64(_) => DataType::Float64,
arrow_type::ArrowTypeEnum::Utf8(_) => DataType::Utf8,
arrow_type::ArrowTypeEnum::Utf8View(_) => DataType::Utf8View,
arrow_type::ArrowTypeEnum::LargeUtf8(_) => DataType::LargeUtf8,
arrow_type::ArrowTypeEnum::Binary(_) => DataType::Binary,
arrow_type::ArrowTypeEnum::BinaryView(_) => DataType::BinaryView,
arrow_type::ArrowTypeEnum::FixedSizeBinary(size) => {
DataType::FixedSizeBinary(*size)
}
arrow_type::ArrowTypeEnum::LargeBinary(_) => DataType::LargeBinary,
arrow_type::ArrowTypeEnum::Date32(_) => DataType::Date32,
arrow_type::ArrowTypeEnum::Date64(_) => DataType::Date64,
arrow_type::ArrowTypeEnum::Duration(time_unit) => {
DataType::Duration(parse_i32_to_time_unit(time_unit)?)
}
arrow_type::ArrowTypeEnum::Timestamp(protobuf::Timestamp {
time_unit,
timezone,
}) => DataType::Timestamp(
parse_i32_to_time_unit(time_unit)?,
match timezone.len() {
0 => None,
_ => Some(timezone.as_str().into()),
},
),
arrow_type::ArrowTypeEnum::Time32(time_unit) => {
DataType::Time32(parse_i32_to_time_unit(time_unit)?)
}
arrow_type::ArrowTypeEnum::Time64(time_unit) => {
DataType::Time64(parse_i32_to_time_unit(time_unit)?)
}
arrow_type::ArrowTypeEnum::Interval(interval_unit) => {
DataType::Interval(parse_i32_to_interval_unit(interval_unit)?)
}
arrow_type::ArrowTypeEnum::Decimal32(protobuf::Decimal32Type {
precision,
scale,
}) => DataType::Decimal32(*precision as u8, *scale as i8),
arrow_type::ArrowTypeEnum::Decimal64(protobuf::Decimal64Type {
precision,
scale,
}) => DataType::Decimal64(*precision as u8, *scale as i8),
arrow_type::ArrowTypeEnum::Decimal128(protobuf::Decimal128Type {
precision,
scale,
}) => DataType::Decimal128(*precision as u8, *scale as i8),
arrow_type::ArrowTypeEnum::Decimal256(protobuf::Decimal256Type {
precision,
scale,
}) => DataType::Decimal256(*precision as u8, *scale as i8),
arrow_type::ArrowTypeEnum::List(list) => {
let list_type =
list.as_ref().field_type.as_deref().required("field_type")?;
DataType::List(Arc::new(list_type))
}
arrow_type::ArrowTypeEnum::LargeList(list) => {
let list_type =
list.as_ref().field_type.as_deref().required("field_type")?;
DataType::LargeList(Arc::new(list_type))
}
arrow_type::ArrowTypeEnum::FixedSizeList(list) => {
let list_type =
list.as_ref().field_type.as_deref().required("field_type")?;
let list_size = list.list_size;
DataType::FixedSizeList(Arc::new(list_type), list_size)
}
arrow_type::ArrowTypeEnum::ListView(list) => {
let list_type =
list.as_ref().field_type.as_deref().required("field_type")?;
DataType::ListView(Arc::new(list_type))
}
arrow_type::ArrowTypeEnum::LargeListView(list) => {
let list_type =
list.as_ref().field_type.as_deref().required("field_type")?;
DataType::LargeListView(Arc::new(list_type))
}
arrow_type::ArrowTypeEnum::Struct(strct) => DataType::Struct(
parse_proto_fields_to_fields(&strct.sub_field_types)?.into(),
),
arrow_type::ArrowTypeEnum::Union(union) => {
let union_mode = protobuf::UnionMode::try_from(union.union_mode)
.map_err(|_| Error::unknown("UnionMode", union.union_mode))?;
let union_mode = match union_mode {
protobuf::UnionMode::Dense => UnionMode::Dense,
protobuf::UnionMode::Sparse => UnionMode::Sparse,
};
let union_fields = parse_proto_fields_to_fields(&union.union_types)?;
let union_fields = if union.type_ids.is_empty() {
UnionFields::from_fields(union_fields)
} else {
let type_ids = union.type_ids.iter().map(|i| *i as i8);
UnionFields::try_new(type_ids, union_fields).map_err(|e| {
DataFusionError::from(e).context("Deserializing Union DataType")
})?
};
DataType::Union(union_fields, union_mode)
}
arrow_type::ArrowTypeEnum::Dictionary(dict) => {
let key_datatype = dict.as_ref().key.as_deref().required("key")?;
let value_datatype = dict.as_ref().value.as_deref().required("value")?;
DataType::Dictionary(Box::new(key_datatype), Box::new(value_datatype))
}
arrow_type::ArrowTypeEnum::Map(map) => {
let field: Field =
map.as_ref().field_type.as_deref().required("field_type")?;
let keys_sorted = map.keys_sorted;
DataType::Map(Arc::new(field), keys_sorted)
}
arrow_type::ArrowTypeEnum::RunEndEncoded(run_end_encoded) => {
let run_ends_field: Field = run_end_encoded
.as_ref()
.run_ends_field
.as_deref()
.required("run_ends_field")?;
let value_field: Field = run_end_encoded
.as_ref()
.values_field
.as_deref()
.required("values_field")?;
DataType::RunEndEncoded(run_ends_field.into(), value_field.into())
}
})
}
}
impl TryFrom<&protobuf::Field> for Field {
type Error = Error;
fn try_from(field: &protobuf::Field) -> Result<Self, Self::Error> {
let datatype = field.arrow_type.as_deref().required("arrow_type")?;
let field = Self::new(field.name.as_str(), datatype, field.nullable)
.with_metadata(field.metadata.clone());
Ok(field)
}
}
impl TryFrom<&protobuf::Schema> for Schema {
type Error = Error;
fn try_from(
schema: &protobuf::Schema,
) -> datafusion_common::Result<Self, Self::Error> {
let fields = schema
.columns
.iter()
.map(Field::try_from)
.collect::<datafusion_common::Result<Vec<_>, _>>()?;
Ok(Self::new_with_metadata(fields, schema.metadata.clone()))
}
}
impl TryFrom<&protobuf::ScalarValue> for ScalarValue {
type Error = Error;
fn try_from(
scalar: &protobuf::ScalarValue,
) -> datafusion_common::Result<Self, Self::Error> {
use protobuf::scalar_value::Value;
let value = scalar
.value
.as_ref()
.ok_or_else(|| Error::required("value"))?;
Ok(match value {
Value::BoolValue(v) => Self::Boolean(Some(*v)),
Value::Utf8Value(v) => Self::Utf8(Some(v.to_owned())),
Value::Utf8ViewValue(v) => Self::Utf8View(Some(v.to_owned())),
Value::LargeUtf8Value(v) => Self::LargeUtf8(Some(v.to_owned())),
Value::Int8Value(v) => Self::Int8(Some(*v as i8)),
Value::Int16Value(v) => Self::Int16(Some(*v as i16)),
Value::Int32Value(v) => Self::Int32(Some(*v)),
Value::Int64Value(v) => Self::Int64(Some(*v)),
Value::Uint8Value(v) => Self::UInt8(Some(*v as u8)),
Value::Uint16Value(v) => Self::UInt16(Some(*v as u16)),
Value::Uint32Value(v) => Self::UInt32(Some(*v)),
Value::Uint64Value(v) => Self::UInt64(Some(*v)),
Value::Float32Value(v) => Self::Float32(Some(*v)),
Value::Float64Value(v) => Self::Float64(Some(*v)),
Value::Date32Value(v) => Self::Date32(Some(*v)),
Value::ListValue(v)
| Value::FixedSizeListValue(v)
| Value::LargeListValue(v)
| Value::ListViewValue(v)
| Value::LargeListViewValue(v)
| Value::StructValue(v)
| Value::MapValue(v) => {
let protobuf::ScalarNestedValue {
ipc_message,
arrow_data,
dictionaries,
schema,
} = &v;
let schema: Schema = if let Some(schema_ref) = schema {
schema_ref.try_into()?
} else {
return Err(Error::General(
"Invalid schema while deserializing nested ScalarValue"
.to_string(),
));
};
let schema: Schema = {
let ipc_gen = IpcDataGenerator {};
let write_options = IpcWriteOptions::default();
let mut dict_tracker = DictionaryTracker::new(false);
let encoded_schema = ipc_gen.schema_to_bytes_with_dictionary_tracker(
&schema,
&mut dict_tracker,
&write_options,
);
let message =
root_as_message(encoded_schema.ipc_message.as_slice()).map_err(
|e| {
Error::General(format!(
"Error IPC schema message while deserializing nested ScalarValue: {e}"
))
},
)?;
let ipc_schema = message.header_as_schema().ok_or_else(|| {
Error::General(
"Unexpected message type deserializing nested ScalarValue schema"
.to_string(),
)
})?;
try_fb_to_schema(ipc_schema).map_err(|e| {
Error::General(format!(
"Error converting IPC schema while deserializing nested ScalarValue: {e}"
))
})?
};
let message = root_as_message(ipc_message.as_slice()).map_err(|e| {
Error::General(format!(
"Error IPC message while deserializing nested ScalarValue: {e}"
))
})?;
let buffer = Buffer::from(arrow_data.as_slice());
let ipc_batch = message.header_as_record_batch().ok_or_else(|| {
Error::General(
"Unexpected message type deserializing nested ScalarValue"
.to_string(),
)
})?;
let mut dict_by_id: HashMap<i64, ArrayRef> =
HashMap::with_capacity(dictionaries.len());
for protobuf::scalar_nested_value::Dictionary {
ipc_message,
arrow_data,
} in dictionaries
{
let message = root_as_message(ipc_message.as_slice()).map_err(|e| {
Error::General(format!(
"Error IPC message while deserializing nested ScalarValue dictionary message: {e}"
))
})?;
let buffer = Buffer::from(arrow_data.as_slice());
let dict_batch = message.header_as_dictionary_batch().ok_or_else(|| {
Error::General(
"Unexpected message type deserializing nested ScalarValue dictionary message"
.to_string(),
)
})?;
read_dictionary(
&buffer,
dict_batch,
&schema,
&mut dict_by_id,
&message.version(),
)
.map_err(|e| arrow_datafusion_err!(e))
.map_err(|e| e.context("Decoding nested ScalarValue dictionary"))?;
}
let record_batch = read_record_batch(
&buffer,
ipc_batch,
Arc::new(schema),
&dict_by_id,
None,
&message.version(),
)
.map_err(|e| arrow_datafusion_err!(e))
.map_err(|e| e.context("Decoding nested ScalarValue value"))?;
let arr = record_batch.column(0);
match value {
Value::ListValue(_) => {
Self::List(arr.as_list::<i32>().to_owned().into())
}
Value::LargeListValue(_) => {
Self::LargeList(arr.as_list::<i64>().to_owned().into())
}
Value::FixedSizeListValue(_) => {
Self::FixedSizeList(arr.as_fixed_size_list().to_owned().into())
}
Value::ListViewValue(_) => {
Self::ListView(arr.as_list_view::<i32>().to_owned().into())
}
Value::LargeListViewValue(_) => {
Self::LargeListView(arr.as_list_view::<i64>().to_owned().into())
}
Value::StructValue(_) => {
Self::Struct(arr.as_struct().to_owned().into())
}
Value::MapValue(_) => Self::Map(arr.as_map().to_owned().into()),
_ => unreachable!(),
}
}
Value::NullValue(v) => {
let null_type: DataType = v.try_into()?;
null_type.try_into().map_err(Error::DataFusionError)?
}
Value::Decimal32Value(val) => {
let array = vec_to_array(val.value.clone());
Self::Decimal32(Some(i32::from_be_bytes(array)), val.p as u8, val.s as i8)
}
Value::Decimal64Value(val) => {
let array = vec_to_array(val.value.clone());
Self::Decimal64(Some(i64::from_be_bytes(array)), val.p as u8, val.s as i8)
}
Value::Decimal128Value(val) => {
let array = vec_to_array(val.value.clone());
Self::Decimal128(
Some(i128::from_be_bytes(array)),
val.p as u8,
val.s as i8,
)
}
Value::Decimal256Value(val) => {
let array = vec_to_array(val.value.clone());
Self::Decimal256(
Some(i256::from_be_bytes(array)),
val.p as u8,
val.s as i8,
)
}
Value::Date64Value(v) => Self::Date64(Some(*v)),
Value::Time32Value(v) => {
let time_value =
v.value.as_ref().ok_or_else(|| Error::required("value"))?;
match time_value {
protobuf::scalar_time32_value::Value::Time32SecondValue(t) => {
Self::Time32Second(Some(*t))
}
protobuf::scalar_time32_value::Value::Time32MillisecondValue(t) => {
Self::Time32Millisecond(Some(*t))
}
}
}
Value::Time64Value(v) => {
let time_value =
v.value.as_ref().ok_or_else(|| Error::required("value"))?;
match time_value {
protobuf::scalar_time64_value::Value::Time64MicrosecondValue(t) => {
Self::Time64Microsecond(Some(*t))
}
protobuf::scalar_time64_value::Value::Time64NanosecondValue(t) => {
Self::Time64Nanosecond(Some(*t))
}
}
}
Value::IntervalYearmonthValue(v) => Self::IntervalYearMonth(Some(*v)),
Value::DurationSecondValue(v) => Self::DurationSecond(Some(*v)),
Value::DurationMillisecondValue(v) => Self::DurationMillisecond(Some(*v)),
Value::DurationMicrosecondValue(v) => Self::DurationMicrosecond(Some(*v)),
Value::DurationNanosecondValue(v) => Self::DurationNanosecond(Some(*v)),
Value::TimestampValue(v) => {
let timezone = if v.timezone.is_empty() {
None
} else {
Some(v.timezone.as_str().into())
};
let ts_value =
v.value.as_ref().ok_or_else(|| Error::required("value"))?;
match ts_value {
protobuf::scalar_timestamp_value::Value::TimeMicrosecondValue(t) => {
Self::TimestampMicrosecond(Some(*t), timezone)
}
protobuf::scalar_timestamp_value::Value::TimeNanosecondValue(t) => {
Self::TimestampNanosecond(Some(*t), timezone)
}
protobuf::scalar_timestamp_value::Value::TimeSecondValue(t) => {
Self::TimestampSecond(Some(*t), timezone)
}
protobuf::scalar_timestamp_value::Value::TimeMillisecondValue(t) => {
Self::TimestampMillisecond(Some(*t), timezone)
}
}
}
Value::DictionaryValue(v) => {
let index_type: DataType = v
.index_type
.as_ref()
.ok_or_else(|| Error::required("index_type"))?
.try_into()?;
let value: Self = v
.value
.as_ref()
.ok_or_else(|| Error::required("value"))?
.as_ref()
.try_into()?;
Self::Dictionary(Box::new(index_type), Box::new(value))
}
Value::RunEndEncodedValue(v) => {
let run_ends_field: Field = v
.run_ends_field
.as_ref()
.ok_or_else(|| Error::required("run_ends_field"))?
.try_into()?;
let values_field: Field = v
.values_field
.as_ref()
.ok_or_else(|| Error::required("values_field"))?
.try_into()?;
let value: Self = v
.value
.as_ref()
.ok_or_else(|| Error::required("value"))?
.as_ref()
.try_into()?;
Self::RunEndEncoded(
run_ends_field.into(),
values_field.into(),
Box::new(value),
)
}
Value::BinaryValue(v) => Self::Binary(Some(v.clone())),
Value::BinaryViewValue(v) => Self::BinaryView(Some(v.clone())),
Value::LargeBinaryValue(v) => Self::LargeBinary(Some(v.clone())),
Value::IntervalDaytimeValue(v) => Self::IntervalDayTime(Some(
IntervalDayTimeType::make_value(v.days, v.milliseconds),
)),
Value::IntervalMonthDayNano(v) => Self::IntervalMonthDayNano(Some(
IntervalMonthDayNanoType::make_value(v.months, v.days, v.nanos),
)),
Value::UnionValue(val) => {
let mode = match val.mode {
0 => UnionMode::Sparse,
1 => UnionMode::Dense,
id => Err(Error::unknown("UnionMode", id))?,
};
let ids = val
.fields
.iter()
.map(|f| f.field_id as i8)
.collect::<Vec<_>>();
let fields = val
.fields
.iter()
.map(|f| f.field.clone())
.collect::<Option<Vec<_>>>();
let fields = fields.ok_or_else(|| Error::required("UnionField"))?;
let fields = parse_proto_fields_to_fields(&fields)?;
let union_fields = UnionFields::try_new(ids, fields).map_err(|e| {
DataFusionError::from(e).context("Deserializing Union ScalarValue")
})?;
let v_id = val.value_id as i8;
let val = match &val.value {
None => None,
Some(val) => {
let val: ScalarValue = val
.as_ref()
.try_into()
.map_err(|_| Error::General("Invalid Scalar".to_string()))?;
Some((v_id, Box::new(val)))
}
};
Self::Union(val, union_fields, mode)
}
Value::FixedSizeBinaryValue(v) => {
Self::FixedSizeBinary(v.length, Some(v.clone().values))
}
})
}
}
impl From<protobuf::TimeUnit> for TimeUnit {
fn from(time_unit: protobuf::TimeUnit) -> Self {
match time_unit {
protobuf::TimeUnit::Second => TimeUnit::Second,
protobuf::TimeUnit::Millisecond => TimeUnit::Millisecond,
protobuf::TimeUnit::Microsecond => TimeUnit::Microsecond,
protobuf::TimeUnit::Nanosecond => TimeUnit::Nanosecond,
}
}
}
impl From<protobuf::IntervalUnit> for IntervalUnit {
fn from(interval_unit: protobuf::IntervalUnit) -> Self {
match interval_unit {
protobuf::IntervalUnit::YearMonth => IntervalUnit::YearMonth,
protobuf::IntervalUnit::DayTime => IntervalUnit::DayTime,
protobuf::IntervalUnit::MonthDayNano => IntervalUnit::MonthDayNano,
}
}
}
impl TryFrom<protobuf::Constraints> for Constraints {
type Error = DataFusionError;
fn try_from(
constraints: protobuf::Constraints,
) -> datafusion_common::Result<Self, Self::Error> {
Self::try_from(&constraints)
}
}
impl TryFrom<protobuf::Constraint> for Constraint {
type Error = DataFusionError;
fn try_from(
value: protobuf::Constraint,
) -> datafusion_common::Result<Self, Self::Error> {
Constraint::try_from(&value)
}
}
impl From<&protobuf::ColumnStats> for ColumnStatistics {
fn from(cs: &protobuf::ColumnStats) -> ColumnStatistics {
ColumnStatistics {
null_count: if let Some(nc) = &cs.null_count {
nc.clone().into()
} else {
Precision::Absent
},
max_value: if let Some(max) = &cs.max_value {
max.clone().into()
} else {
Precision::Absent
},
min_value: if let Some(min) = &cs.min_value {
min.clone().into()
} else {
Precision::Absent
},
sum_value: if let Some(sum) = &cs.sum_value {
sum.clone().into()
} else {
Precision::Absent
},
distinct_count: if let Some(dc) = &cs.distinct_count {
dc.clone().into()
} else {
Precision::Absent
},
byte_size: if let Some(sbs) = &cs.byte_size {
sbs.clone().into()
} else {
Precision::Absent
},
}
}
}
impl From<protobuf::Precision> for Precision<usize> {
fn from(s: protobuf::Precision) -> Self {
let Ok(precision_type) = s.precision_info.try_into() else {
return Precision::Absent;
};
match precision_type {
protobuf::PrecisionInfo::Exact => {
if let Some(val) = s.val {
if let Ok(ScalarValue::UInt64(Some(val))) =
ScalarValue::try_from(&val)
{
usize::try_from(val).map_or(Precision::Absent, Precision::Exact)
} else {
Precision::Absent
}
} else {
Precision::Absent
}
}
protobuf::PrecisionInfo::Inexact => {
if let Some(val) = s.val {
if let Ok(ScalarValue::UInt64(Some(val))) =
ScalarValue::try_from(&val)
{
usize::try_from(val).map_or(Precision::Absent, Precision::Inexact)
} else {
Precision::Absent
}
} else {
Precision::Absent
}
}
protobuf::PrecisionInfo::Absent => Precision::Absent,
}
}
}
impl From<protobuf::Precision> for Precision<ScalarValue> {
fn from(s: protobuf::Precision) -> Self {
let Ok(precision_type) = s.precision_info.try_into() else {
return Precision::Absent;
};
match precision_type {
protobuf::PrecisionInfo::Exact => {
if let Some(val) = s.val {
if let Ok(val) = ScalarValue::try_from(&val) {
Precision::Exact(val)
} else {
Precision::Absent
}
} else {
Precision::Absent
}
}
protobuf::PrecisionInfo::Inexact => {
if let Some(val) = s.val {
if let Ok(val) = ScalarValue::try_from(&val) {
Precision::Inexact(val)
} else {
Precision::Absent
}
} else {
Precision::Absent
}
}
protobuf::PrecisionInfo::Absent => Precision::Absent,
}
}
}
impl From<protobuf::JoinSide> for JoinSide {
fn from(t: protobuf::JoinSide) -> Self {
match t {
protobuf::JoinSide::LeftSide => JoinSide::Left,
protobuf::JoinSide::RightSide => JoinSide::Right,
protobuf::JoinSide::None => JoinSide::None,
}
}
}
impl TryFrom<&protobuf::Constraint> for Constraint {
type Error = DataFusionError;
fn try_from(
value: &protobuf::Constraint,
) -> datafusion_common::Result<Self, Self::Error> {
let decode_indices = |indices: &[u64]| {
indices
.iter()
.map(|&index| usize_from_wire(index, "Constraint", "indices"))
.collect::<datafusion_common::Result<Vec<_>>>()
};
match &value.constraint_mode {
Some(protobuf::constraint::ConstraintMode::PrimaryKey(elem)) => {
Ok(Constraint::PrimaryKey(decode_indices(&elem.indices)?))
}
Some(protobuf::constraint::ConstraintMode::Unique(elem)) => {
Ok(Constraint::Unique(decode_indices(&elem.indices)?))
}
None => Err(plan_datafusion_err!(
"Constraint: missing required field 'constraint_mode'"
)),
}
}
}
impl TryFrom<&protobuf::Constraints> for Constraints {
type Error = DataFusionError;
fn try_from(
constraints: &protobuf::Constraints,
) -> datafusion_common::Result<Self, Self::Error> {
Ok(Constraints::new_unverified(
constraints
.constraints
.iter()
.map(Constraint::try_from)
.collect::<datafusion_common::Result<Vec<_>>>()?,
))
}
}
impl TryFrom<&protobuf::Statistics> for Statistics {
type Error = DataFusionError;
fn try_from(
s: &protobuf::Statistics,
) -> datafusion_common::Result<Self, Self::Error> {
Ok(Statistics {
num_rows: if let Some(nr) = &s.num_rows {
nr.clone().into()
} else {
Precision::Absent
},
total_byte_size: if let Some(tbs) = &s.total_byte_size {
tbs.clone().into()
} else {
Precision::Absent
},
column_statistics: s.column_stats.iter().map(|s| s.into()).collect(),
})
}
}
impl From<protobuf::CompressionTypeVariant> for CompressionTypeVariant {
fn from(value: protobuf::CompressionTypeVariant) -> Self {
match value {
protobuf::CompressionTypeVariant::Gzip => Self::GZIP,
protobuf::CompressionTypeVariant::Bzip2 => Self::BZIP2,
protobuf::CompressionTypeVariant::Xz => Self::XZ,
protobuf::CompressionTypeVariant::Zstd => Self::ZSTD,
protobuf::CompressionTypeVariant::Uncompressed => Self::UNCOMPRESSED,
}
}
}
impl From<CompressionTypeVariant> for protobuf::CompressionTypeVariant {
fn from(value: CompressionTypeVariant) -> Self {
match value {
CompressionTypeVariant::GZIP => Self::Gzip,
CompressionTypeVariant::BZIP2 => Self::Bzip2,
CompressionTypeVariant::XZ => Self::Xz,
CompressionTypeVariant::ZSTD => Self::Zstd,
CompressionTypeVariant::UNCOMPRESSED => Self::Uncompressed,
}
}
}
impl From<protobuf::CsvQuoteStyle> for datafusion_common::parsers::CsvQuoteStyle {
fn from(value: protobuf::CsvQuoteStyle) -> Self {
match value {
protobuf::CsvQuoteStyle::Necessary => Self::Necessary,
protobuf::CsvQuoteStyle::Always => Self::Always,
protobuf::CsvQuoteStyle::NonNumeric => Self::NonNumeric,
protobuf::CsvQuoteStyle::Never => Self::Never,
}
}
}
impl TryFrom<&protobuf::CsvWriterOptions> for CsvWriterOptions {
type Error = DataFusionError;
fn try_from(
opts: &protobuf::CsvWriterOptions,
) -> datafusion_common::Result<Self, Self::Error> {
let protobuf::CsvWriterOptions {
compression,
delimiter,
has_header,
date_format,
datetime_format,
timestamp_format,
time_format,
null_value,
quote,
escape,
double_quote,
quote_style,
ignore_leading_whitespace,
ignore_trailing_whitespace,
compression_level,
timestamp_tz_format,
terminator,
} = opts;
let mut writer_options = WriterBuilder::new();
if !delimiter.is_empty() {
if let Some(delimiter) = delimiter.chars().next() {
if delimiter.is_ascii() {
writer_options = writer_options.with_delimiter(delimiter as u8);
} else {
return Err(proto_error("CSV Delimiter is not ASCII"));
}
} else {
return Err(proto_error("Error parsing CSV Delimiter"));
}
}
if !quote.is_empty() {
if let Some(quote) = quote.chars().next() {
if quote.is_ascii() {
writer_options = writer_options.with_quote(quote as u8);
} else {
return Err(proto_error("CSV Quote is not ASCII"));
}
} else {
return Err(proto_error("Error parsing CSV Quote"));
}
}
if !escape.is_empty() {
if let Some(escape) = escape.chars().next() {
if escape.is_ascii() {
writer_options = writer_options.with_escape(escape as u8);
} else {
return Err(proto_error("CSV Escape is not ASCII"));
}
} else {
return Err(proto_error("Error parsing CSV Escape"));
}
}
let quote_style = match protobuf::CsvQuoteStyle::try_from(*quote_style) {
Ok(protobuf::CsvQuoteStyle::Always) => QuoteStyle::Always,
Ok(protobuf::CsvQuoteStyle::NonNumeric) => QuoteStyle::NonNumeric,
Ok(protobuf::CsvQuoteStyle::Never) => QuoteStyle::Never,
Ok(protobuf::CsvQuoteStyle::Necessary) => QuoteStyle::Necessary,
_ => {
return Err(proto_error(
"Unknown quote style, must be one of: 'Always', 'NonNumeric', 'Never', 'Necessary'",
));
}
};
writer_options = writer_options
.with_header(*has_header)
.with_null(null_value.clone())
.with_double_quote(*double_quote)
.with_quote_style(quote_style)
.with_ignore_leading_whitespace(*ignore_leading_whitespace)
.with_ignore_trailing_whitespace(*ignore_trailing_whitespace);
if let Some(date_format) = date_format {
writer_options = writer_options.with_date_format(date_format.clone());
}
if let Some(datetime_format) = datetime_format {
writer_options = writer_options.with_datetime_format(datetime_format.clone());
}
if let Some(timestamp_format) = timestamp_format {
writer_options =
writer_options.with_timestamp_format(timestamp_format.clone());
}
if let Some(timestamp_tz_format) = timestamp_tz_format {
writer_options =
writer_options.with_timestamp_tz_format(timestamp_tz_format.clone());
}
if let Some(time_format) = time_format {
writer_options = writer_options.with_time_format(time_format.clone());
}
writer_options = match terminator.as_slice() {
[] => writer_options,
[byte] => writer_options.with_line_terminator(Terminator::Any(*byte)),
[b'\r', b'\n'] => writer_options.with_line_terminator(Terminator::CRLF),
_ => {
return Err(proto_error("CSV line terminator must be one byte or CRLF"));
}
};
let compression = protobuf::CompressionTypeVariant::try_from(*compression)
.unwrap_or_default()
.into();
Ok(CsvWriterOptions {
writer_options,
compression,
compression_level: *compression_level,
})
}
}
impl TryFrom<&protobuf::JsonWriterOptions> for JsonWriterOptions {
type Error = DataFusionError;
fn try_from(
opts: &protobuf::JsonWriterOptions,
) -> datafusion_common::Result<Self, Self::Error> {
let protobuf::JsonWriterOptions {
compression,
compression_level,
} = opts;
let compression: CompressionTypeVariant =
protobuf::CompressionTypeVariant::try_from(*compression)
.unwrap_or_default()
.into();
Ok(JsonWriterOptions {
compression,
compression_level: *compression_level,
})
}
}
impl TryFrom<&protobuf::CsvOptions> for CsvOptions {
type Error = DataFusionError;
fn try_from(
proto_opts: &protobuf::CsvOptions,
) -> datafusion_common::Result<Self, Self::Error> {
Ok(CsvOptions {
has_header: proto_opts.has_header.first().map(|h| *h != 0),
delimiter: proto_opts.delimiter[0],
quote: proto_opts.quote[0],
terminator: proto_opts.terminator.first().copied(),
escape: proto_opts.escape.first().copied(),
double_quote: proto_opts.double_quote.first().map(|h| *h != 0),
newlines_in_values: proto_opts.newlines_in_values.first().map(|h| *h != 0),
compression: proto_opts.compression().into(),
compression_level: proto_opts.compression_level,
schema_infer_max_rec: proto_opts
.schema_infer_max_rec
.map(|v| usize_from_wire(v, "CsvOptions", "schema_infer_max_rec"))
.transpose()?,
date_format: (!proto_opts.date_format.is_empty())
.then(|| proto_opts.date_format.clone()),
datetime_format: (!proto_opts.datetime_format.is_empty())
.then(|| proto_opts.datetime_format.clone()),
timestamp_format: (!proto_opts.timestamp_format.is_empty())
.then(|| proto_opts.timestamp_format.clone()),
timestamp_tz_format: (!proto_opts.timestamp_tz_format.is_empty())
.then(|| proto_opts.timestamp_tz_format.clone()),
time_format: (!proto_opts.time_format.is_empty())
.then(|| proto_opts.time_format.clone()),
null_value: (!proto_opts.null_value.is_empty())
.then(|| proto_opts.null_value.clone()),
null_regex: (!proto_opts.null_regex.is_empty())
.then(|| proto_opts.null_regex.clone()),
comment: proto_opts.comment.first().copied(),
truncated_rows: proto_opts.truncated_rows.first().map(|h| *h != 0),
quote_style: proto_opts.quote_style().into(),
ignore_leading_whitespace: proto_opts
.ignore_leading_whitespace
.first()
.map(|h| *h != 0),
ignore_trailing_whitespace: proto_opts
.ignore_trailing_whitespace
.first()
.map(|h| *h != 0),
})
}
}
impl TryFrom<&protobuf::ParquetOptions> for ParquetOptions {
type Error = DataFusionError;
fn try_from(
value: &protobuf::ParquetOptions,
) -> datafusion_common::Result<Self, Self::Error> {
let to_usize =
|value: u64, field: &str| usize_from_wire(value, "ParquetOptions", field);
Ok(ParquetOptions {
enable_page_index: value.enable_page_index,
pruning: value.pruning,
skip_metadata: value.skip_metadata,
metadata_size_hint: value
.metadata_size_hint_opt
.map(|opt| match opt {
protobuf::parquet_options::MetadataSizeHintOpt::MetadataSizeHint(v) => {
to_usize(v, "metadata_size_hint")
}
})
.transpose()?,
pushdown_filters: value.pushdown_filters,
reorder_filters: value.reorder_filters,
force_filter_selections: value.force_filter_selections,
data_pagesize_limit: to_usize(
value.data_pagesize_limit,
"data_pagesize_limit",
)?,
write_batch_size: to_usize(value.write_batch_size, "write_batch_size")?,
writer_version: value.writer_version.parse().map_err(|e| {
DataFusionError::Internal(format!("Failed to parse writer_version: {e}"))
})?,
compression: value.compression_opt.as_ref().map(|opt| match opt {
protobuf::parquet_options::CompressionOpt::Compression(v) => v.parse(),
}).transpose()?,
dictionary_enabled: value.dictionary_enabled_opt.as_ref().map(|protobuf::parquet_options::DictionaryEnabledOpt::DictionaryEnabled(v)| *v),
dictionary_page_size_limit: to_usize(
value.dictionary_page_size_limit,
"dictionary_page_size_limit",
)?,
statistics_enabled: value
.statistics_enabled_opt.as_ref()
.map(|opt| match opt {
protobuf::parquet_options::StatisticsEnabledOpt::StatisticsEnabled(v) => v.parse(),
})
.transpose()?,
max_row_group_size: to_usize(value.max_row_group_size, "max_row_group_size")?,
max_in_list_size: to_usize(value.max_in_list_size, "max_in_list_size")?,
row_group_range_assignment: RowGroupRangeAssignment::from_proto_str(
&value.row_group_range_assignment,
)?,
created_by: value.created_by.clone(),
column_index_truncate_length: value
.column_index_truncate_length_opt.as_ref()
.map(|opt| match opt {
protobuf::parquet_options::ColumnIndexTruncateLengthOpt::ColumnIndexTruncateLength(v) => {
to_usize(*v, "column_index_truncate_length")
}
})
.transpose()?,
statistics_truncate_length: value
.statistics_truncate_length_opt.as_ref()
.map(|opt| match opt {
protobuf::parquet_options::StatisticsTruncateLengthOpt::StatisticsTruncateLength(v) => {
to_usize(*v, "statistics_truncate_length")
}
})
.transpose()?,
data_page_row_count_limit: to_usize(
value.data_page_row_count_limit,
"data_page_row_count_limit",
)?,
encoding: value
.encoding_opt
.as_ref()
.map(|opt| match opt {
protobuf::parquet_options::EncodingOpt::Encoding(v) => v.parse(),
})
.transpose()?,
bloom_filter_on_read: value.bloom_filter_on_read,
bloom_filter_on_write: value.bloom_filter_on_write,
bloom_filter_fpp: value.clone()
.bloom_filter_fpp_opt
.map(|opt| match opt {
protobuf::parquet_options::BloomFilterFppOpt::BloomFilterFpp(v) => Some(v),
})
.unwrap_or(None),
bloom_filter_ndv: value.clone()
.bloom_filter_ndv_opt
.map(|opt| match opt {
protobuf::parquet_options::BloomFilterNdvOpt::BloomFilterNdv(v) => Some(v),
})
.unwrap_or(None),
allow_single_file_parallelism: value.allow_single_file_parallelism,
maximum_parallel_row_group_writers: to_usize(
value.maximum_parallel_row_group_writers,
"maximum_parallel_row_group_writers",
)?,
maximum_buffered_record_batches_per_stream: to_usize(
value.maximum_buffered_record_batches_per_stream,
"maximum_buffered_record_batches_per_stream",
)?,
schema_force_view_types: value.schema_force_view_types,
binary_as_string: value.binary_as_string,
coerce_int96: value.coerce_int96_opt.as_ref().map(|opt| match opt {
protobuf::parquet_options::CoerceInt96Opt::CoerceInt96(v) => v.parse(),
}).transpose()?,
coerce_int96_tz: value.coerce_int96_tz_opt.as_ref().map(|opt| match opt {
protobuf::parquet_options::CoerceInt96TzOpt::CoerceInt96Tz(v) => v.parse(),
}).transpose()?,
skip_arrow_metadata: value.skip_arrow_metadata,
write_row_group_number_distinct_values: value.write_row_group_number_distinct_values,
max_predicate_cache_size: value.max_predicate_cache_size_opt.map(|opt| match opt {
protobuf::parquet_options::MaxPredicateCacheSizeOpt::MaxPredicateCacheSize(v) => {
to_usize(v, "max_predicate_cache_size")
}
}).transpose()?,
max_row_group_bytes: value.max_row_group_bytes_opt.map(|opt| match opt {
protobuf::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(v) => {
MaxRowGroupBytes::try_new(to_usize(v, "max_row_group_bytes")?)
}
}).transpose()?,
content_defined_chunking: value.content_defined_chunking.map(ParquetCdcOptions::try_from).transpose()?.unwrap_or_default(),
enable_rle_to_dictionary: value.enable_rle_to_dictionary,
})
}
}
impl TryFrom<protobuf::ParquetCdcOptions> for ParquetCdcOptions {
type Error = DataFusionError;
fn try_from(
value: protobuf::ParquetCdcOptions,
) -> datafusion_common::Result<Self, Self::Error> {
let to_usize =
|value: u64, field: &str| usize_from_wire(value, "ParquetCdcOptions", field);
Ok(ParquetCdcOptions {
enabled: value.enabled,
min_chunk_size: to_usize(value.min_chunk_size, "min_chunk_size")?,
max_chunk_size: to_usize(value.max_chunk_size, "max_chunk_size")?,
norm_level: value.norm_level,
})
}
}
impl TryFrom<&protobuf::ParquetColumnOptions> for ParquetColumnOptions {
type Error = DataFusionError;
fn try_from(
value: &protobuf::ParquetColumnOptions,
) -> datafusion_common::Result<Self, Self::Error> {
Ok(ParquetColumnOptions {
compression: value.compression_opt.clone().map(|opt| match opt {
protobuf::parquet_column_options::CompressionOpt::Compression(v) => Some(v),
}).unwrap_or(None),
dictionary_enabled: value.dictionary_enabled_opt.as_ref().map(|protobuf::parquet_column_options::DictionaryEnabledOpt::DictionaryEnabled(v)| *v),
statistics_enabled: value
.statistics_enabled_opt.clone()
.map(|opt| match opt {
protobuf::parquet_column_options::StatisticsEnabledOpt::StatisticsEnabled(v) => Some(v),
})
.unwrap_or(None),
encoding: value
.encoding_opt.clone()
.map(|opt| match opt {
protobuf::parquet_column_options::EncodingOpt::Encoding(v) => Some(v),
})
.unwrap_or(None),
bloom_filter_enabled: value.bloom_filter_enabled_opt.map(|opt| match opt {
protobuf::parquet_column_options::BloomFilterEnabledOpt::BloomFilterEnabled(v) => Some(v),
})
.unwrap_or(None),
bloom_filter_fpp: value
.bloom_filter_fpp_opt
.map(|opt| match opt {
protobuf::parquet_column_options::BloomFilterFppOpt::BloomFilterFpp(v) => Some(v),
})
.unwrap_or(None),
bloom_filter_ndv: value
.bloom_filter_ndv_opt
.map(|opt| match opt {
protobuf::parquet_column_options::BloomFilterNdvOpt::BloomFilterNdv(v) => Some(v),
})
.unwrap_or(None),
})
}
}
impl TryFrom<&protobuf::TableParquetOptions> for TableParquetOptions {
type Error = DataFusionError;
fn try_from(
value: &protobuf::TableParquetOptions,
) -> datafusion_common::Result<Self, Self::Error> {
let mut column_specific_options: HashMap<String, ParquetColumnOptions> =
HashMap::with_capacity(value.column_specific_options.len());
for protobuf::ParquetColumnSpecificOptions {
column_name,
options: maybe_options,
} in &value.column_specific_options
{
if let Some(options) = maybe_options {
column_specific_options.insert(column_name.clone(), options.try_into()?);
}
}
let opts = TableParquetOptions {
global: value
.global
.as_ref()
.map(ParquetOptions::try_from)
.transpose()?
.unwrap_or_default(),
column_specific_options,
..Default::default()
};
Ok(opts)
}
}
impl TryFrom<&protobuf::JsonOptions> for JsonOptions {
type Error = DataFusionError;
fn try_from(
proto_opts: &protobuf::JsonOptions,
) -> datafusion_common::Result<Self, Self::Error> {
let compression: protobuf::CompressionTypeVariant = proto_opts.compression();
Ok(JsonOptions {
compression: compression.into(),
compression_level: proto_opts.compression_level,
schema_infer_max_rec: proto_opts
.schema_infer_max_rec
.map(|v| usize_from_wire(v, "JsonOptions", "schema_infer_max_rec"))
.transpose()?,
newline_delimited: proto_opts.newline_delimited.unwrap_or(true),
})
}
}
pub fn parse_i32_to_time_unit(value: &i32) -> datafusion_common::Result<TimeUnit, Error> {
protobuf::TimeUnit::try_from(*value)
.map(|t| t.into())
.map_err(|_| Error::unknown("TimeUnit", *value))
}
pub fn parse_i32_to_interval_unit(
value: &i32,
) -> datafusion_common::Result<IntervalUnit, Error> {
protobuf::IntervalUnit::try_from(*value)
.map(|t| t.into())
.map_err(|_| Error::unknown("IntervalUnit", *value))
}
fn vec_to_array<T, const N: usize>(v: Vec<T>) -> [T; N] {
v.try_into().unwrap_or_else(|v: Vec<T>| {
panic!("Expected a Vec of length {} but it was {}", N, v.len())
})
}
pub fn parse_proto_fields_to_fields<'a, I>(fields: I) -> Result<Vec<Field>, Error>
where
I: IntoIterator<Item = &'a protobuf::Field>,
{
fields
.into_iter()
.map(Field::try_from)
.collect::<datafusion_common::Result<_, _>>()
}
#[cfg(test)]
mod tests {
use datafusion_common::TableReference;
use datafusion_common::config::{
MaxRowGroupBytes, ParquetCdcOptions, ParquetOptions, TableParquetOptions,
};
use datafusion_common::parquet_config::{
DFParquetCompression, DFParquetEncoding, DFParquetStatistics, DFTimeUnit,
RowGroupRangeAssignment,
};
#[test]
fn constraint_requires_mode() {
let err = datafusion_common::Constraint::try_from(
&crate::protobuf_common::Constraint {
constraint_mode: None,
},
)
.unwrap_err();
assert!(
err.to_string()
.contains("Constraint: missing required field 'constraint_mode'")
);
}
#[test]
fn column_relation_round_trip_preserves_dotted_bare_table() {
let column = datafusion_common::Column::new(
Some(TableReference::bare("has.dot")),
"column",
);
let proto: crate::protobuf_common::Column = (&column).into();
let relation = proto.relation.expect("relation should be present");
assert_eq!(relation.relation, "has.dot");
assert_eq!(relation.parts, vec!["has.dot".to_string()]);
let recovered = TableReference::from(relation);
assert_eq!(recovered, TableReference::bare("has.dot"));
}
#[test]
fn column_relation_round_trip_preserves_dotted_partial_reference() {
let column = datafusion_common::Column::new(
Some(TableReference::partial("my.schema", "table")),
"column",
);
let proto: crate::protobuf_common::Column = (&column).into();
let relation = proto.relation.expect("relation should be present");
assert_eq!(relation.relation, "my.schema.table");
assert_eq!(
relation.parts,
vec!["my.schema".to_string(), "table".to_string()]
);
let recovered = TableReference::from(relation);
assert_eq!(recovered, TableReference::partial("my.schema", "table"));
}
#[test]
fn column_relation_round_trip_preserves_dotted_full_reference() {
let column = datafusion_common::Column::new(
Some(TableReference::full("catalog", "my.schema", "table")),
"column",
);
let proto: crate::protobuf_common::Column = (&column).into();
let relation = proto.relation.expect("relation should be present");
assert_eq!(relation.relation, "catalog.my.schema.table");
assert_eq!(
relation.parts,
vec![
"catalog".to_string(),
"my.schema".to_string(),
"table".to_string()
]
);
let recovered = TableReference::from(relation);
assert_eq!(
recovered,
TableReference::full("catalog", "my.schema", "table")
);
}
#[test]
fn df_schema_round_trip_preserves_dotted_qualifiers() {
use std::sync::Arc;
use datafusion_common::DFSchema;
use datafusion_common::arrow::datatypes::{DataType, Field};
let schema = DFSchema::new_with_metadata(
vec![
(
Some(TableReference::partial("my.schema", "table")),
Arc::new(Field::new("partial_col", DataType::Utf8, true)),
),
(
Some(TableReference::full("catalog", "my.schema", "table")),
Arc::new(Field::new("full_col", DataType::Utf8, true)),
),
],
std::collections::HashMap::<String, String>::new(),
)
.unwrap();
let proto: crate::protobuf_common::DfSchema = (&schema).try_into().unwrap();
let recovered = DFSchema::try_from(&proto).unwrap();
let qualifiers = recovered
.iter()
.map(|(qualifier, _)| qualifier.cloned())
.collect::<Vec<_>>();
assert_eq!(
qualifiers,
vec![
Some(TableReference::partial("my.schema", "table")),
Some(TableReference::full("catalog", "my.schema", "table")),
]
);
}
#[test]
fn column_relation_decodes_legacy_relation() {
let proto = crate::protobuf_common::ColumnRelation {
relation: "schema.table".to_string(),
parts: vec![],
};
let recovered = TableReference::from(proto);
assert_eq!(recovered, TableReference::partial("schema", "table"));
}
#[test]
fn table_parquet_options_defaults_missing_global() {
let recovered = TableParquetOptions::try_from(
&crate::protobuf_common::TableParquetOptions::default(),
)
.expect("missing global should use defaults");
assert_eq!(recovered, TableParquetOptions::default());
}
#[test]
fn table_parquet_options_checks_nested_usize_conversion() {
let proto = crate::protobuf_common::TableParquetOptions {
global: Some(crate::protobuf_common::ParquetOptions {
data_pagesize_limit: u64::MAX,
writer_version: "1.0".to_string(),
..Default::default()
}),
..Default::default()
};
let recovered = TableParquetOptions::try_from(&proto);
if usize::BITS >= u64::BITS {
assert_eq!(recovered.unwrap().global.data_pagesize_limit, usize::MAX);
} else {
assert_eq!(
recovered.unwrap_err().strip_backtrace(),
"Error during planning: ParquetOptions: data_pagesize_limit wire value 18446744073709551615 is out of range for usize"
);
}
}
#[test]
fn table_parquet_options_propagates_nested_conversion_error() {
let proto = crate::protobuf_common::TableParquetOptions {
global: Some(crate::protobuf_common::ParquetOptions {
writer_version: "1.0".to_string(),
max_row_group_bytes_opt: Some(
crate::protobuf_common::parquet_options::MaxRowGroupBytesOpt::MaxRowGroupBytes(0),
),
..Default::default()
}),
..Default::default()
};
let err = TableParquetOptions::try_from(&proto).unwrap_err();
assert_eq!(
err.strip_backtrace(),
"Invalid or Unsupported Configuration: max_row_group_bytes must be greater than 0"
);
}
fn parquet_options_proto_round_trip(opts: ParquetOptions) -> ParquetOptions {
let proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
ParquetOptions::try_from(&proto).expect("from_proto")
}
fn table_parquet_options_proto_round_trip(
opts: TableParquetOptions,
) -> TableParquetOptions {
let proto: crate::protobuf_common::TableParquetOptions =
(&opts).try_into().expect("to_proto");
TableParquetOptions::try_from(&proto).expect("from_proto")
}
#[test]
fn test_parquet_options_cdc_disabled_round_trip() {
let opts = ParquetOptions::default();
assert!(!opts.content_defined_chunking.enabled);
let recovered = parquet_options_proto_round_trip(opts.clone());
assert_eq!(opts, recovered);
}
#[test]
fn test_parquet_options_coerce_int96_tz_unset_round_trip() {
let opts = ParquetOptions::default();
assert!(opts.coerce_int96_tz.is_none());
let recovered = parquet_options_proto_round_trip(opts.clone());
assert_eq!(recovered.coerce_int96_tz, None);
}
#[test]
fn test_parquet_options_coerce_int96_tz_without_unit_round_trip() {
let opts = ParquetOptions {
coerce_int96_tz: Some("+08".parse().unwrap()),
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts.clone());
assert_eq!(recovered.coerce_int96, None);
assert_eq!(recovered.coerce_int96_tz, opts.coerce_int96_tz);
}
#[test]
fn test_parquet_options_coerce_int96_tz_set_round_trip() {
let opts = ParquetOptions {
coerce_int96: Some(DFTimeUnit::Microsecond),
coerce_int96_tz: Some("UTC".parse().unwrap()),
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts.clone());
assert_eq!(recovered.coerce_int96, Some(DFTimeUnit::Microsecond));
assert_eq!(recovered.coerce_int96_tz, opts.coerce_int96_tz);
}
#[test]
fn test_parquet_options_row_group_range_assignment_round_trip() {
let opts = ParquetOptions {
row_group_range_assignment: RowGroupRangeAssignment::Midpoint,
..ParquetOptions::default()
};
let mut proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
assert_eq!(ParquetOptions::try_from(&proto).unwrap(), opts);
proto.row_group_range_assignment.clear();
assert_eq!(
ParquetOptions::try_from(&proto).unwrap(),
ParquetOptions::default()
);
}
#[test]
fn test_parquet_statistics_round_trip() {
let opts = ParquetOptions {
statistics_enabled: Some(DFParquetStatistics::Chunk),
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts);
assert_eq!(
recovered.statistics_enabled,
Some(DFParquetStatistics::Chunk)
);
}
#[test]
fn test_parquet_compression_round_trip() {
let opts = ParquetOptions {
compression: Some(DFParquetCompression::Gzip(6)),
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts);
assert_eq!(recovered.compression, Some(DFParquetCompression::Gzip(6)));
}
#[test]
fn test_parquet_encoding_round_trip() {
for encoding in [
None,
Some(DFParquetEncoding::ByteStreamSplit),
Some(DFParquetEncoding::Alp),
] {
let opts = ParquetOptions {
encoding,
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts);
assert_eq!(recovered.encoding, encoding);
}
}
#[test]
fn test_invalid_parquet_encoding_rejected_from_proto() {
let opts = ParquetOptions::default();
let mut proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
proto.encoding_opt = Some(
crate::protobuf_common::parquet_options::EncodingOpt::Encoding(
"invalid".to_string(),
),
);
let err = ParquetOptions::try_from(&proto).unwrap_err();
assert!(
err.to_string()
.contains("Unknown or unsupported parquet encoding: invalid"),
"unexpected error: {err}"
);
}
#[test]
fn test_invalid_parquet_compression_rejected_from_proto() {
let opts = ParquetOptions::default();
let mut proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
proto.compression_opt = Some(
crate::protobuf_common::parquet_options::CompressionOpt::Compression(
"zstd".to_string(),
),
);
let err = ParquetOptions::try_from(&proto).unwrap_err();
assert!(
err.to_string()
.contains("zstd compression requires specifying a level such as zstd(4)"),
"unexpected error: {err}"
);
}
#[test]
fn test_invalid_parquet_coerce_int96_tz_rejected_from_proto() {
let opts = ParquetOptions::default();
let mut proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
proto.coerce_int96_tz_opt = Some(
crate::protobuf_common::parquet_options::CoerceInt96TzOpt::CoerceInt96Tz(
"Not/A_Timezone".to_string(),
),
);
let err = ParquetOptions::try_from(&proto).unwrap_err();
assert!(
err.to_string()
.contains("Invalid time zone: Not/A_Timezone."),
"unexpected error: {err}"
);
}
#[test]
fn test_invalid_parquet_coerce_int96_rejected_from_proto() {
let opts = ParquetOptions::default();
let mut proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
proto.coerce_int96_opt = Some(
crate::protobuf_common::parquet_options::CoerceInt96Opt::CoerceInt96(
"nanos".to_string(),
),
);
let err = ParquetOptions::try_from(&proto).unwrap_err();
assert!(
err.to_string().contains(
"Invalid parquet coerce_int96 setting: nanos. Expected one of: ns, us, ms, s"
),
"unexpected error: {err}"
);
}
#[test]
fn test_invalid_parquet_statistics_rejected_from_proto() {
let opts = ParquetOptions::default();
let mut proto: crate::protobuf_common::ParquetOptions =
(&opts).try_into().expect("to_proto");
proto.statistics_enabled_opt = Some(
crate::protobuf_common::parquet_options::StatisticsEnabledOpt::StatisticsEnabled(
"invalid".to_string(),
),
);
let err = ParquetOptions::try_from(&proto).unwrap_err();
assert!(
err.to_string().contains(
"Invalid parquet statistics setting: invalid. Expected one of: none, chunk, page"
),
"unexpected error: {err}"
);
}
#[test]
fn test_parquet_options_max_row_group_bytes_round_trip() {
let opts = ParquetOptions {
max_row_group_bytes: Some(
MaxRowGroupBytes::try_new(64 * 1024 * 1024).unwrap(),
),
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts.clone());
assert_eq!(
recovered.max_row_group_bytes.map(|v| v.get()),
Some(64 * 1024 * 1024)
);
}
#[test]
fn test_table_parquet_options_coerce_int96_tz_round_trip() {
let mut opts = TableParquetOptions::default();
opts.global.coerce_int96 = Some(DFTimeUnit::Microsecond);
opts.global.coerce_int96_tz = Some("America/Los_Angeles".parse().unwrap());
let recovered = table_parquet_options_proto_round_trip(opts.clone());
assert_eq!(recovered.global.coerce_int96, Some(DFTimeUnit::Microsecond));
assert_eq!(
recovered.global.coerce_int96_tz,
opts.global.coerce_int96_tz
);
}
#[test]
fn test_parquet_options_cdc_enabled_round_trip() {
let opts = ParquetOptions {
content_defined_chunking: ParquetCdcOptions {
enabled: true,
min_chunk_size: 128 * 1024,
max_chunk_size: 512 * 1024,
norm_level: 2,
},
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts.clone());
let cdc = recovered.content_defined_chunking;
assert!(cdc.enabled);
assert_eq!(cdc.min_chunk_size, 128 * 1024);
assert_eq!(cdc.max_chunk_size, 512 * 1024);
assert_eq!(cdc.norm_level, 2);
}
#[test]
fn test_parquet_options_cdc_negative_norm_level_round_trip() {
let opts = ParquetOptions {
content_defined_chunking: ParquetCdcOptions {
enabled: true,
norm_level: -3,
..ParquetCdcOptions::default()
},
..ParquetOptions::default()
};
let recovered = parquet_options_proto_round_trip(opts);
assert_eq!(recovered.content_defined_chunking.norm_level, -3);
}
#[test]
fn test_table_parquet_options_cdc_round_trip() {
let mut opts = TableParquetOptions::default();
opts.global.content_defined_chunking = ParquetCdcOptions {
enabled: true,
min_chunk_size: 64 * 1024,
max_chunk_size: 2 * 1024 * 1024,
norm_level: -1,
};
let recovered = table_parquet_options_proto_round_trip(opts.clone());
let cdc = recovered.global.content_defined_chunking;
assert!(cdc.enabled);
assert_eq!(cdc.min_chunk_size, 64 * 1024);
assert_eq!(cdc.max_chunk_size, 2 * 1024 * 1024);
assert_eq!(cdc.norm_level, -1);
}
#[test]
fn test_table_parquet_options_cdc_disabled_round_trip() {
let opts = TableParquetOptions::default();
assert!(!opts.global.content_defined_chunking.enabled);
let recovered = table_parquet_options_proto_round_trip(opts.clone());
assert!(!recovered.global.content_defined_chunking.enabled);
}
}