Skip to main content

datafusion_physical_expr/simplifier/
const_evaluator.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Constant expression evaluation for the physical expression simplifier
6
7use std::sync::Arc;
8
9use arrow::array::new_null_array;
10use arrow::datatypes::{DataType, Field, Schema};
11use arrow::record_batch::RecordBatch;
12use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
13use datafusion_common::{Result, ScalarValue, internal_datafusion_err};
14use datafusion_expr::{Operator, simplify::REGEX_PLANNING_SIZE_LIMIT_BYTES};
15use datafusion_expr_common::columnar_value::ColumnarValue;
16use regex::{Error as RegexError, RegexBuilder};
17
18use crate::expressions::{BinaryExpr, Column, Literal};
19use crate::{PhysicalExpr, ScalarFunctionExpr};
20
21/// Simplify expressions that consist only of literals by evaluating them.
22///
23/// This function checks if all children of the given expression are literals.
24/// If so, it evaluates the expression against a dummy RecordBatch and returns
25/// the result as a new Literal.
26///
27/// # Example transformations
28/// - `1 + 2` -> `3`
29/// - `(1 + 2) * 3` -> `9` (with bottom-up traversal)
30/// - `'hello' || ' world'` -> `'hello world'`
31#[deprecated(
32    since = "53.0.0",
33    note = "This function will be removed in a future release in favor of a private implementation that depends on other implementation details. Please open an issue if you have a use case for keeping it."
34)]
35pub fn simplify_const_expr(
36    expr: Arc<dyn PhysicalExpr>,
37) -> Result<Transformed<Arc<dyn PhysicalExpr>>> {
38    let batch = create_dummy_batch()?;
39    // If expr is already a const literal or can't be evaluated into one.
40    if expr.is::<Literal>()
41        || (!can_evaluate_as_constant(&expr))
42        || (!should_evaluate_const_expr(&expr))
43    {
44        return Ok(Transformed::no(expr));
45    }
46
47    // Evaluate the expression
48    match expr.evaluate(batch) {
49        Ok(ColumnarValue::Scalar(scalar)) => {
50            Ok(Transformed::yes(Arc::new(Literal::new(scalar))))
51        }
52        Ok(ColumnarValue::Array(arr)) if arr.len() == 1 => {
53            // Some operations return an array even for scalar inputs
54            let scalar = ScalarValue::try_from_array(&arr, 0)?;
55            Ok(Transformed::yes(Arc::new(Literal::new(scalar))))
56        }
57        Ok(_) => {
58            // Unexpected result - keep original expression
59            Ok(Transformed::no(expr))
60        }
61        Err(_) => {
62            // On error, keep original expression
63            // The expression might succeed at runtime due to short-circuit evaluation
64            // or other runtime conditions
65            Ok(Transformed::no(expr))
66        }
67    }
68}
69
70/// Simplify expressions whose immediate children are all literals.
71///
72/// This function only checks the direct children of the expression,
73/// not the entire subtree. It is designed to be used with bottom-up tree
74/// traversal, where children are simplified before parents.
75///
76/// # Example transformations
77/// - `1 + 2` -> `3`
78/// - `(1 + 2) * 3` -> `9` (with bottom-up traversal, inner expr simplified first)
79/// - `'hello' || ' world'` -> `'hello world'`
80pub(crate) fn simplify_const_expr_immediate(
81    expr: Arc<dyn PhysicalExpr>,
82    batch: &RecordBatch,
83) -> Result<Transformed<Arc<dyn PhysicalExpr>>> {
84    // Already a literal - nothing to do
85    if expr.is::<Literal>() {
86        return Ok(Transformed::no(expr));
87    }
88
89    // Column references cannot be evaluated at plan time
90    if expr.is::<Column>() {
91        return Ok(Transformed::no(expr));
92    }
93
94    // Volatile nodes cannot be evaluated at plan time
95    if expr.is_volatile_node() {
96        return Ok(Transformed::no(expr));
97    }
98
99    // Since transform visits bottom-up, children have already been simplified.
100    // If all children are now Literals, this node can be const-evaluated.
101    // This is O(k) where k = number of children, instead of O(subtree).
102    //
103    // Leaf nodes (zero children) are rejected here. Const-folding is only
104    // sound for a node whose value is fully determined by its child literals;
105    // a leaf has no children, so there is nothing to derive constness from.
106    // The known leaves that are constant (`Literal`) or known-non-constant
107    // (`Column`, volatile) are handled by the dedicated checks above. Any
108    // other leaf is opaque to the simplifier and must be preserved as-is,
109    // otherwise `all` over an empty child list would vacuously hold and the
110    // node would be evaluated against the dummy batch, producing a value
111    // unrelated to its real runtime semantics.
112    let children = expr.children();
113    if children.is_empty() || !children.iter().all(|c| c.is::<Literal>()) {
114        return Ok(Transformed::no(expr));
115    }
116
117    if !should_evaluate_const_expr(&expr) {
118        return Ok(Transformed::no(expr));
119    }
120
121    // Evaluate the expression
122    match expr.evaluate(batch) {
123        Ok(ColumnarValue::Scalar(scalar)) => {
124            Ok(Transformed::yes(Arc::new(Literal::new(scalar))))
125        }
126        Ok(ColumnarValue::Array(arr)) if arr.len() == 1 => {
127            // Some operations return an array even for scalar inputs
128            let scalar = ScalarValue::try_from_array(&arr, 0)?;
129            Ok(Transformed::yes(Arc::new(Literal::new(scalar))))
130        }
131        Ok(_) => {
132            // Unexpected result - keep original expression
133            Ok(Transformed::no(expr))
134        }
135        Err(_) => {
136            // On error, keep original expression
137            // The expression might succeed at runtime due to short-circuit evaluation
138            // or other runtime conditions
139            Ok(Transformed::no(expr))
140        }
141    }
142}
143
144/// Create a 1-row dummy RecordBatch for evaluating constant expressions.
145///
146/// The batch is never actually accessed for data - it's just needed because
147/// the PhysicalExpr::evaluate API requires a RecordBatch. For expressions
148/// that only contain literals, the batch content is irrelevant.
149///
150/// This is the same approach used in the logical expression `ConstEvaluator`.
151pub(crate) fn create_dummy_batch() -> Result<&'static RecordBatch> {
152    static DUMMY_BATCH: std::sync::OnceLock<Result<RecordBatch>> =
153        std::sync::OnceLock::new();
154    DUMMY_BATCH
155        .get_or_init(|| {
156            // RecordBatch requires at least one column
157            let dummy_schema =
158                Arc::new(Schema::new(vec![Field::new("_", DataType::Null, true)]));
159            let col = new_null_array(&DataType::Null, 1);
160            Ok(RecordBatch::try_new(dummy_schema, vec![col])?)
161        })
162        .as_ref()
163        .map_err(|e| {
164            internal_datafusion_err!(
165                "Failed to create dummy batch for constant expression evaluation: {e}"
166            )
167        })
168}
169
170fn can_evaluate_as_constant(expr: &Arc<dyn PhysicalExpr>) -> bool {
171    let mut can_evaluate = true;
172
173    expr.apply(|e| {
174        if e.is::<Column>() || e.is_volatile_node() {
175            can_evaluate = false;
176            Ok(TreeNodeRecursion::Stop)
177        } else {
178            Ok(TreeNodeRecursion::Continue)
179        }
180    })
181    .expect("apply should not fail");
182
183    can_evaluate
184}
185
186fn should_evaluate_const_expr(expr: &Arc<dyn PhysicalExpr>) -> bool {
187    if let Some(function) = expr.downcast_ref::<ScalarFunctionExpr>() {
188        let Some(args) = function
189            .args()
190            .iter()
191            .map(|arg| arg.downcast_ref::<Literal>().map(Literal::value))
192            .collect::<Option<Vec<_>>>()
193        else {
194            return true;
195        };
196        return function.fun().should_evaluate_const(&args);
197    }
198
199    let Some(binary) = expr.downcast_ref::<BinaryExpr>() else {
200        return true;
201    };
202    if !matches!(
203        binary.op(),
204        Operator::RegexMatch
205            | Operator::RegexNotMatch
206            | Operator::RegexIMatch
207            | Operator::RegexNotIMatch
208    ) {
209        return true;
210    }
211    let Some(pattern) = binary.right().downcast_ref::<Literal>() else {
212        return true;
213    };
214    let Some(pattern) = pattern.value().try_as_str().flatten() else {
215        return true;
216    };
217
218    let mut builder = RegexBuilder::new(pattern);
219    builder.size_limit(REGEX_PLANNING_SIZE_LIMIT_BYTES);
220    if matches!(
221        binary.op(),
222        Operator::RegexIMatch | Operator::RegexNotIMatch
223    ) {
224        builder.case_insensitive(true);
225    }
226    !matches!(builder.build(), Err(RegexError::CompiledTooBig(_)))
227}
228
229/// Check if this expression has any column references.
230#[deprecated(
231    since = "53.0.0",
232    note = "This function isn't used internally and is trivial to implement, therefore it will be removed in a future release."
233)]
234pub fn has_column_references(expr: &Arc<dyn PhysicalExpr>) -> bool {
235    let mut has_columns = false;
236    expr.apply(|expr| {
237        if expr.downcast_ref::<Column>().is_some() {
238            has_columns = true;
239            Ok(TreeNodeRecursion::Stop)
240        } else {
241            Ok(TreeNodeRecursion::Continue)
242        }
243    })
244    .expect("apply should not fail");
245    has_columns
246}