Skip to main content

datafusion_physical_expr_common/
physical_expr.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
5use std::any::Any;
6use std::fmt;
7use std::fmt::{Debug, Display, Formatter};
8use std::hash::{Hash, Hasher};
9use std::sync::Arc;
10
11use crate::utils::scatter;
12
13use arrow::array::{Array, ArrayRef, BooleanArray, new_empty_array};
14use arrow::compute::filter_record_batch;
15use arrow::datatypes::{DataType, Field, FieldRef, Schema};
16use arrow::record_batch::RecordBatch;
17use datafusion_common::tree_node::{
18    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
19};
20use datafusion_common::{
21    Result, ScalarValue, assert_eq_or_internal_err, exec_err, not_impl_err,
22};
23use datafusion_expr_common::columnar_value::ColumnarValue;
24use datafusion_expr_common::dyn_eq::{DynEq, DynHash};
25use datafusion_expr_common::interval_arithmetic::Interval;
26use datafusion_expr_common::placement::ExpressionPlacement;
27use datafusion_expr_common::sort_properties::ExprProperties;
28#[expect(deprecated)]
29use datafusion_expr_common::statistics::Distribution;
30
31use itertools::izip;
32
33/// Shared [`PhysicalExpr`].
34pub type PhysicalExprRef = Arc<dyn PhysicalExpr>;
35
36/// [`PhysicalExpr`]s represent expressions such as `A + 1` or `CAST(c1 AS int)`.
37///
38/// `PhysicalExpr` knows its type, nullability and can be evaluated directly on
39/// a [`RecordBatch`] (see [`Self::evaluate`]).
40///
41/// `PhysicalExpr` are the physical counterpart to [`Expr`] used in logical
42/// planning. They are typically created from [`Expr`] by a [`PhysicalPlanner`]
43/// invoked from a higher level API
44///
45/// Some important examples of `PhysicalExpr` are:
46/// * [`Column`]: Represents a column at a given index in a RecordBatch
47///
48/// To create `PhysicalExpr` from  `Expr`, see
49/// * [`SessionContext::create_physical_expr`]: A high level API
50/// * [`create_physical_expr`]: A low level API
51///
52/// # Formatting `PhysicalExpr` as strings
53/// There are three ways to format `PhysicalExpr` as a string:
54/// * [`Debug`]: Standard Rust debugging format (e.g. `Constant { value: ... }`)
55/// * [`Display`]: Detailed SQL-like format that shows expression structure (e.g. (`Utf8 ("foobar")`). This is often used for debugging and tests
56/// * [`Self::fmt_sql`]: SQL-like human readable format (e.g. ('foobar')`), See also [`sql_fmt`]
57///
58/// [`SessionContext::create_physical_expr`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html#method.create_physical_expr
59/// [`PhysicalPlanner`]: https://docs.rs/datafusion/latest/datafusion/physical_planner/trait.PhysicalPlanner.html
60/// [`Expr`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html
61/// [`create_physical_expr`]: https://docs.rs/datafusion/latest/datafusion/physical_expr/fn.create_physical_expr.html
62/// [`Column`]: https://docs.rs/datafusion/latest/datafusion/physical_expr/expressions/struct.Column.html
63pub trait PhysicalExpr: Any + Send + Sync + Display + Debug + DynEq + DynHash {
64    /// Get the data type of this expression, given the schema of the input.
65    /// Returns an error if the data type cannot be determined, ex. if the
66    /// schema is missing a required field.
67    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
68        Ok(self.return_field(input_schema)?.data_type().to_owned())
69    }
70    /// Determine whether this expression is nullable, given the schema of the input
71    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
72        Ok(self.return_field(input_schema)?.is_nullable())
73    }
74    /// Evaluate an expression against a RecordBatch
75    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue>;
76    /// The output field associated with this expression
77    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
78        Ok(Arc::new(Field::new(
79            format!("{self}"),
80            self.data_type(input_schema)?,
81            self.nullable(input_schema)?,
82        )))
83    }
84    /// Evaluates this expression only for rows where `selection` is `true`.
85    ///
86    /// Rows where `selection` is `false` or null are skipped during evaluation and
87    /// produce `NULL` in the result. Thus, values in those rows cannot trigger
88    /// evaluation errors such as division by zero.
89    ///
90    /// # Example
91    ///
92    /// Given `expr = 4 / val`:
93    ///
94    /// ```text
95    /// val  selection | result
96    ///   0      false |   NULL
97    ///   1       true |      4
98    ///   2       true |      2
99    /// ```
100    ///
101    /// The first row is not evaluated, avoiding division by zero. Its result is
102    /// `NULL`.
103    ///
104    /// # Errors
105    ///
106    /// Returns an `Err` if the expression could not be evaluated or if the length of
107    /// `selection` does not equal the number of rows in `batch`.
108    fn evaluate_selection(
109        &self,
110        batch: &RecordBatch,
111        selection: &BooleanArray,
112    ) -> Result<ColumnarValue> {
113        let row_count = batch.num_rows();
114        if row_count != selection.len() {
115            return exec_err!(
116                "Selection array length does not match batch row count: {} != {row_count}",
117                selection.len()
118            );
119        }
120
121        // First, check if we can avoid filtering altogether.
122        if selection.null_count() == 0 && !selection.has_false() {
123            // All values from the `selection` filter are true and match the input batch.
124            // No need to perform any filtering.
125            return self.evaluate(batch);
126        }
127
128        // Next, prepare the result array for each 'true' row in the selection vector.
129        let filtered_result = if !selection.has_true() {
130            // Do not call `evaluate` when the selection is empty.
131            // `evaluate_selection` is used to conditionally evaluate expressions.
132            // When the expression in question is fallible, evaluating it with an empty
133            // record batch may trigger a runtime error (e.g. division by zero).
134            //
135            // Instead, create an empty array matching the expected return type.
136            let datatype = self.data_type(batch.schema_ref().as_ref())?;
137            ColumnarValue::Array(new_empty_array(&datatype))
138        } else {
139            // If we reach this point, there's no other option than to filter the batch.
140            // This is a fairly costly operation since it requires creating partial copies
141            // (worst case of length `row_count - 1`) of all the arrays in the record batch.
142            // The resulting `filtered_batch` will contain one row per true in `selection`.
143            let filtered_batch = filter_record_batch(batch, selection)?;
144            self.evaluate(&filtered_batch)?
145        };
146
147        // Finally, scatter the filtered result array so that the indices match the input rows again.
148        match &filtered_result {
149            ColumnarValue::Array(a) => {
150                scatter(selection, a.as_ref()).map(ColumnarValue::Array)
151            }
152            ColumnarValue::Scalar(ScalarValue::Boolean(value)) => {
153                // When the scalar is true or false, skip the scatter process
154                if let Some(v) = value {
155                    if *v {
156                        Ok(ColumnarValue::from(Arc::new(selection.clone()) as ArrayRef))
157                    } else {
158                        Ok(filtered_result)
159                    }
160                } else {
161                    let array = BooleanArray::from(vec![None; row_count]);
162                    scatter(selection, &array).map(ColumnarValue::Array)
163                }
164            }
165            ColumnarValue::Scalar(_) => Ok(filtered_result),
166        }
167    }
168
169    /// Get a list of child PhysicalExpr that provide the input for this expr.
170    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>>;
171
172    /// Returns a new PhysicalExpr where all children were replaced by new exprs.
173    ///
174    /// If the implementation returns a [`PhysicalExpr::expression_id`], then
175    /// the identifier should be preserved by the new expression.
176    fn with_new_children(
177        self: Arc<Self>,
178        children: Vec<Arc<dyn PhysicalExpr>>,
179    ) -> Result<Arc<dyn PhysicalExpr>>;
180
181    /// Computes the output interval for the expression, given the input
182    /// intervals.
183    ///
184    /// # Parameters
185    ///
186    /// * `children` are the intervals for the children (inputs) of this
187    ///   expression.
188    ///
189    /// # Returns
190    ///
191    /// A `Result` containing the output interval for the expression in
192    /// case of success, or an error object in case of failure.
193    ///
194    /// Note that the output bounds must form an **envelope** that contains all
195    /// possible outputs of the expression given the input bounds. While
196    /// expressions should output the tightest possible bounds, they do not need
197    /// to be exact and can be conservative.
198    ///
199    /// # Example
200    ///
201    /// If the expression is `a + b`, and the input intervals are `a: [1, 2]`
202    /// and `b: [3, 4]`, then the output interval would be `[4, 6]`.
203    ///
204    /// If the expression is `sin(a)`, it is correct (though not precise) to
205    /// produce the interval `[-1, 1]` for any input interval for `a`.
206    fn evaluate_bounds(&self, _children: &[&Interval]) -> Result<Interval> {
207        not_impl_err!("Not implemented for {self}")
208    }
209
210    /// Updates bounds for child expressions, given a known interval for this
211    /// expression.
212    ///
213    /// This is used to propagate constraints down through an expression tree.
214    ///
215    /// # Parameters
216    ///
217    /// * `interval` is the currently known interval for this expression.
218    /// * `children` are the current intervals for the children of this expression.
219    ///
220    /// # Returns
221    ///
222    /// A `Result` containing a `Vec` of new intervals for the children (in order)
223    /// in case of success, or an error object in case of failure.
224    ///
225    /// If constraint propagation reveals an infeasibility for any child, returns
226    /// [`None`]. If none of the children intervals change as a result of
227    /// propagation, may return an empty vector instead of cloning `children`.
228    /// This is the default (and conservative) return value.
229    ///
230    /// # Example
231    ///
232    /// If the expression is `a + b`, the current `interval` is `[4, 5]` and the
233    /// inputs `a` and `b` are respectively given as `[0, 2]` and `[-∞, 4]`, then
234    /// propagation would return `[0, 2]` and `[2, 4]` as `b` must be at least
235    /// `2` to make the output at least `4`.
236    fn propagate_constraints(
237        &self,
238        _interval: &Interval,
239        _children: &[&Interval],
240    ) -> Result<Option<Vec<Interval>>> {
241        Ok(Some(vec![]))
242    }
243
244    /// Computes the output statistics for the expression, given the input
245    /// statistics.
246    ///
247    /// # Parameters
248    ///
249    /// * `children` are the statistics for the children (inputs) of this
250    ///   expression.
251    ///
252    /// # Returns
253    ///
254    /// A `Result` containing the output statistics for the expression in
255    /// case of success, or an error object in case of failure.
256    ///
257    /// Expressions (should) implement this function and utilize the independence
258    /// assumption, match on children distribution types and compute the output
259    /// statistics accordingly. The default implementation simply creates an
260    /// unknown output distribution by combining input ranges. This logic loses
261    /// distribution information, but is a safe default.
262    #[deprecated(
263        since = "54.0.0",
264        note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
265    )]
266    #[expect(deprecated)]
267    fn evaluate_statistics(&self, children: &[&Distribution]) -> Result<Distribution> {
268        let children_ranges = children
269            .iter()
270            .map(|c| c.range())
271            .collect::<Result<Vec<_>>>()?;
272        let children_ranges_refs = children_ranges.iter().collect::<Vec<_>>();
273        let output_interval = self.evaluate_bounds(children_ranges_refs.as_slice())?;
274        let dt = output_interval.data_type();
275        if dt.eq(&DataType::Boolean) {
276            let p = if output_interval.eq(&Interval::TRUE) {
277                ScalarValue::new_one(&dt)
278            } else if output_interval.eq(&Interval::FALSE) {
279                ScalarValue::new_zero(&dt)
280            } else {
281                ScalarValue::try_from(&dt)
282            }?;
283            Distribution::new_bernoulli(p)
284        } else {
285            Distribution::new_from_interval(output_interval)
286        }
287    }
288
289    /// Updates children statistics using the given parent statistic for this
290    /// expression.
291    ///
292    /// This is used to propagate statistics down through an expression tree.
293    ///
294    /// # Parameters
295    ///
296    /// * `parent` is the currently known statistics for this expression.
297    /// * `children` are the current statistics for the children of this expression.
298    ///
299    /// # Returns
300    ///
301    /// A `Result` containing a `Vec` of new statistics for the children (in order)
302    /// in case of success, or an error object in case of failure.
303    ///
304    /// If statistics propagation reveals an infeasibility for any child, returns
305    /// [`None`]. If none of the children statistics change as a result of
306    /// propagation, may return an empty vector instead of cloning `children`.
307    /// This is the default (and conservative) return value.
308    ///
309    /// Expressions (should) implement this function and apply Bayes rule to
310    /// reconcile and update parent/children statistics. This involves utilizing
311    /// the independence assumption, and matching on distribution types. The
312    /// default implementation simply creates an unknown distribution if it can
313    /// narrow the range by propagating ranges. This logic loses distribution
314    /// information, but is a safe default.
315    #[deprecated(
316        since = "54.0.0",
317        note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
318    )]
319    #[expect(deprecated)]
320    fn propagate_statistics(
321        &self,
322        parent: &Distribution,
323        children: &[&Distribution],
324    ) -> Result<Option<Vec<Distribution>>> {
325        let children_ranges = children
326            .iter()
327            .map(|c| c.range())
328            .collect::<Result<Vec<_>>>()?;
329        let children_ranges_refs = children_ranges.iter().collect::<Vec<_>>();
330        let parent_range = parent.range()?;
331        let Some(propagated_children) =
332            self.propagate_constraints(&parent_range, children_ranges_refs.as_slice())?
333        else {
334            return Ok(None);
335        };
336        izip!(propagated_children.into_iter(), children_ranges, children)
337            .map(|(new_interval, old_interval, child)| {
338                if new_interval == old_interval {
339                    // We weren't able to narrow the range, preserve the old statistics.
340                    Ok((*child).clone())
341                } else if new_interval.data_type().eq(&DataType::Boolean) {
342                    let dt = old_interval.data_type();
343                    let p = if new_interval.eq(&Interval::TRUE) {
344                        ScalarValue::new_one(&dt)
345                    } else if new_interval.eq(&Interval::FALSE) {
346                        ScalarValue::new_zero(&dt)
347                    } else {
348                        unreachable!("Given that we have a range reduction for a boolean interval, we should have certainty")
349                    }?;
350                    Distribution::new_bernoulli(p)
351                } else {
352                    Distribution::new_from_interval(new_interval)
353                }
354            })
355            .collect::<Result<_>>()
356            .map(Some)
357    }
358
359    /// Calculates the properties of this [`PhysicalExpr`] based on its
360    /// children's properties (i.e. order and range), recursively aggregating
361    /// the information from its children. In cases where the [`PhysicalExpr`]
362    /// has no children (e.g., `Literal` or `Column`), these properties should
363    /// be specified externally, as the function defaults to unknown properties.
364    fn get_properties(&self, _children: &[ExprProperties]) -> Result<ExprProperties> {
365        Ok(ExprProperties::new_unknown())
366    }
367
368    /// Format this `PhysicalExpr` in nice human readable "SQL" format
369    ///
370    /// Specifically, this format is designed to be readable by humans, at the
371    /// expense of details. Use `Display` or `Debug` for more detailed
372    /// representation.
373    ///
374    /// See the [`fmt_sql`] function for an example of printing `PhysicalExpr`s as SQL.
375    fn fmt_sql(&self, f: &mut Formatter<'_>) -> fmt::Result;
376
377    /// Take a snapshot of this `PhysicalExpr`, if it is dynamic.
378    ///
379    /// "Dynamic" in this case means containing references to structures that may change
380    /// during plan execution, such as hash tables.
381    ///
382    /// This method is used to capture the current state of `PhysicalExpr`s that may contain
383    /// dynamic references to other operators in order to serialize it over the wire
384    /// or treat it via downcast matching.
385    ///
386    /// You should not call this method directly as it does not handle recursion.
387    /// Instead use [`snapshot_physical_expr`] to handle recursion and capture the
388    /// full state of the `PhysicalExpr`.
389    ///
390    /// This is expected to return "simple" expressions that do not have mutable state
391    /// and are composed of DataFusion's built-in `PhysicalExpr` implementations.
392    /// Callers however should *not* assume anything about the returned expressions
393    /// since callers and implementers may not agree on what "simple" or "built-in"
394    /// means.
395    /// In other words, if you need to serialize a `PhysicalExpr` across the wire
396    /// you should call this method and then try to serialize the result,
397    /// but you should handle unknown or unexpected `PhysicalExpr` implementations gracefully
398    /// just as if you had not called this method at all.
399    ///
400    /// In particular, consider:
401    /// * A `PhysicalExpr` that references the current state of a `datafusion::physical_plan::TopK`
402    ///   that is involved in a query with `SELECT * FROM t1 ORDER BY a LIMIT 10`.
403    ///   This function may return something like `a >= 12`.
404    /// * A `PhysicalExpr` that references the current state of a `datafusion::physical_plan::joins::HashJoinExec`
405    ///   from a query such as `SELECT * FROM t1 JOIN t2 ON t1.a = t2.b`.
406    ///   This function may return something like `t2.b IN (1, 5, 7)`.
407    ///
408    /// A system or function that can only deal with a hardcoded set of `PhysicalExpr` implementations
409    /// or needs to serialize this state to bytes may not be able to handle these dynamic references.
410    /// In such cases, we should return a simplified version of the `PhysicalExpr` that does not
411    /// contain these dynamic references.
412    ///
413    /// Systems that implement remote execution of plans, e.g. serialize a portion of the query plan
414    /// and send it across the wire to a remote executor may want to call this method after
415    /// every batch on the source side and broadcast / update the current snapshot to the remote executor.
416    ///
417    /// Note for implementers: this method should *not* handle recursion.
418    /// Recursion is handled in [`snapshot_physical_expr`].
419    fn snapshot(&self) -> Result<Option<Arc<dyn PhysicalExpr>>> {
420        // By default, we return None to indicate that this PhysicalExpr does not
421        // have any dynamic references or state.
422        // This is a safe default behavior.
423        Ok(None)
424    }
425
426    /// Returns the generation of this `PhysicalExpr` for snapshotting purposes.
427    /// The generation is an arbitrary u64 that can be used to track changes
428    /// in the state of the `PhysicalExpr` over time without having to do an exhaustive comparison.
429    /// This is useful to avoid unnecessary computation or serialization if there are no changes to the expression.
430    /// In particular, dynamic expressions that may change over time; this allows cheap checks for changes.
431    /// Static expressions that do not change over time should return 0, as does the default implementation.
432    /// You should not call this method directly as it does not handle recursion.
433    /// Instead use [`snapshot_generation`] to handle recursion and capture the
434    /// full state of the `PhysicalExpr`.
435    fn snapshot_generation(&self) -> u64 {
436        // By default, we return 0 to indicate that this PhysicalExpr does not
437        // have any dynamic references or state.
438        // Since the recursive algorithm XORs the generations of all children the overall
439        // generation will be 0 if no children have a non-zero generation, meaning that
440        // static expressions will always return 0.
441        0
442    }
443
444    /// Returns true if the expression node is volatile, i.e. whether it can return
445    /// different results when evaluated multiple times with the same input.
446    ///
447    /// Note: unlike [`is_volatile`], this function does not consider inputs:
448    /// - `random()` returns `true`,
449    /// - `a + random()` returns `false` (because the operation `+` itself is not volatile.)
450    ///
451    /// The default to this function was set to `false` when it was created
452    /// to avoid imposing API churn on implementers, but this is not a safe default in general.
453    /// It is highly recommended that volatile expressions implement this method and return `true`.
454    /// This default may be removed in the future if it causes problems or we decide to
455    /// eat the cost of the breaking change and require all implementers to make a choice.
456    fn is_volatile_node(&self) -> bool {
457        false
458    }
459
460    /// Returns placement information for this expression.
461    ///
462    /// This is used by optimizers to make decisions about expression placement,
463    /// such as whether to push expressions down through projections.
464    ///
465    /// The default implementation returns [`ExpressionPlacement::KeepInPlace`].
466    fn placement(&self) -> ExpressionPlacement {
467        ExpressionPlacement::KeepInPlace
468    }
469
470    /// Return a stable, globally-unique identifier for this [`PhysicalExpr`], if it
471    /// has one.
472    ///
473    /// This identifier tracks which expressions which are connected (e.g. `DynamicFilterPhysicalExpr`
474    /// where two expressions may be different but store the same mutable inner state). Tracking
475    /// connected expressions helps preserve referential integrity within plan nodes
476    /// during serialization and deserialization.
477    ///
478    /// This id must be preserved across [`PhysicalExpr::with_new_children`] or any other
479    /// methods which may want to preserve identity.
480    ///
481    /// Default is `None`: the expression has no identity worth preserving across a
482    /// serialization boundary.
483    fn expression_id(&self) -> Option<u64> {
484        None
485    }
486
487    /// Serialize this expression to a [`PhysicalExprNode`] proto message.
488    ///
489    /// Returning `Ok(None)` means "this expression does not know how to
490    /// serialize itself"; the caller (typically `datafusion-proto`) will fall
491    /// back to its existing codec / extension paths. This matches today's
492    /// behavior for expressions that aren't built into `datafusion-proto`.
493    ///
494    /// Returning `Ok(Some(node))` means the expression has serialized itself
495    /// fully; the caller should not try any further fallback path.
496    ///
497    /// Returning `Err(_)` means a real serialization failure (e.g. the
498    /// expression knows it should serialize but a child failed).
499    ///
500    /// The motivating use case is letting expressions with private state
501    /// (e.g. `DynamicFilterPhysicalExpr`'s `RwLock`-protected inner fields)
502    /// reach into their own internals for `try_to_proto`/`try_from_proto`
503    /// without having to expose `pub` accessors to `datafusion-proto`. See
504    /// <https://github.com/apache/datafusion/issues/21835>.
505    ///
506    /// The `try_` prefix matches the fallible `try_from_proto` decode
507    /// constructors; both sides of the round-trip are fallible and named
508    /// consistently.
509    ///
510    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
511    #[cfg(feature = "proto")]
512    fn try_to_proto(
513        &self,
514        _ctx: &proto_encode::PhysicalExprEncodeCtx<'_>,
515    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
516        Ok(None)
517    }
518}
519
520/// Encode-side context for [`PhysicalExpr::try_to_proto`].
521///
522/// Expression authors only ever see [`proto_encode::PhysicalExprEncodeCtx`]:
523/// a concrete struct with stable methods. Internally it dispatches to a
524/// [`proto_encode::PhysicalExprEncode`] implementor that lives in
525/// `datafusion-proto`, which is what lets `physical-expr-common` stay free
526/// of `datafusion-proto` as a dep.
527///
528/// More specialized helpers (e.g. encoding UDFs/UDAFs/UDWFs through the
529/// extension codec) can be added to the context as expressions migrate;
530/// today they're not required because the encoder forwards to the existing
531/// codec via the proto converter.
532#[cfg(feature = "proto")]
533pub mod proto_encode {
534    use std::sync::Arc;
535
536    use datafusion_common::Result;
537    use datafusion_proto_models::protobuf::PhysicalExprNode;
538
539    use super::PhysicalExpr;
540
541    /// Encoder context handed to [`super::PhysicalExpr::try_to_proto`].
542    ///
543    /// Wraps an internal [`PhysicalExprEncode`] trait object so callers see a
544    /// stable concrete type while implementations can evolve in
545    /// `datafusion-proto`.
546    pub struct PhysicalExprEncodeCtx<'a> {
547        encoder: &'a dyn PhysicalExprEncode,
548    }
549
550    impl<'a> PhysicalExprEncodeCtx<'a> {
551        /// Construct a new encode context. Typically called by
552        /// `datafusion-proto`; expression authors receive `&PhysicalExprEncodeCtx`.
553        pub fn new(encoder: &'a dyn PhysicalExprEncode) -> Self {
554            Self { encoder }
555        }
556
557        /// Encode a child expression. Routes through the configured encoder
558        /// so dedup-aware encoding is preserved.
559        pub fn encode_child(
560            &self,
561            expr: &Arc<dyn PhysicalExpr>,
562        ) -> Result<PhysicalExprNode> {
563            self.encoder.encode(expr)
564        }
565
566        /// Encode a sequence of child expressions, preserving order.
567        ///
568        /// Convenience wrapper over [`Self::encode_child`] for expressions
569        /// holding a `repeated` proto field (e.g. the `list` of an `InList`).
570        /// The first encode error short-circuits.
571        pub fn encode_children_expressions<'b, I>(
572            &self,
573            exprs: I,
574        ) -> Result<Vec<PhysicalExprNode>>
575        where
576            I: IntoIterator<Item = &'b Arc<dyn PhysicalExpr>>,
577        {
578            exprs
579                .into_iter()
580                .map(|expr| self.encode_child(expr))
581                .collect()
582        }
583    }
584
585    /// Internal dispatch trait. Implementors live in `datafusion-proto` and
586    /// wrap the existing `PhysicalExtensionCodec` +
587    /// `PhysicalProtoConverterExtension` plumbing. Expression authors should
588    /// use [`PhysicalExprEncodeCtx`] instead of calling this directly.
589    pub trait PhysicalExprEncode {
590        /// Encode an expression to a protobuf node.
591        fn encode(&self, expr: &Arc<dyn PhysicalExpr>) -> Result<PhysicalExprNode>;
592    }
593}
594
595/// Decode-side counterpart to [`proto_encode`].
596///
597/// Expression authors implement an associated `try_from_proto` on their
598/// concrete type, with the signature
599///
600/// ```ignore
601/// fn try_from_proto(
602///     node: &PhysicalExprNode,
603///     ctx: &PhysicalExprDecodeCtx<'_>,
604/// ) -> Result<Arc<dyn PhysicalExpr>>
605/// ```
606///
607/// It takes the whole [`PhysicalExprNode`] — the exact inverse of what
608/// [`PhysicalExpr::try_to_proto`] returns — so the constructor can also see
609/// outer-node fields such as `expr_id`. The central match in
610/// `datafusion-proto` dispatches `ExprType` variants to these constructors.
611///
612/// As with the encode side, the public surface is a struct (not a `&dyn`
613/// trait) so future fields/helpers (registries for third-party expressions,
614/// schema-resolution caches, etc.) can be added without changing the
615/// signature every expression depends on.
616///
617/// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
618#[cfg(feature = "proto")]
619pub mod proto_decode {
620    use std::any::Any;
621    use std::sync::Arc;
622
623    use arrow::datatypes::Schema;
624    use datafusion_common::Result;
625    use datafusion_proto_models::protobuf::PhysicalExprNode;
626
627    use super::PhysicalExpr;
628
629    /// Open the outer [`PhysicalExprNode`] and assert it carries the expected
630    /// `ExprType` variant, returning the inner payload (auto-derefs through
631    /// `Box`) or bailing with an `Internal` error.
632    ///
633    /// Every `try_from_proto` starts with the same six-line `match`:
634    ///
635    /// ```ignore
636    /// let try_cast = match &node.expr_type {
637    ///     Some(protobuf::physical_expr_node::ExprType::TryCast(x)) => x.as_ref(),
638    ///     _ => return internal_err!("PhysicalExprNode is not a TryCastExpr"),
639    /// };
640    /// ```
641    ///
642    /// With this macro that collapses to:
643    ///
644    /// ```ignore
645    /// let try_cast = expect_expr_variant!(
646    ///     node,
647    ///     protobuf::physical_expr_node::ExprType::TryCast,
648    ///     "TryCastExpr",
649    /// );
650    /// ```
651    ///
652    /// Pass the variant as a `::` path so the macro stays agnostic to how
653    /// the caller imports the proto types.
654    #[macro_export]
655    macro_rules! expect_expr_variant {
656        ($node:expr, $variant:path, $expr_name:literal $(,)?) => {{
657            match &$node.expr_type {
658                ::core::option::Option::Some($variant(inner)) => inner,
659                _ => {
660                    return ::datafusion_common::internal_err!(concat!(
661                        "PhysicalExprNode is not a ",
662                        $expr_name
663                    ));
664                }
665            }
666        }};
667    }
668    #[doc(inline)]
669    pub use expect_expr_variant;
670
671    /// Decoder context handed to per-expression `try_from_proto` constructors.
672    ///
673    /// Wraps an internal [`PhysicalExprDecode`] trait object plus a borrowed
674    /// schema. The trait stays an implementation detail of `datafusion-proto`;
675    /// expression authors only see this struct.
676    pub struct PhysicalExprDecodeCtx<'a> {
677        schema: &'a Schema,
678        decoder: &'a dyn PhysicalExprDecode,
679    }
680
681    impl<'a> PhysicalExprDecodeCtx<'a> {
682        /// Construct a new decode context. Typically called by
683        /// `datafusion-proto`; expression authors receive
684        /// `&PhysicalExprDecodeCtx`.
685        pub fn new(schema: &'a Schema, decoder: &'a dyn PhysicalExprDecode) -> Self {
686            Self { schema, decoder }
687        }
688
689        /// The schema bound to this decode context. Use it for column lookups,
690        /// data-type resolution, etc.
691        pub fn schema(&self) -> &Schema {
692            self.schema
693        }
694
695        /// The session this decode runs under, if the decoder supplied one
696        /// and it is a `T`.
697        ///
698        /// `datafusion-proto` supplies its `TaskContext`, so an expression that
699        /// resolves a UDF by name or reads configuration calls
700        /// `ctx.session::<TaskContext>()`. The session is type-erased because
701        /// `TaskContext` is defined in a crate that depends on this one.
702        pub fn session<T: 'static>(&self) -> Option<&T> {
703            self.decoder.session()?.downcast_ref()
704        }
705
706        /// Decode an expression node, recursing into child sub-expressions.
707        ///
708        /// Routes built-in `ExprType` variants through `datafusion-proto`'s
709        /// central match and forwards extension nodes to the registered codec
710        /// (today via [`PhysicalExtensionCodec::try_decode_expr`]; later via
711        /// a per-type registry — see #21835).
712        ///
713        /// [`PhysicalExtensionCodec::try_decode_expr`]: https://docs.rs/datafusion-proto/latest/datafusion_proto/physical_plan/trait.PhysicalExtensionCodec.html#method.try_decode_expr
714        pub fn decode(&self, node: &PhysicalExprNode) -> Result<Arc<dyn PhysicalExpr>> {
715            self.decoder.decode(node, self.schema)
716        }
717
718        /// Decode a required child node, erroring if it is absent.
719        ///
720        /// Proto child expressions are encoded as `Option<Box<PhysicalExprNode>>`;
721        /// pass the field directly (e.g. `node.expr.as_deref()`). `expr_name`
722        /// is the expression being decoded (e.g. `"InListExpr"`) and `field`
723        /// the proto field (e.g. `"expr"`); both are woven into the error so
724        /// it names *where* the missing field is, without each author
725        /// hand-rolling the string.
726        pub fn decode_required_expression(
727            &self,
728            node: Option<&PhysicalExprNode>,
729            expr_name: &str,
730            field: &str,
731        ) -> Result<Arc<dyn PhysicalExpr>> {
732            let node = node.ok_or_else(|| {
733                datafusion_common::internal_datafusion_err!(
734                    "{expr_name} is missing required field '{field}'"
735                )
736            })?;
737            self.decode(node)
738        }
739
740        /// Decode a sequence of child nodes, preserving order.
741        ///
742        /// Convenience wrapper over [`Self::decode`] for expressions holding a
743        /// `repeated` proto field (e.g. the `list` of an `InList`). The first
744        /// decode error short-circuits.
745        pub fn decode_children_expressions<'b, I>(
746            &self,
747            nodes: I,
748        ) -> Result<Vec<Arc<dyn PhysicalExpr>>>
749        where
750            I: IntoIterator<Item = &'b PhysicalExprNode>,
751        {
752            nodes.into_iter().map(|node| self.decode(node)).collect()
753        }
754    }
755
756    /// Unwrap a required non-expression proto field.
757    ///
758    /// Mirrors [`PhysicalExprDecodeCtx::decode_required_expression`] for proto
759    /// fields that aren't [`PhysicalExprNode`]s — e.g. the `arrow_type` of a
760    /// `PhysicalCastNode` or the `scalar` of a `PhysicalLiteralNode`. Keeps
761    /// the "missing required field" message format identical across
762    /// expressions:
763    ///
764    /// ```ignore
765    /// let arrow_type = require_proto_field(
766    ///     cast_expr.arrow_type.as_ref(),
767    ///     "CastExpr",
768    ///     "arrow_type",
769    /// )?;
770    /// ```
771    pub fn require_proto_field<T>(
772        opt: Option<T>,
773        expr_name: &str,
774        field: &str,
775    ) -> Result<T> {
776        opt.ok_or_else(|| {
777            datafusion_common::internal_datafusion_err!(
778                "{expr_name} is missing required field '{field}'"
779            )
780        })
781    }
782
783    /// Internal dispatch trait. Implementors live in `datafusion-proto`.
784    /// Expression authors should use [`PhysicalExprDecodeCtx`] instead of
785    /// calling this directly.
786    pub trait PhysicalExprDecode {
787        /// Decode a proto node into a concrete `PhysicalExpr`. The schema is
788        /// passed alongside so implementations can support recursive children
789        /// and rebind the context per call (e.g. for nested plans).
790        fn decode(
791            &self,
792            node: &PhysicalExprNode,
793            schema: &Schema,
794        ) -> Result<Arc<dyn PhysicalExpr>>;
795
796        /// The session the decode runs under, read through
797        /// [`PhysicalExprDecodeCtx::session`]. Defaults to `None`.
798        fn session(&self) -> Option<&dyn Any> {
799            None
800        }
801    }
802}
803
804impl dyn PhysicalExpr {
805    /// Returns `true` if the expression is of type `T`.
806    ///
807    /// Prefer this over `downcast_ref::<T>().is_some()`. Works correctly when
808    /// called on `Arc<dyn PhysicalExpr>` via auto-deref.
809    pub fn is<T: PhysicalExpr>(&self) -> bool {
810        (self as &dyn Any).is::<T>()
811    }
812
813    /// Attempts to downcast this expression to a concrete type `T`, returning
814    /// `None` if the expression is not of that type.
815    ///
816    /// Works correctly when called on `Arc<dyn PhysicalExpr>` via auto-deref,
817    /// unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would attempt to
818    /// downcast the `Arc` itself.
819    pub fn downcast_ref<T: PhysicalExpr>(&self) -> Option<&T> {
820        (self as &dyn Any).downcast_ref()
821    }
822}
823
824impl PartialEq for dyn PhysicalExpr {
825    fn eq(&self, other: &Self) -> bool {
826        self.dyn_eq(other as &dyn Any)
827    }
828}
829impl Eq for dyn PhysicalExpr {}
830
831impl Hash for dyn PhysicalExpr {
832    fn hash<H: Hasher>(&self, state: &mut H) {
833        self.dyn_hash(state);
834    }
835}
836
837/// Returns a copy of this expr if we change any child according to the pointer comparison.
838/// The size of `children` must be equal to the size of `PhysicalExpr::children()`.
839pub fn with_new_children_if_necessary(
840    expr: Arc<dyn PhysicalExpr>,
841    children: Vec<Arc<dyn PhysicalExpr>>,
842) -> Result<Arc<dyn PhysicalExpr>> {
843    let old_children = expr.children();
844    assert_eq_or_internal_err!(
845        children.len(),
846        old_children.len(),
847        "PhysicalExpr: Wrong number of children"
848    );
849
850    if children.is_empty()
851        || children
852            .iter()
853            .zip(old_children.iter())
854            .any(|(c1, c2)| !Arc::ptr_eq(c1, c2))
855    {
856        Ok(expr.with_new_children(children)?)
857    } else {
858        Ok(expr)
859    }
860}
861
862/// Returns [`Display`] able a list of [`PhysicalExpr`]
863///
864/// Example output: `[a + 1, b]`
865pub fn format_physical_expr_list<T>(exprs: T) -> impl Display
866where
867    T: IntoIterator,
868    T::Item: Display,
869    T::IntoIter: Clone,
870{
871    struct DisplayWrapper<I>(I)
872    where
873        I: Iterator + Clone,
874        I::Item: Display;
875
876    impl<I> Display for DisplayWrapper<I>
877    where
878        I: Iterator + Clone,
879        I::Item: Display,
880    {
881        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
882            let mut iter = self.0.clone();
883            write!(f, "[")?;
884            if let Some(expr) = iter.next() {
885                write!(f, "{expr}")?;
886            }
887            for expr in iter {
888                write!(f, ", {expr}")?;
889            }
890            write!(f, "]")?;
891            Ok(())
892        }
893    }
894
895    DisplayWrapper(exprs.into_iter())
896}
897
898/// Prints a [`PhysicalExpr`] in a SQL-like format
899///
900/// # Example
901/// ```
902/// # // The boilerplate needed to create a `PhysicalExpr` for the example
903/// use std::collections::HashMap;
904/// # use std::fmt::Formatter;
905/// # use std::sync::Arc;
906/// # use arrow::array::RecordBatch;
907/// # use arrow::datatypes::{DataType, Field, FieldRef, Schema};
908/// # use datafusion_common::Result;
909/// # use datafusion_expr_common::columnar_value::ColumnarValue;
910/// # use datafusion_physical_expr_common::physical_expr::{fmt_sql, PhysicalExpr};
911/// # #[derive(Debug, PartialEq, Eq, Hash)]
912/// # struct MyExpr {}
913/// # impl PhysicalExpr for MyExpr {
914/// # fn data_type(&self, input_schema: &Schema) -> Result<DataType> { unimplemented!() }
915/// # fn nullable(&self, input_schema: &Schema) -> Result<bool> { unimplemented!() }
916/// # fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { unimplemented!() }
917/// # fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> { unimplemented!() }
918/// # fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>>{ unimplemented!() }
919/// # fn with_new_children(self: Arc<Self>, children: Vec<Arc<dyn PhysicalExpr>>) -> Result<Arc<dyn PhysicalExpr>> { unimplemented!() }
920/// # fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "CASE a > b THEN 1 ELSE 0 END") }
921/// # }
922/// # impl std::fmt::Display for MyExpr {fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { unimplemented!() } }
923/// # fn make_physical_expr() -> Arc<dyn PhysicalExpr> { Arc::new(MyExpr{}) }
924/// let expr: Arc<dyn PhysicalExpr> = make_physical_expr();
925/// // wrap the expression in `sql_fmt` which can be used with
926/// // `format!`, `to_string()`, etc
927/// let expr_as_sql = fmt_sql(expr.as_ref());
928/// assert_eq!(
929///   "The SQL: CASE a > b THEN 1 ELSE 0 END",
930///   format!("The SQL: {expr_as_sql}")
931/// );
932/// ```
933pub fn fmt_sql(expr: &dyn PhysicalExpr) -> impl Display + '_ {
934    struct Wrapper<'a> {
935        expr: &'a dyn PhysicalExpr,
936    }
937
938    impl Display for Wrapper<'_> {
939        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
940            self.expr.fmt_sql(f)?;
941            Ok(())
942        }
943    }
944
945    Wrapper { expr }
946}
947
948/// Take a snapshot of the given `PhysicalExpr` if it is dynamic.
949///
950/// Take a snapshot of this `PhysicalExpr` if it is dynamic.
951/// This is used to capture the current state of `PhysicalExpr`s that may contain
952/// dynamic references to other operators in order to serialize it over the wire
953/// or treat it via downcast matching.
954///
955/// See the documentation of [`PhysicalExpr::snapshot`] for more details.
956///
957/// # Returns
958///
959/// Returns a snapshot of the `PhysicalExpr` if it is dynamic, otherwise
960/// returns itself.
961pub fn snapshot_physical_expr(
962    expr: Arc<dyn PhysicalExpr>,
963) -> Result<Arc<dyn PhysicalExpr>> {
964    snapshot_physical_expr_opt(expr).data()
965}
966
967/// Take a snapshot of the given `PhysicalExpr` if it is dynamic.
968///
969/// Take a snapshot of this `PhysicalExpr` if it is dynamic.
970/// This is used to capture the current state of `PhysicalExpr`s that may contain
971/// dynamic references to other operators in order to serialize it over the wire
972/// or treat it via downcast matching.
973///
974/// See the documentation of [`PhysicalExpr::snapshot`] for more details.
975///
976/// # Returns
977///
978/// Returns a `[`Transformed`] indicating whether a snapshot was taken,
979/// along with the resulting `PhysicalExpr`.
980pub fn snapshot_physical_expr_opt(
981    expr: Arc<dyn PhysicalExpr>,
982) -> Result<Transformed<Arc<dyn PhysicalExpr>>> {
983    expr.transform_up(|e| {
984        if let Some(snapshot) = e.snapshot()? {
985            Ok(Transformed::yes(snapshot))
986        } else {
987            Ok(Transformed::no(Arc::clone(&e)))
988        }
989    })
990}
991
992/// Check the generation of this `PhysicalExpr`.
993/// Dynamic `PhysicalExpr`s may have a generation that is incremented
994/// every time the state of the `PhysicalExpr` changes.
995/// If the generation changes that means this `PhysicalExpr` or one of its children
996/// has changed since the last time it was evaluated.
997///
998/// This algorithm will not produce collisions as long as the structure of the
999/// `PhysicalExpr` does not change and no `PhysicalExpr` decrements its own generation.
1000pub fn snapshot_generation(expr: &Arc<dyn PhysicalExpr>) -> u64 {
1001    let mut generation = 0u64;
1002    expr.apply(|e| {
1003        // Add the current generation of the `PhysicalExpr` to our global generation.
1004        generation = generation.wrapping_add(e.snapshot_generation());
1005        Ok(TreeNodeRecursion::Continue)
1006    })
1007    .expect("this traversal is infallible");
1008
1009    generation
1010}
1011
1012/// Check if the given `PhysicalExpr` is dynamic.
1013/// Internally this calls [`snapshot_generation`] to check if the generation is non-zero,
1014/// any dynamic `PhysicalExpr` should have a non-zero generation.
1015#[deprecated(
1016    since = "55.0.0",
1017    note = "Downcast to `DynamicFilterPhysicalExpr`, or use \
1018    `DynamicFilterTracking::classify(expr).contains_dynamic_filter()` from \
1019    `datafusion_physical_expr`"
1020)]
1021pub fn is_dynamic_physical_expr(expr: &Arc<dyn PhysicalExpr>) -> bool {
1022    // If the generation is non-zero, then this `PhysicalExpr` is dynamic.
1023    snapshot_generation(expr) != 0
1024}
1025
1026/// Returns true if the expression is volatile, i.e. whether it can return different
1027/// results when evaluated multiple times with the same input.
1028///
1029/// For example the function call `RANDOM()` is volatile as each call will
1030/// return a different value.
1031///
1032/// This method recursively checks if any sub-expression is volatile, for example
1033/// `1 + RANDOM()` will return `true`.
1034pub fn is_volatile(expr: &Arc<dyn PhysicalExpr>) -> bool {
1035    if expr.is_volatile_node() {
1036        return true;
1037    }
1038    let mut is_volatile = false;
1039    expr.apply(|e| {
1040        if e.is_volatile_node() {
1041            is_volatile = true;
1042            Ok(TreeNodeRecursion::Stop)
1043        } else {
1044            Ok(TreeNodeRecursion::Continue)
1045        }
1046    })
1047    .expect("infallible closure should not fail");
1048    is_volatile
1049}
1050
1051#[cfg(test)]
1052mod test {
1053    use crate::physical_expr::PhysicalExpr;
1054    use arrow::array::{Array, BooleanArray, Int64Array, RecordBatch};
1055    use arrow::datatypes::{DataType, Schema};
1056    use datafusion_expr_common::columnar_value::ColumnarValue;
1057    use std::fmt::{Display, Formatter};
1058    use std::sync::Arc;
1059
1060    #[derive(Debug, PartialEq, Eq, Hash)]
1061    struct TestExpr {}
1062
1063    impl PhysicalExpr for TestExpr {
1064        fn data_type(&self, _schema: &Schema) -> datafusion_common::Result<DataType> {
1065            Ok(DataType::Int64)
1066        }
1067
1068        fn nullable(&self, _schema: &Schema) -> datafusion_common::Result<bool> {
1069            Ok(false)
1070        }
1071
1072        fn evaluate(
1073            &self,
1074            batch: &RecordBatch,
1075        ) -> datafusion_common::Result<ColumnarValue> {
1076            let data = vec![1; batch.num_rows()];
1077            Ok(ColumnarValue::Array(Arc::new(Int64Array::from(data))))
1078        }
1079
1080        fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
1081            vec![]
1082        }
1083
1084        fn with_new_children(
1085            self: Arc<Self>,
1086            _children: Vec<Arc<dyn PhysicalExpr>>,
1087        ) -> datafusion_common::Result<Arc<dyn PhysicalExpr>> {
1088            Ok(Arc::new(Self {}))
1089        }
1090
1091        fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1092            f.write_str("TestExpr")
1093        }
1094    }
1095
1096    impl Display for TestExpr {
1097        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1098            self.fmt_sql(f)
1099        }
1100    }
1101
1102    macro_rules! assert_arrays_eq {
1103        ($EXPECTED: expr, $ACTUAL: expr, $MESSAGE: expr) => {
1104            let expected = $EXPECTED.to_array(1).unwrap();
1105            let actual = $ACTUAL;
1106
1107            let actual_array = actual.to_array(expected.len()).unwrap();
1108            let actual_ref = actual_array.as_ref();
1109            let expected_ref = expected.as_ref();
1110            assert!(
1111                actual_ref == expected_ref,
1112                "{}: expected: {:?}, actual: {:?}",
1113                $MESSAGE,
1114                $EXPECTED,
1115                actual_ref
1116            );
1117        };
1118    }
1119
1120    fn test_evaluate_selection(
1121        batch: &RecordBatch,
1122        selection: &BooleanArray,
1123        expected: &ColumnarValue,
1124    ) {
1125        let expr = TestExpr {};
1126
1127        // First check that the `evaluate_selection` is the expected one
1128        let selection_result = expr.evaluate_selection(batch, selection).unwrap();
1129        assert_eq!(
1130            expected.to_array(1).unwrap().len(),
1131            selection_result.to_array(1).unwrap().len(),
1132            "evaluate_selection should output row count should match input record batch"
1133        );
1134        assert_arrays_eq!(
1135            expected,
1136            &selection_result,
1137            "evaluate_selection returned unexpected value"
1138        );
1139
1140        // If we're selecting all rows, the result should be the same as calling `evaluate`
1141        // with the full record batch.
1142        if (0..batch.num_rows())
1143            .all(|row_idx| row_idx < selection.len() && selection.value(row_idx))
1144        {
1145            let empty_result = expr.evaluate(batch).unwrap();
1146
1147            assert_arrays_eq!(
1148                empty_result,
1149                &selection_result,
1150                "evaluate_selection does not match unfiltered evaluate result"
1151            );
1152        }
1153    }
1154
1155    fn test_evaluate_selection_error(batch: &RecordBatch, selection: &BooleanArray) {
1156        let expr = TestExpr {};
1157
1158        // First check that the `evaluate_selection` is the expected one
1159        let selection_result = expr.evaluate_selection(batch, selection);
1160        assert!(selection_result.is_err(), "evaluate_selection should fail");
1161    }
1162
1163    #[test]
1164    pub fn test_evaluate_selection_with_empty_record_batch() {
1165        test_evaluate_selection(
1166            &RecordBatch::new_empty(Arc::new(Schema::empty())),
1167            &BooleanArray::from(vec![false; 0]),
1168            &ColumnarValue::Array(Arc::new(Int64Array::new_null(0))),
1169        );
1170    }
1171
1172    #[test]
1173    pub fn test_evaluate_selection_with_empty_record_batch_with_larger_false_selection() {
1174        test_evaluate_selection_error(
1175            &RecordBatch::new_empty(Arc::new(Schema::empty())),
1176            &BooleanArray::from(vec![false; 10]),
1177        );
1178    }
1179
1180    #[test]
1181    pub fn test_evaluate_selection_with_empty_record_batch_with_larger_true_selection() {
1182        test_evaluate_selection_error(
1183            &RecordBatch::new_empty(Arc::new(Schema::empty())),
1184            &BooleanArray::from(vec![true; 10]),
1185        );
1186    }
1187
1188    #[test]
1189    pub fn test_evaluate_selection_with_non_empty_record_batch() {
1190        test_evaluate_selection(
1191            &unsafe { RecordBatch::new_unchecked(Arc::new(Schema::empty()), vec![], 10) },
1192            &BooleanArray::from(vec![true; 10]),
1193            &ColumnarValue::Array(Arc::new(Int64Array::from(vec![1; 10]))),
1194        );
1195    }
1196
1197    #[test]
1198    pub fn test_evaluate_selection_with_non_empty_record_batch_with_larger_false_selection()
1199     {
1200        test_evaluate_selection_error(
1201            &unsafe { RecordBatch::new_unchecked(Arc::new(Schema::empty()), vec![], 10) },
1202            &BooleanArray::from(vec![false; 20]),
1203        );
1204    }
1205
1206    #[test]
1207    pub fn test_evaluate_selection_with_non_empty_record_batch_with_larger_true_selection()
1208     {
1209        test_evaluate_selection_error(
1210            &unsafe { RecordBatch::new_unchecked(Arc::new(Schema::empty()), vec![], 10) },
1211            &BooleanArray::from(vec![true; 20]),
1212        );
1213    }
1214
1215    #[test]
1216    pub fn test_evaluate_selection_with_non_empty_record_batch_with_smaller_false_selection()
1217     {
1218        test_evaluate_selection_error(
1219            &unsafe { RecordBatch::new_unchecked(Arc::new(Schema::empty()), vec![], 10) },
1220            &BooleanArray::from(vec![false; 5]),
1221        );
1222    }
1223
1224    #[test]
1225    pub fn test_evaluate_selection_with_non_empty_record_batch_with_smaller_true_selection()
1226     {
1227        test_evaluate_selection_error(
1228            &unsafe { RecordBatch::new_unchecked(Arc::new(Schema::empty()), vec![], 10) },
1229            &BooleanArray::from(vec![true; 5]),
1230        );
1231    }
1232}
1233
1234#[cfg(all(test, feature = "proto"))]
1235mod proto_helper_tests {
1236    use datafusion_common::DataFusionError;
1237    use datafusion_proto_models::protobuf::{
1238        self, PhysicalColumn, PhysicalExprNode, physical_expr_node,
1239    };
1240
1241    use crate::expect_expr_variant;
1242    use crate::physical_expr::proto_decode::require_proto_field;
1243
1244    fn column_node() -> PhysicalExprNode {
1245        PhysicalExprNode {
1246            expr_id: None,
1247            expr_type: Some(physical_expr_node::ExprType::Column(PhysicalColumn {
1248                name: "a".to_string(),
1249                index: 0,
1250            })),
1251        }
1252    }
1253
1254    #[test]
1255    fn require_proto_field_returns_inner() {
1256        let v = require_proto_field(Some(7_u32), "FooExpr", "answer").unwrap();
1257        assert_eq!(v, 7);
1258    }
1259
1260    #[test]
1261    fn require_proto_field_reports_missing() {
1262        let err = require_proto_field::<u32>(None, "FooExpr", "answer").unwrap_err();
1263        assert!(matches!(
1264            err,
1265            DataFusionError::Internal(msg)
1266                if msg.contains("FooExpr is missing required field 'answer'")
1267        ));
1268    }
1269
1270    fn expect_column(
1271        node: &PhysicalExprNode,
1272    ) -> Result<&PhysicalColumn, DataFusionError> {
1273        let inner =
1274            expect_expr_variant!(node, physical_expr_node::ExprType::Column, "Column",);
1275        Ok(inner)
1276    }
1277
1278    #[test]
1279    fn expect_expr_variant_returns_inner_payload() {
1280        let node = column_node();
1281        let col = expect_column(&node).unwrap();
1282        assert_eq!(col.name, "a");
1283    }
1284
1285    #[test]
1286    fn expect_expr_variant_rejects_wrong_variant() {
1287        let node = PhysicalExprNode {
1288            expr_id: None,
1289            expr_type: Some(physical_expr_node::ExprType::Negative(Box::new(
1290                protobuf::PhysicalNegativeNode { expr: None },
1291            ))),
1292        };
1293        let err = expect_column(&node).unwrap_err();
1294        assert!(matches!(
1295            err,
1296            DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a Column")
1297        ));
1298    }
1299
1300    #[test]
1301    fn expect_expr_variant_rejects_missing_expr_type() {
1302        let node = PhysicalExprNode {
1303            expr_id: None,
1304            expr_type: None,
1305        };
1306        let err = expect_column(&node).unwrap_err();
1307        assert!(matches!(
1308            err,
1309            DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a Column")
1310        ));
1311    }
1312}