use super::*;
pub(super) fn to_substrait_named_struct(
producer: &mut impl SubstraitProducer,
schema: &DFSchemaRef,
) -> Result<NamedStruct> {
let mut names = Vec::with_capacity(schema.fields().len());
for field in schema.fields() {
flatten_field_names(field, &mut names)?;
}
let field_types = proto::r#type::Struct {
types: schema
.fields()
.iter()
.map(|f| to_substrait_type(producer, f.data_type(), f.is_nullable()))
.collect::<Result<_>>()?,
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability: proto::r#type::Nullability::Required as i32,
};
Ok(NamedStruct {
names,
r#struct: Some(field_types),
})
}
fn flatten_field_names(field: &Field, names: &mut Vec<String>) -> Result<()> {
names.push(field.name().to_string());
flatten_nested_names(field.data_type(), names)
}
fn flatten_nested_names(data_type: &DataType, names: &mut Vec<String>) -> Result<()> {
match data_type {
DataType::Struct(fields) => fields
.iter()
.try_for_each(|field| flatten_field_names(field, names)),
DataType::List(field) | DataType::LargeList(field) => {
flatten_nested_names(field.data_type(), names)
}
DataType::Map(field, _) => match field.data_type() {
DataType::Struct(key_and_value) if key_and_value.len() == 2 => {
flatten_nested_names(key_and_value[0].data_type(), names)?;
flatten_nested_names(key_and_value[1].data_type(), names)
}
_ => plan_err!("Map fields must contain a Struct with exactly 2 fields"),
},
DataType::Dictionary(key, value) => {
flatten_nested_names(key, names)?;
flatten_nested_names(value, names)
}
_ => Ok(()),
}
}
pub(super) fn to_substrait_precision(time_unit: &TimeUnit) -> i32 {
match time_unit {
TimeUnit::Second => 0,
TimeUnit::Millisecond => 3,
TimeUnit::Microsecond => 6,
TimeUnit::Nanosecond => 9,
}
}
pub(super) fn to_substrait_type(
producer: &mut impl SubstraitProducer,
data_type: &DataType,
nullable: bool,
) -> Result<proto::Type> {
let nullability = if nullable {
proto::r#type::Nullability::Nullable as i32
} else {
proto::r#type::Nullability::Required as i32
};
let kind = match data_type {
DataType::Null => {
let type_anchor = producer.register_type(NULL_TYPE_NAME.to_string());
proto::r#type::Kind::UserDefined(proto::r#type::UserDefined {
type_reference: type_anchor,
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
type_parameters: vec![],
})
}
DataType::Boolean => proto::r#type::Kind::Bool(proto::r#type::Boolean {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::Int8 => proto::r#type::Kind::I8(proto::r#type::I8 {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::UInt8 => proto::r#type::Kind::I8(proto::r#type::I8 {
type_variation_reference: UNSIGNED_INTEGER_TYPE_VARIATION_REF,
nullability,
}),
DataType::Int16 => proto::r#type::Kind::I16(proto::r#type::I16 {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::UInt16 => proto::r#type::Kind::I16(proto::r#type::I16 {
type_variation_reference: UNSIGNED_INTEGER_TYPE_VARIATION_REF,
nullability,
}),
DataType::Int32 => proto::r#type::Kind::I32(proto::r#type::I32 {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::UInt32 => proto::r#type::Kind::I32(proto::r#type::I32 {
type_variation_reference: UNSIGNED_INTEGER_TYPE_VARIATION_REF,
nullability,
}),
DataType::Int64 => proto::r#type::Kind::I64(proto::r#type::I64 {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::UInt64 => proto::r#type::Kind::I64(proto::r#type::I64 {
type_variation_reference: UNSIGNED_INTEGER_TYPE_VARIATION_REF,
nullability,
}),
DataType::Float16 => {
let type_anchor = producer.register_type(FLOAT_16_TYPE_NAME.to_string());
proto::r#type::Kind::UserDefined(proto::r#type::UserDefined {
type_reference: type_anchor,
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
type_parameters: vec![],
})
}
DataType::Float32 => proto::r#type::Kind::Fp32(proto::r#type::Fp32 {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::Float64 => proto::r#type::Kind::Fp64(proto::r#type::Fp64 {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
}),
DataType::Timestamp(unit, tz) => {
let precision = to_substrait_precision(unit);
match tz {
None => proto::r#type::Kind::PrecisionTimestamp(
proto::r#type::PrecisionTimestamp {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
precision,
},
),
Some(_) => proto::r#type::Kind::PrecisionTimestampTz(
proto::r#type::PrecisionTimestampTz {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
precision,
},
),
}
}
DataType::Time32(unit) => {
proto::r#type::Kind::PrecisionTime(proto::r#type::PrecisionTime {
precision: to_substrait_precision(unit),
type_variation_reference: TIME_32_TYPE_VARIATION_REF,
nullability,
})
}
DataType::Time64(unit) => {
proto::r#type::Kind::PrecisionTime(proto::r#type::PrecisionTime {
precision: to_substrait_precision(unit),
type_variation_reference: TIME_64_TYPE_VARIATION_REF,
nullability,
})
}
DataType::Date32 => proto::r#type::Kind::Date(proto::r#type::Date {
type_variation_reference: DATE_32_TYPE_VARIATION_REF,
nullability,
}),
DataType::Date64 => proto::r#type::Kind::Date(proto::r#type::Date {
type_variation_reference: DATE_64_TYPE_VARIATION_REF,
nullability,
}),
DataType::Interval(unit) => match unit {
IntervalUnit::YearMonth => {
proto::r#type::Kind::IntervalYear(proto::r#type::IntervalYear {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
})
}
IntervalUnit::DayTime => {
proto::r#type::Kind::IntervalDay(proto::r#type::IntervalDay {
type_variation_reference: DEFAULT_INTERVAL_DAY_TYPE_VARIATION_REF,
nullability,
precision: Some(3),
})
}
IntervalUnit::MonthDayNano => {
proto::r#type::Kind::IntervalCompound(proto::r#type::IntervalCompound {
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
precision: 9,
})
}
},
DataType::Duration(unit) => {
proto::r#type::Kind::IntervalDay(proto::r#type::IntervalDay {
type_variation_reference: DURATION_INTERVAL_DAY_TYPE_VARIATION_REF,
nullability,
precision: Some(to_substrait_precision(unit)),
})
}
DataType::Binary => proto::r#type::Kind::Binary(proto::r#type::Binary {
type_variation_reference: DEFAULT_CONTAINER_TYPE_VARIATION_REF,
nullability,
}),
DataType::FixedSizeBinary(length) => {
proto::r#type::Kind::FixedBinary(proto::r#type::FixedBinary {
length: *length,
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
})
}
DataType::LargeBinary => proto::r#type::Kind::Binary(proto::r#type::Binary {
type_variation_reference: LARGE_CONTAINER_TYPE_VARIATION_REF,
nullability,
}),
DataType::BinaryView => proto::r#type::Kind::Binary(proto::r#type::Binary {
type_variation_reference: VIEW_CONTAINER_TYPE_VARIATION_REF,
nullability,
}),
DataType::Utf8 => proto::r#type::Kind::String(proto::r#type::String {
type_variation_reference: DEFAULT_CONTAINER_TYPE_VARIATION_REF,
nullability,
}),
DataType::LargeUtf8 => proto::r#type::Kind::String(proto::r#type::String {
type_variation_reference: LARGE_CONTAINER_TYPE_VARIATION_REF,
nullability,
}),
DataType::Utf8View => proto::r#type::Kind::String(proto::r#type::String {
type_variation_reference: VIEW_CONTAINER_TYPE_VARIATION_REF,
nullability,
}),
DataType::List(inner) => {
let inner_type =
to_substrait_type(producer, inner.data_type(), inner.is_nullable())?;
proto::r#type::Kind::List(Box::new(proto::r#type::List {
r#type: Some(Box::new(inner_type)),
type_variation_reference: DEFAULT_CONTAINER_TYPE_VARIATION_REF,
nullability,
}))
}
DataType::LargeList(inner) => {
let inner_type =
to_substrait_type(producer, inner.data_type(), inner.is_nullable())?;
proto::r#type::Kind::List(Box::new(proto::r#type::List {
r#type: Some(Box::new(inner_type)),
type_variation_reference: LARGE_CONTAINER_TYPE_VARIATION_REF,
nullability,
}))
}
DataType::Map(inner, _) => match inner.data_type() {
DataType::Struct(key_and_value) if key_and_value.len() == 2 => {
let key_type = to_substrait_type(
producer,
key_and_value[0].data_type(),
key_and_value[0].is_nullable(),
)?;
let value_type = to_substrait_type(
producer,
key_and_value[1].data_type(),
key_and_value[1].is_nullable(),
)?;
proto::r#type::Kind::Map(Box::new(proto::r#type::Map {
key: Some(Box::new(key_type)),
value: Some(Box::new(value_type)),
type_variation_reference: DEFAULT_MAP_TYPE_VARIATION_REF,
nullability,
}))
}
_ => {
return plan_err!(
"Map fields must contain a Struct with exactly 2 fields"
);
}
},
DataType::Dictionary(key_type, value_type) => {
let key_type = to_substrait_type(producer, key_type, nullable)?;
let value_type = to_substrait_type(producer, value_type, nullable)?;
proto::r#type::Kind::Map(Box::new(proto::r#type::Map {
key: Some(Box::new(key_type)),
value: Some(Box::new(value_type)),
type_variation_reference: DICTIONARY_MAP_TYPE_VARIATION_REF,
nullability,
}))
}
DataType::Struct(fields) => {
let field_types = fields
.iter()
.map(|field| {
to_substrait_type(producer, field.data_type(), field.is_nullable())
})
.collect::<Result<Vec<_>>>()?;
proto::r#type::Kind::Struct(proto::r#type::Struct {
types: field_types,
type_variation_reference: DEFAULT_TYPE_VARIATION_REF,
nullability,
})
}
DataType::Decimal128(precision, scale) => {
proto::r#type::Kind::Decimal(proto::r#type::Decimal {
type_variation_reference: DECIMAL_128_TYPE_VARIATION_REF,
nullability,
scale: *scale as i32,
precision: *precision as i32,
})
}
DataType::Decimal256(precision, scale) => {
proto::r#type::Kind::Decimal(proto::r#type::Decimal {
type_variation_reference: DECIMAL_256_TYPE_VARIATION_REF,
nullability,
scale: *scale as i32,
precision: *precision as i32,
})
}
_ => return not_impl_err!("Unsupported cast type: {data_type}"),
};
Ok(proto::Type { kind: Some(kind) })
}
pub(super) fn decode_data_type(
consumer: &impl SubstraitConsumer,
data_type: &proto::Type,
) -> Result<DataType> {
let mut name_idx = 0;
from_substrait_type(consumer, data_type, &[], &mut name_idx)
}
pub(super) fn to_substrait_cast_type(
producer: &mut impl SubstraitProducer,
data_type: &DataType,
) -> Result<proto::Type> {
let decoded = bare_decoded_type(data_type);
if decoded != *data_type {
return plan_err!(
"MATCH_RECOGNIZE Substrait export cannot preserve CAST target type {data_type}: \
a bare Substrait type would decode it as {decoded}"
);
}
to_substrait_type(producer, data_type, true)
}
pub(super) fn bare_decoded_type(data_type: &DataType) -> DataType {
let field = |data_type: &DataType, name: &str, nullable: bool| {
Arc::new(Field::new(name, bare_decoded_type(data_type), nullable))
};
match data_type {
DataType::Timestamp(unit, Some(_)) => {
DataType::Timestamp(*unit, Some("UTC".into()))
}
DataType::Struct(fields) => DataType::Struct(
fields
.iter()
.enumerate()
.map(|(index, f)| {
field(f.data_type(), &format!("c{index}"), f.is_nullable())
})
.collect(),
),
DataType::List(element) => DataType::List(field(
element.data_type(),
Field::LIST_FIELD_DEFAULT_NAME,
true,
)),
DataType::LargeList(element) => DataType::LargeList(field(
element.data_type(),
Field::LIST_FIELD_DEFAULT_NAME,
true,
)),
DataType::Map(entries, _) => match entries.data_type() {
DataType::Struct(key_and_value) if key_and_value.len() == 2 => DataType::Map(
Arc::new(Field::new_struct(
"entries",
[
field(key_and_value[0].data_type(), "key", false),
field(key_and_value[1].data_type(), "value", true),
],
false,
)),
false,
),
_ => data_type.clone(),
},
DataType::Dictionary(key, value) => DataType::Dictionary(
Box::new(bare_decoded_type(key)),
Box::new(bare_decoded_type(value)),
),
_ => data_type.clone(),
}
}
pub(super) fn validate_output_schema(
plan: &LogicalPlan,
expected: &DFSchema,
expected_types: &[proto::Type],
boundary: MatchRecognizeBoundary,
) -> Result<()> {
let compare_names = match boundary {
MatchRecognizeBoundary::CompletePlan => true,
MatchRecognizeBoundary::RowStreamNode | MatchRecognizeBoundary::OneRowNode => {
false
}
};
let actual_fields = plan.schema().fields();
let expected_fields = expected.fields();
if actual_fields.len() != expected_fields.len() {
return plan_err!(
"MATCH_RECOGNIZE output schema mismatch: planned {} fields but payload declares {} fields",
actual_fields.len(),
expected_fields.len()
);
}
for ((index, (actual, expected)), expected_type) in actual_fields
.iter()
.zip(expected_fields.iter())
.enumerate()
.zip(expected_types.iter())
{
let expected_nullable = substrait_type_is_nullable(expected_type)?;
if actual.is_nullable() != expected_nullable {
return plan_err!(
"MATCH_RECOGNIZE output schema mismatch at field {}: planned {} nullable={}, payload declares nullable={}",
index,
actual.name(),
actual.is_nullable(),
expected_nullable
);
}
if !output_type_matches(actual.data_type(), expected.data_type(), expected_type)?
|| (compare_names && actual.name() != expected.name())
{
return plan_err!(
"MATCH_RECOGNIZE output schema mismatch at field {}: planned {} {:?}, payload declares {} {:?}",
index,
actual.name(),
actual.data_type(),
expected.name(),
expected.data_type()
);
}
}
Ok(())
}
pub(super) fn output_type_matches(
actual: &DataType,
expected: &DataType,
wire: &proto::Type,
) -> Result<bool> {
use proto::r#type::Kind;
let field_matches =
|actual: &Field, expected: &Field, wire: &proto::Type| -> Result<bool> {
Ok(actual.is_nullable() == substrait_type_is_nullable(wire)?
&& output_type_matches(actual.data_type(), expected.data_type(), wire)?)
};
match (actual, expected, wire.kind.as_ref()) {
(
DataType::Struct(actual),
DataType::Struct(expected),
Some(Kind::Struct(wire)),
) => {
if actual.len() != expected.len() || actual.len() != wire.types.len() {
return Ok(false);
}
for ((actual, expected), wire) in actual.iter().zip(expected).zip(&wire.types)
{
if actual.name() != expected.name()
|| !field_matches(actual, expected, wire)?
{
return Ok(false);
}
}
Ok(true)
}
(DataType::List(actual), DataType::List(expected), Some(Kind::List(wire)))
| (
DataType::LargeList(actual),
DataType::LargeList(expected),
Some(Kind::List(wire)),
) => match wire.r#type.as_deref() {
Some(wire) => field_matches(actual, expected, wire),
None => Ok(false),
},
(DataType::Map(actual, _), DataType::Map(expected, _), Some(Kind::Map(wire))) => {
let (DataType::Struct(actual), DataType::Struct(expected)) =
(actual.data_type(), expected.data_type())
else {
return Ok(false);
};
let (Some(key), Some(value)) = (wire.key.as_deref(), wire.value.as_deref())
else {
return Ok(false);
};
Ok(actual.len() == 2
&& expected.len() == 2
&& field_matches(&actual[0], &expected[0], key)?
&& field_matches(&actual[1], &expected[1], value)?)
}
(
DataType::Dictionary(actual_key, actual_value),
DataType::Dictionary(expected_key, expected_value),
Some(Kind::Map(wire)),
) => {
let (Some(key), Some(value)) = (wire.key.as_deref(), wire.value.as_deref())
else {
return Ok(false);
};
substrait_type_is_nullable(key)?;
substrait_type_is_nullable(value)?;
Ok(output_type_matches(actual_key, expected_key, key)?
&& output_type_matches(actual_value, expected_value, value)?)
}
(
DataType::Timestamp(actual_unit, actual_zone),
DataType::Timestamp(expected_unit, expected_zone),
_,
) => Ok(actual_unit == expected_unit
&& actual_zone.is_some() == expected_zone.is_some()),
(
DataType::Decimal128(precision, scale),
DataType::Decimal128(_, _),
Some(Kind::Decimal(wire)),
)
| (
DataType::Decimal256(precision, scale),
DataType::Decimal256(_, _),
Some(Kind::Decimal(wire)),
) => Ok(
i32::from(*precision) == wire.precision && i32::from(*scale) == wire.scale
),
(DataType::Utf8, DataType::Utf8View, _)
| (DataType::Utf8View, DataType::Utf8, _) => Ok(true),
_ => Ok(actual == expected),
}
}
#[allow(
deprecated,
reason = "decode all upstream Substrait wire type variants"
)]
pub(super) fn substrait_type_is_nullable(data_type: &proto::Type) -> Result<bool> {
use proto::r#type::Kind;
let nullability = match data_type.kind.as_ref().ok_or_else(|| {
datafusion::common::DataFusionError::Plan(
"Substrait Type missing kind".to_string(),
)
})? {
Kind::Bool(value) => value.nullability,
Kind::I8(value) => value.nullability,
Kind::I16(value) => value.nullability,
Kind::I32(value) => value.nullability,
Kind::I64(value) => value.nullability,
Kind::Fp32(value) => value.nullability,
Kind::Fp64(value) => value.nullability,
Kind::String(value) => value.nullability,
Kind::Binary(value) => value.nullability,
Kind::Timestamp(value) => value.nullability,
Kind::Date(value) => value.nullability,
Kind::Time(value) => value.nullability,
Kind::IntervalYear(value) => value.nullability,
Kind::IntervalDay(value) => value.nullability,
Kind::TimestampTz(value) => value.nullability,
Kind::Uuid(value) => value.nullability,
Kind::FixedChar(value) => value.nullability,
Kind::Varchar(value) => value.nullability,
Kind::FixedBinary(value) => value.nullability,
Kind::Decimal(value) => value.nullability,
Kind::Struct(value) => value.nullability,
Kind::List(value) => value.nullability,
Kind::Map(value) => value.nullability,
Kind::Func(value) => value.nullability,
Kind::UserDefined(value) => value.nullability,
Kind::PrecisionTimestamp(value) => value.nullability,
Kind::PrecisionTimestampTz(value) => value.nullability,
Kind::IntervalCompound(value) => value.nullability,
Kind::PrecisionTime(value) => value.nullability,
Kind::Alias(value) => value.nullability,
Kind::UserDefinedTypeReference(_) => {
return Ok(false);
}
};
match proto::r#type::Nullability::try_from(nullability).map_err(|_| {
datafusion::common::DataFusionError::Plan(format!(
"unknown Substrait nullability value {nullability}"
))
})? {
proto::r#type::Nullability::Nullable => Ok(true),
proto::r#type::Nullability::Required => Ok(false),
proto::r#type::Nullability::Unspecified => {
plan_err!("Substrait type nullability is unspecified")
}
}
}