use crate::logical_plan::producer::SubstraitProducer;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::common::{DFSchemaRef, ScalarValue, not_impl_err};
use datafusion::logical_expr::expr::{Exists, InSubquery, SetComparison};
use datafusion::logical_expr::{Case, Expr, ExprSchemable, LogicalPlan};
use substrait::proto::Expression;
use substrait::proto::expression::if_then::IfClause;
use substrait::proto::expression::{IfThen, RexType};
pub fn from_case(
producer: &mut impl SubstraitProducer,
case: &Case,
schema: &DFSchemaRef,
) -> datafusion::common::Result<Expression> {
let Case {
expr,
when_then_expr,
else_expr,
} = case;
if let Some(base) = expr
&& is_volatile_including_subqueries(base)?
{
return not_impl_err!(
"Substrait does not support a volatile CASE base expression: {base}"
);
}
let when_operand_is_inert = |(when, _): &(Box<Expr>, Box<Expr>)| {
matches!(when.as_ref(), Expr::Literal(..) | Expr::Column(_))
};
let null_base_guard = match expr {
Some(base)
if !when_then_expr.iter().all(when_operand_is_inert)
&& base.nullable(schema.as_ref())? =>
{
Some(base)
}
_ => None,
};
let mut ifs: Vec<IfClause> =
Vec::with_capacity(when_then_expr.len() + usize::from(null_base_guard.is_some()));
if let Some(base) = null_base_guard {
let condition = producer.handle_expr(&base.clone().is_null(), schema)?;
let then = match else_expr {
Some(e) => producer.handle_expr(e, schema)?,
None => {
let result_type = match when_then_expr.first() {
Some((_, then)) => then.get_type(schema.as_ref())?,
None => {
return not_impl_err!("CASE with no WHEN clause");
}
};
let null = Expr::Literal(ScalarValue::try_from(&result_type)?, None);
producer.handle_expr(&null, schema)?
}
};
ifs.push(IfClause {
r#if: Some(condition),
then: Some(then),
});
}
for (when, then) in when_then_expr {
let condition = match expr {
Some(base) => {
let eq = Expr::eq(*base.clone(), *when.clone());
producer.handle_expr(&eq, schema)?
}
None => producer.handle_expr(when, schema)?,
};
ifs.push(IfClause {
r#if: Some(condition),
then: Some(producer.handle_expr(then, schema)?),
});
}
let r#else: Option<Box<Expression>> = match else_expr {
Some(e) => Some(Box::new(producer.handle_expr(e, schema)?)),
None => None,
};
Ok(Expression {
rex_type: Some(RexType::IfThen(Box::new(IfThen { ifs, r#else }))),
})
}
fn is_volatile_including_subqueries(expr: &Expr) -> datafusion::common::Result<bool> {
expr.exists(|expr| match expr {
Expr::ScalarSubquery(subquery)
| Expr::Exists(Exists { subquery, .. })
| Expr::InSubquery(InSubquery { subquery, .. })
| Expr::SetComparison(SetComparison { subquery, .. }) => {
plan_is_volatile(&subquery.subquery)
}
expr => Ok(expr.is_volatile_node()),
})
}
fn plan_is_volatile(plan: &LogicalPlan) -> datafusion::common::Result<bool> {
plan.exists(|plan| {
let mut volatile = false;
plan.apply_expressions(|expr| {
volatile = is_volatile_including_subqueries(expr)?;
Ok(if volatile {
TreeNodeRecursion::Stop
} else {
TreeNodeRecursion::Continue
})
})?;
Ok(volatile)
})
}