use super::THRESHOLD_INLINE_INLIST;
use arrow::datatypes::DataType;
use datafusion_common::tree_node::{Transformed, TreeNodeRewriter};
use datafusion_common::{DFSchema, Result};
use datafusion_expr::expr::InList;
use datafusion_expr::{Expr, ExprSchemable};
pub(super) struct ShortenInListSimplifier<'a> {
schema: &'a DFSchema,
}
impl<'a> ShortenInListSimplifier<'a> {
pub(super) fn new(schema: &'a DFSchema) -> Self {
Self { schema }
}
fn should_retain_short_inlist(&self, expr: &Expr, list: &[Expr]) -> bool {
let Ok(data_type) = expr.get_type(self.schema) else {
return false;
};
matches!(
data_type,
DataType::Int32
| DataType::Int64
| DataType::UInt64
| DataType::Float32
| DataType::Float64
| DataType::FixedSizeBinary(1 | 2 | 4 | 8 | 16)
) && list.iter().all(|expr| expr.as_literal().is_some())
}
}
impl TreeNodeRewriter for ShortenInListSimplifier<'_> {
type Node = Expr;
fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
if let Expr::InList(InList {
ref expr,
ref list,
negated,
}) = expr
&& !list.is_empty()
&& (
list.len() == 1
|| list.len() <= THRESHOLD_INLINE_INLIST
&& expr.try_as_col().is_some()
&& !self.should_retain_short_inlist(expr, list)
)
{
let first_val = list[0].clone();
if negated {
return Ok(Transformed::yes(list.iter().skip(1).cloned().fold(
(*expr.clone()).not_eq(first_val),
|acc, y| {
acc.and((*expr.clone()).not_eq(y))
},
)));
} else {
return Ok(Transformed::yes(list.iter().skip(1).cloned().fold(
(*expr.clone()).eq(first_val),
|acc, y| {
acc.or((*expr.clone()).eq(y))
},
)));
}
}
Ok(Transformed::no(expr))
}
}