use crate::core::{
static_predicate_and_col_name, static_predicate_or_col_name, static_scalar_col_name,
};
pub(crate) use crate::planning::define::{StaticAnalysis, is_static};
use crate::planning::expr_safety::can_precompute;
use datafusion::arrow::datatypes::DataType;
use datafusion::common::DFSchema;
use datafusion::logical_expr::{BinaryExpr, Expr, ExprSchemable, Operator};
#[cfg(test)]
use std::collections::BTreeSet;
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExtractionKind {
BooleanAnd,
BooleanOr,
Scalar,
}
#[derive(Debug, Clone)]
pub struct StaticExtraction {
pub column_name: String,
pub expr: Expr,
pub kind: ExtractionKind,
pub symbols: Vec<String>,
}
pub struct ExtractionContext<'a> {
input_schema: &'a DFSchema,
bool_and_counter: usize,
bool_or_counter: usize,
scalar_counter: usize,
seen: HashMap<(ExtractionKind, Expr), usize>,
pub extractions: Vec<StaticExtraction>,
}
impl<'a> ExtractionContext<'a> {
pub fn new(input_schema: &'a DFSchema) -> Self {
Self {
input_schema,
bool_and_counter: 0,
bool_or_counter: 0,
scalar_counter: 0,
seen: HashMap::new(),
extractions: Vec::new(),
}
}
fn can_prepare(&self, expr: &Expr) -> bool {
!expr.is_volatile() && can_precompute(expr, self.input_schema)
}
fn get_or_create_extraction(
&mut self,
expr: &Expr,
kind: ExtractionKind,
symbol: &str,
) -> String {
let key = (kind, expr.clone());
if let Some(&index) = self.seen.get(&key) {
let extraction = &mut self.extractions[index];
if !extraction.symbols.iter().any(|known| known == symbol) {
extraction.symbols.push(symbol.to_string());
}
return extraction.column_name.clone();
}
let col_name = match kind {
ExtractionKind::BooleanAnd => {
let name = static_predicate_and_col_name(self.bool_and_counter);
self.bool_and_counter += 1;
name
}
ExtractionKind::BooleanOr => {
let name = static_predicate_or_col_name(self.bool_or_counter);
self.bool_or_counter += 1;
name
}
ExtractionKind::Scalar => {
let name = static_scalar_col_name(self.scalar_counter);
self.scalar_counter += 1;
name
}
};
let index = self.extractions.len();
self.extractions.push(StaticExtraction {
column_name: col_name.clone(),
expr: expr.clone(),
kind,
symbols: vec![symbol.to_string()],
});
self.seen.insert(key, index);
col_name
}
}
fn is_literal_or_column_cast_chain(expr: &Expr) -> bool {
match expr {
Expr::Column(_) | Expr::Literal(_, _) => true,
Expr::Cast(cast) => is_literal_or_column_cast_chain(&cast.expr),
Expr::TryCast(cast) => is_literal_or_column_cast_chain(&cast.expr),
_ => false,
}
}
pub fn extract_static_subexpressions(
expr: Expr,
analysis: StaticAnalysis<'_>,
ctx: &mut ExtractionContext<'_>,
symbol: &str,
) -> Expr {
if is_static(&expr, analysis) {
return expr;
}
extract_from_expr(expr, analysis, ctx, symbol, ExtractionNesting::default())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BooleanChainKind {
And,
Or,
}
impl BooleanChainKind {
fn operator(self) -> Operator {
match self {
Self::And => Operator::And,
Self::Or => Operator::Or,
}
}
fn combine(self, exprs: Vec<Expr>) -> Option<Expr> {
match self {
Self::And => exprs.into_iter().reduce(Expr::and),
Self::Or => exprs.into_iter().reduce(Expr::or),
}
}
fn extraction_kind(self) -> ExtractionKind {
match self {
Self::And => ExtractionKind::BooleanAnd,
Self::Or => ExtractionKind::BooleanOr,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ExtractionNesting {
inside_or: bool,
inside_and: bool,
positive_polarity: bool,
follows_boolean_term: bool,
}
impl Default for ExtractionNesting {
fn default() -> Self {
Self {
inside_or: false,
inside_and: false,
positive_polarity: true,
follows_boolean_term: false,
}
}
}
impl ExtractionNesting {
fn enter(self, kind: BooleanChainKind) -> Self {
match kind {
BooleanChainKind::And => Self {
inside_and: true,
..self
},
BooleanChainKind::Or => Self {
inside_or: true,
..self
},
}
}
fn negated(self) -> Self {
Self {
inside_or: self.inside_and,
inside_and: self.inside_or,
positive_polarity: !self.positive_polarity,
..self
}
}
fn after_boolean_term(self) -> Self {
Self {
follows_boolean_term: true,
..self
}
}
fn scalar_operand(self) -> Self {
Self {
inside_or: true,
inside_and: true,
..self
}
}
fn allows_boolean_extraction(self, kind: BooleanChainKind) -> bool {
self.positive_polarity
&& !self.follows_boolean_term
&& match kind {
BooleanChainKind::And => !self.inside_or,
BooleanChainKind::Or => !self.inside_and,
}
}
}
fn extract_from_expr(
expr: Expr,
analysis: StaticAnalysis<'_>,
ctx: &mut ExtractionContext<'_>,
symbol: &str,
nesting: ExtractionNesting,
) -> Expr {
match expr {
expr @ Expr::BinaryExpr(BinaryExpr {
op: Operator::And, ..
}) => handle_boolean_chain(
expr,
analysis,
ctx,
symbol,
nesting,
BooleanChainKind::And,
),
expr @ Expr::BinaryExpr(BinaryExpr {
op: Operator::Or, ..
}) => handle_boolean_chain(
expr,
analysis,
ctx,
symbol,
nesting,
BooleanChainKind::Or,
),
Expr::BinaryExpr(BinaryExpr { left, op, right }) if is_comparison(op) => {
handle_comparison(*left, op, *right, analysis, ctx, symbol, nesting)
}
Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
let nesting = nesting.scalar_operand();
let new_left = extract_from_expr(*left, analysis, ctx, symbol, nesting);
let new_right = extract_from_expr(*right, analysis, ctx, symbol, nesting);
Expr::BinaryExpr(BinaryExpr {
left: Box::new(new_left),
op,
right: Box::new(new_right),
})
}
Expr::Not(inner) => {
let new_inner =
extract_from_expr(*inner, analysis, ctx, symbol, nesting.negated());
Expr::Not(Box::new(new_inner))
}
expr => expr,
}
}
fn handle_comparison(
left: Expr,
op: Operator,
right: Expr,
analysis: StaticAnalysis<'_>,
ctx: &mut ExtractionContext<'_>,
symbol: &str,
nesting: ExtractionNesting,
) -> Expr {
let nesting = nesting.scalar_operand();
let left_static = is_static(&left, analysis);
let right_static = is_static(&right, analysis);
if left_static && right_static {
return Expr::BinaryExpr(BinaryExpr {
left: Box::new(left),
op,
right: Box::new(right),
});
}
let mut rewrite_side = |side: Expr, is_side_static: bool| {
if !is_side_static {
extract_from_expr(side, analysis, ctx, symbol, nesting)
} else if !is_literal_or_column_cast_chain(&side) && ctx.can_prepare(&side) {
let name =
ctx.get_or_create_extraction(&side, ExtractionKind::Scalar, symbol);
Expr::Column(datafusion_common::Column::from_name(name))
} else {
side
}
};
let (new_left, new_right) = if right_static {
let right = rewrite_side(right, true);
(rewrite_side(left, false), right)
} else {
(rewrite_side(left, left_static), rewrite_side(right, false))
};
Expr::BinaryExpr(BinaryExpr {
left: Box::new(new_left),
op,
right: Box::new(new_right),
})
}
fn handle_boolean_chain(
expr: Expr,
analysis: StaticAnalysis<'_>,
ctx: &mut ExtractionContext<'_>,
symbol: &str,
nesting: ExtractionNesting,
kind: BooleanChainKind,
) -> Expr {
let mut children = boolean_terms(&expr, kind.operator()).cloned().peekable();
let mut result_children = Vec::new();
if nesting.allows_boolean_extraction(kind) {
let mut prefix = Vec::new();
while let Some(child) = children.next_if(|child| {
is_static(child, analysis)
&& ctx.can_prepare(child)
&& matches!(child.get_type(ctx.input_schema), Ok(DataType::Boolean))
}) {
prefix.push(child);
}
if let Some(prefix) = kind.combine(prefix) {
let guard = if is_literal_or_column_cast_chain(&prefix) {
prefix
} else {
let column =
ctx.get_or_create_extraction(&prefix, kind.extraction_kind(), symbol);
Expr::Column(datafusion_common::Column::from_name(column))
};
result_children.push(guard);
}
}
let mut child_nesting = nesting.enter(kind);
if !result_children.is_empty() {
child_nesting = child_nesting.after_boolean_term();
}
for child in children {
let child = if is_static(&child, analysis) {
child
} else {
extract_from_expr(child, analysis, ctx, symbol, child_nesting)
};
result_children.push(child);
child_nesting = child_nesting.after_boolean_term();
}
kind.combine(result_children)
.expect("binary boolean chain retains at least one child")
}
pub(crate) fn boolean_terms(expr: &Expr, op: Operator) -> impl Iterator<Item = &Expr> {
let mut stack = vec![expr];
std::iter::from_fn(move || {
while let Some(current) = stack.pop() {
if let Expr::BinaryExpr(binary) = current
&& binary.op == op
{
stack.push(&binary.right);
stack.push(&binary.left);
} else {
return Some(current);
}
}
None
})
}
pub(crate) fn is_comparison(op: Operator) -> bool {
matches!(
op,
Operator::Eq
| Operator::NotEq
| Operator::Lt
| Operator::LtEq
| Operator::Gt
| Operator::GtEq
)
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod rewrite_tests {
use super::*;
use crate::core::{classifier_bits_col_name, managed_aggregate_col_name};
use datafusion::arrow::datatypes::{Field, Schema};
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{col, expr::Case, lit};
use std::collections::BTreeSet;
#[test]
fn null_typed_leading_boolean_terms_are_not_extracted_as_boolean_slots() {
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("flag", DataType::Boolean, true),
Field::new("price", DataType::Float64, true),
]))
.expect("schema");
let vars = BTreeSet::from(["A".to_string()]);
let generated = BTreeSet::from([
classifier_bits_col_name("A"),
managed_aggregate_col_name(0),
]);
let analysis = StaticAnalysis::new(&vars, &generated);
let null_case = Expr::Case(Case::new(
None,
vec![(Box::new(col("flag")), Box::new(lit(ScalarValue::Null)))],
None,
));
let null_coalesce = datafusion_functions::core::coalesce()
.call(vec![lit(ScalarValue::Null), lit(ScalarValue::Null)]);
let candidate = col(managed_aggregate_col_name(0)).gt_eq(lit(2_i64));
for (label, null_term) in [
("CASE WHEN flag THEN NULL END", null_case.clone()),
("COALESCE(NULL, NULL)", null_coalesce),
] {
assert_eq!(
null_term.get_type(&schema).unwrap(),
DataType::Null,
"{label}"
);
assert!(
can_precompute(&null_term, &schema),
"{label} must exercise the Boolean-type guard rather than can_precompute"
);
for (op_label, expr) in [
("OR", null_term.clone().or(candidate.clone())),
("AND", null_term.clone().and(candidate.clone())),
] {
let mut ctx = ExtractionContext::new(&schema);
let rewritten =
extract_static_subexpressions(expr.clone(), analysis, &mut ctx, "A");
assert!(ctx.extractions.is_empty(), "{label} {op_label}");
assert_eq!(rewritten, expr, "{label} {op_label}");
}
}
let bool_term = col("price").gt(lit(100.0));
let mixed = bool_term
.clone()
.and(null_case.clone())
.and(candidate.clone());
let mut ctx = ExtractionContext::new(&schema);
let rewritten = extract_static_subexpressions(mixed, analysis, &mut ctx, "A");
assert_eq!(ctx.extractions.len(), 1);
assert_eq!(ctx.extractions[0].kind, ExtractionKind::BooleanAnd);
assert_eq!(ctx.extractions[0].expr, bool_term);
assert_eq!(
ctx.extractions[0].expr.get_type(&schema).unwrap(),
DataType::Boolean
);
assert_eq!(
rewritten,
col("__mr_static_predicate_and_0")
.and(null_case)
.and(candidate.clone())
);
let mut or_ctx = ExtractionContext::new(&schema);
let or_rewritten = extract_static_subexpressions(
bool_term.clone().or(candidate.clone()),
analysis,
&mut or_ctx,
"A",
);
assert_eq!(or_ctx.extractions.len(), 1);
assert_eq!(or_ctx.extractions[0].kind, ExtractionKind::BooleanOr);
assert_eq!(or_ctx.extractions[0].expr, bool_term);
assert_eq!(
or_rewritten,
col("__mr_static_predicate_or_0").or(candidate)
);
}
}
#[cfg(test)]
mod boolean_terms_tests {
use super::*;
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{col, lit};
#[test]
fn boolean_terms_preserve_order_and_boundaries() {
let binary = |left, op, right| {
Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right)))
};
for (op, other) in [(Operator::And, Operator::Or), (Operator::Or, Operator::And)]
{
let terms = vec![
col("a"),
binary(col("b"), op, col("c")).alias("group"),
binary(col("d"), other, col("e")),
Expr::Not(Box::new(binary(col("f"), op, col("g")))),
lit(ScalarValue::Boolean(None)),
col("a"),
];
let left = terms
.iter()
.cloned()
.reduce(|l, r| binary(l, op, r))
.unwrap();
let right = terms
.iter()
.rev()
.cloned()
.reduce(|r, l| binary(l, op, r))
.unwrap();
for expr in [left, right] {
assert_eq!(boolean_terms(&expr, op).cloned().collect::<Vec<_>>(), terms);
}
}
}
}