use crate::logical_plan::consumer::SubstraitConsumer;
use datafusion::arrow::datatypes::Field;
use datafusion::common::{JoinType, NullEquality, not_impl_err, substrait_err};
use datafusion::logical_expr::{
Cast, Expr, LogicalPlan, LogicalPlanBuilder, requalify_sides_if_needed,
};
use std::sync::Arc;
use substrait::proto::set_rel::SetOp;
use substrait::proto::{Rel, SetRel};
pub async fn from_set_rel(
consumer: &impl SubstraitConsumer,
set: &SetRel,
) -> datafusion::common::Result<LogicalPlan> {
if set.inputs.len() < 2 {
substrait_err!("Set operation requires at least two inputs")
} else {
match set.op() {
SetOp::UnionAll => union_rels(consumer, &set.inputs, true).await,
SetOp::UnionDistinct => union_rels(consumer, &set.inputs, false).await,
SetOp::IntersectionPrimary => intersect_rel(
consumer.consume_rel(&set.inputs[0]).await?,
union_rels(consumer, &set.inputs[1..], true).await?,
false,
),
SetOp::IntersectionMultiset => {
intersect_rels(consumer, &set.inputs, false).await
}
SetOp::IntersectionMultisetAll => {
intersect_rels(consumer, &set.inputs, true).await
}
SetOp::MinusPrimary => except_rels(consumer, &set.inputs, false).await,
SetOp::MinusPrimaryAll => except_rels(consumer, &set.inputs, true).await,
set_op => not_impl_err!("Unsupported set operator: {set_op:?}"),
}
}
}
async fn union_rels(
consumer: &impl SubstraitConsumer,
rels: &[Rel],
is_all: bool,
) -> datafusion::common::Result<LogicalPlan> {
let mut union_builder = Ok(LogicalPlanBuilder::from(
consumer.consume_rel(&rels[0]).await?,
));
for input in &rels[1..] {
let rel_plan = consumer.consume_rel(input).await?;
union_builder = if is_all {
union_builder?.union(rel_plan)
} else {
union_builder?.union_distinct(rel_plan)
};
}
union_builder?.build()
}
async fn intersect_rels(
consumer: &impl SubstraitConsumer,
rels: &[Rel],
is_all: bool,
) -> datafusion::common::Result<LogicalPlan> {
let mut rel = consumer.consume_rel(&rels[0]).await?;
for input in &rels[1..] {
rel = intersect_rel(rel, consumer.consume_rel(input).await?, is_all)?;
}
Ok(rel)
}
fn intersect_rel(
left: LogicalPlan,
right: LogicalPlan,
is_all: bool,
) -> datafusion::common::Result<LogicalPlan> {
let left_fields = left.schema().fields();
let right_fields = right.schema().fields();
let from_right: Vec<bool> = left_fields
.iter()
.zip(right_fields.iter())
.map(|(left, right)| {
left.is_nullable()
&& !right.is_nullable()
&& left.data_type() == right.data_type()
})
.collect();
if left_fields.len() != right_fields.len() || !from_right.contains(&true) {
return LogicalPlanBuilder::intersect(left, right, is_all);
}
let (left, right, _) = requalify_sides_if_needed(
LogicalPlanBuilder::from(left),
LogicalPlanBuilder::from(right),
)?;
let left = if is_all { left } else { left.distinct()? };
let right = right.distinct()?.build()?;
let left_columns = left.schema().columns();
let right_columns = right.schema().columns();
let exprs = left
.schema()
.fields()
.iter()
.zip(&left_columns)
.zip(&right_columns)
.zip(&from_right)
.map(|(((field, left), right), from_right)| {
if *from_right {
let target_field = Arc::new(
Field::new(&left.name, field.data_type().clone(), false)
.with_metadata(field.metadata().clone()),
);
Expr::Cast(Cast::new_from_field(
Box::new(Expr::Column(right.clone())),
target_field,
))
.alias_qualified(left.relation.clone(), &left.name)
} else {
Expr::Column(left.clone())
}
})
.collect::<Vec<_>>();
let joined = left
.join_detailed(
right,
JoinType::Inner,
(left_columns, right_columns),
None,
NullEquality::NullEqualsNull,
)?
.build()?;
LogicalPlanBuilder::from(joined).project(exprs)?.build()
}
async fn except_rels(
consumer: &impl SubstraitConsumer,
rels: &[Rel],
is_all: bool,
) -> datafusion::common::Result<LogicalPlan> {
let mut rel = consumer.consume_rel(&rels[0]).await?;
for input in &rels[1..] {
rel =
LogicalPlanBuilder::except(rel, consumer.consume_rel(input).await?, is_all)?;
}
Ok(rel)
}