Skip to main content

datafusion_physical_expr/utils/
mod.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
5mod guarantee;
6pub use guarantee::{Guarantee, LiteralGuarantee};
7
8use std::borrow::Borrow;
9use std::sync::Arc;
10
11use crate::expressions::{BinaryExpr, Column, Literal};
12use crate::tree_node::ExprContext;
13use crate::{
14    AcrossPartitions, ConstExpr, EquivalenceProperties, PhysicalExpr, PhysicalSortExpr,
15};
16
17use arrow::datatypes::Schema;
18use datafusion_common::tree_node::{
19    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
20};
21use datafusion_common::{HashMap, HashSet, Result};
22use datafusion_expr::Operator;
23
24use petgraph::graph::NodeIndex;
25use petgraph::stable_graph::StableGraph;
26
27/// Assume the predicate is in the form of CNF, split the predicate to a Vec of PhysicalExprs.
28///
29/// For example, split "a1 = a2 AND b1 <= b2 AND c1 != c2" into ["a1 = a2", "b1 <= b2", "c1 != c2"]
30pub fn split_conjunction(
31    predicate: &Arc<dyn PhysicalExpr>,
32) -> Vec<&Arc<dyn PhysicalExpr>> {
33    split_impl(Operator::And, predicate, vec![])
34}
35
36impl ConstExpr {
37    /// Collects predicate-derived constants from equality conjunctions.
38    ///
39    /// For each equality predicate of the form `lhs = rhs`, if either side is
40    /// already known constant according to `input_eqs`, or is a literal, then
41    /// the other side is also constant and will be returned as a [`ConstExpr`].
42    ///
43    /// Literals are treated as uniform constants across partitions, so
44    /// `col = literal` produces a constant for `col` with the literal value.
45    ///
46    /// For example, given predicate `a = 5 AND b = c` where `c` is already
47    /// known constant, this returns constants for both `a` (Uniform with value
48    /// 5) and `b` (propagating `c`'s across-partitions value).
49    pub fn collect_predicate_constants(
50        input_eqs: &EquivalenceProperties,
51        predicate: &Arc<dyn PhysicalExpr>,
52    ) -> Vec<ConstExpr> {
53        /// Returns the `AcrossPartitions` value for `expr` if it is constant:
54        /// either already known constant in `input_eqs`, or a `Literal`
55        /// (which is inherently constant across all partitions).
56        fn expr_constant_or_literal(
57            expr: &Arc<dyn PhysicalExpr>,
58            input_eqs: &EquivalenceProperties,
59        ) -> Option<AcrossPartitions> {
60            input_eqs.is_expr_constant(expr).or_else(|| {
61                expr.downcast_ref::<Literal>()
62                    .map(|l| AcrossPartitions::Uniform(Some(l.value().clone())))
63            })
64        }
65
66        let mut constants = Vec::new();
67        for conjunction in split_conjunction(predicate) {
68            if let Some(binary) = conjunction.downcast_ref::<BinaryExpr>()
69                && binary.op() == &Operator::Eq
70            {
71                // Check if either side is constant — either already known
72                // constant from the input equivalence properties, or a literal
73                // value (which is inherently constant across all partitions).
74                let left_const = expr_constant_or_literal(binary.left(), input_eqs);
75                let right_const = expr_constant_or_literal(binary.right(), input_eqs);
76
77                if let Some(left_across) = left_const {
78                    // LEFT is constant, so RIGHT must also be constant.
79                    // Use RIGHT's known across value if available, otherwise
80                    // propagate LEFT's (e.g. Uniform from a literal).
81                    let across = right_const.unwrap_or(left_across);
82                    constants.push(ConstExpr::new(Arc::clone(binary.right()), across));
83                } else if let Some(right_across) = right_const {
84                    // RIGHT is constant, so LEFT must also be constant.
85                    constants
86                        .push(ConstExpr::new(Arc::clone(binary.left()), right_across));
87                }
88            }
89        }
90
91        constants
92    }
93}
94
95/// Create a conjunction of the given predicates.
96/// If the input is empty, return a literal true.
97/// If the input contains a single predicate, return the predicate.
98/// Otherwise, return a conjunction of the predicates (e.g. `a AND b AND c`).
99pub fn conjunction(
100    predicates: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,
101) -> Arc<dyn PhysicalExpr> {
102    conjunction_opt(predicates).unwrap_or_else(|| crate::expressions::lit(true))
103}
104
105/// Create a conjunction of the given predicates.
106/// If the input is empty or the return None.
107/// If the input contains a single predicate, return Some(predicate).
108/// Otherwise, return a Some(..) of a conjunction of the predicates (e.g. `Some(a AND b AND c)`).
109pub fn conjunction_opt(
110    predicates: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,
111) -> Option<Arc<dyn PhysicalExpr>> {
112    predicates
113        .into_iter()
114        .fold(None, |acc, predicate| match acc {
115            None => Some(predicate),
116            Some(acc) => Some(Arc::new(BinaryExpr::new(acc, Operator::And, predicate))),
117        })
118}
119
120/// Assume the predicate is in the form of DNF, split the predicate to a Vec of PhysicalExprs.
121///
122/// For example, split "a1 = a2 OR b1 <= b2 OR c1 != c2" into ["a1 = a2", "b1 <= b2", "c1 != c2"]
123pub fn split_disjunction(
124    predicate: &Arc<dyn PhysicalExpr>,
125) -> Vec<&Arc<dyn PhysicalExpr>> {
126    split_impl(Operator::Or, predicate, vec![])
127}
128
129fn split_impl<'a>(
130    operator: Operator,
131    predicate: &'a Arc<dyn PhysicalExpr>,
132    mut exprs: Vec<&'a Arc<dyn PhysicalExpr>>,
133) -> Vec<&'a Arc<dyn PhysicalExpr>> {
134    match predicate.downcast_ref::<BinaryExpr>() {
135        Some(binary) if binary.op() == &operator => {
136            let exprs = split_impl(operator, binary.left(), exprs);
137            split_impl(operator, binary.right(), exprs)
138        }
139        Some(_) | None => {
140            exprs.push(predicate);
141            exprs
142        }
143    }
144}
145
146/// This function maps back requirement after ProjectionExec
147/// to the Executor for its input.
148// Specifically, `ProjectionExec` changes index of `Column`s in the schema of its input executor.
149// This function changes requirement given according to ProjectionExec schema to the requirement
150// according to schema of input executor to the ProjectionExec.
151// For instance, Column{"a", 0} would turn to Column{"a", 1}. Please note that this function assumes that
152// name of the Column is unique. If we have a requirement such that Column{"a", 0}, Column{"a", 1}.
153// This function will produce incorrect result (It will only emit single Column as a result).
154pub fn map_columns_before_projection(
155    parent_required: &[Arc<dyn PhysicalExpr>],
156    proj_exprs: &[(Arc<dyn PhysicalExpr>, String)],
157) -> Vec<Arc<dyn PhysicalExpr>> {
158    if parent_required.is_empty() {
159        // No need to build mapping.
160        return vec![];
161    }
162    let column_mapping = proj_exprs
163        .iter()
164        .filter_map(|(expr, name)| {
165            expr.downcast_ref::<Column>()
166                .map(|column| (name.clone(), column.clone()))
167        })
168        .collect::<HashMap<_, _>>();
169    parent_required
170        .iter()
171        .filter_map(|r| {
172            r.downcast_ref::<Column>()
173                .and_then(|c| column_mapping.get(c.name()))
174        })
175        .map(|e| Arc::new(e.clone()) as _)
176        .collect()
177}
178
179/// This function returns all `Arc<dyn PhysicalExpr>`s inside the given
180/// `PhysicalSortExpr` sequence.
181pub fn convert_to_expr<T: Borrow<PhysicalSortExpr>>(
182    sequence: impl IntoIterator<Item = T>,
183) -> Vec<Arc<dyn PhysicalExpr>> {
184    sequence
185        .into_iter()
186        .map(|elem| Arc::clone(&elem.borrow().expr))
187        .collect()
188}
189
190/// This function finds the indices of `targets` within `items` using strict
191/// equality.
192pub fn get_indices_of_exprs_strict<T: Borrow<Arc<dyn PhysicalExpr>>>(
193    targets: impl IntoIterator<Item = T>,
194    items: &[Arc<dyn PhysicalExpr>],
195) -> Vec<usize> {
196    targets
197        .into_iter()
198        .filter_map(|target| items.iter().position(|e| e.eq(target.borrow())))
199        .collect()
200}
201
202pub type ExprTreeNode<T> = ExprContext<Option<T>>;
203
204/// This struct is used to convert a [`PhysicalExpr`] tree into a DAEG (i.e. an expression
205/// DAG) by collecting identical expressions in one node. Caller specifies the node type
206/// in the DAEG via the `constructor` argument, which constructs nodes in the DAEG from
207/// the [`ExprTreeNode`] ancillary object.
208struct PhysicalExprDAEGBuilder<'a, T, F: Fn(&ExprTreeNode<NodeIndex>) -> Result<T>> {
209    // The resulting DAEG (expression DAG).
210    graph: StableGraph<T, usize>,
211    // A vector of visited expression nodes and their corresponding node indices.
212    visited_plans: Vec<(Arc<dyn PhysicalExpr>, NodeIndex)>,
213    // A function to convert an input expression node to T.
214    constructor: &'a F,
215}
216
217impl<T, F: Fn(&ExprTreeNode<NodeIndex>) -> Result<T>> PhysicalExprDAEGBuilder<'_, T, F> {
218    // This method mutates an expression node by transforming it to a physical expression
219    // and adding it to the graph. The method returns the mutated expression node.
220    fn mutate(
221        &mut self,
222        mut node: ExprTreeNode<NodeIndex>,
223    ) -> Result<Transformed<ExprTreeNode<NodeIndex>>> {
224        // Get the expression associated with the input expression node.
225        let expr = &node.expr;
226
227        // Check if the expression has already been visited.
228        let node_idx = match self.visited_plans.iter().find(|(e, _)| expr.eq(e)) {
229            // If the expression has been visited, return the corresponding node index.
230            Some((_, idx)) => *idx,
231            // If the expression has not been visited, add a new node to the graph and
232            // add edges to its child nodes. Add the visited expression to the vector
233            // of visited expressions and return the newly created node index.
234            None => {
235                let node_idx = self.graph.add_node((self.constructor)(&node)?);
236                for expr_node in node.children.iter() {
237                    self.graph.add_edge(node_idx, expr_node.data.unwrap(), 0);
238                }
239                self.visited_plans.push((Arc::clone(expr), node_idx));
240                node_idx
241            }
242        };
243        // Set the data field of the input expression node to the corresponding node index.
244        node.data = Some(node_idx);
245        // Return the mutated expression node.
246        Ok(Transformed::yes(node))
247    }
248}
249
250// A function that builds a directed acyclic graph of physical expression trees.
251pub fn build_dag<T, F>(
252    expr: Arc<dyn PhysicalExpr>,
253    constructor: &F,
254) -> Result<(NodeIndex, StableGraph<T, usize>)>
255where
256    F: Fn(&ExprTreeNode<NodeIndex>) -> Result<T>,
257{
258    // Create a new expression tree node from the input expression.
259    let init = ExprTreeNode::new_default(expr);
260    // Create a new `PhysicalExprDAEGBuilder` instance.
261    let mut builder = PhysicalExprDAEGBuilder {
262        graph: StableGraph::<T, usize>::new(),
263        visited_plans: Vec::<(Arc<dyn PhysicalExpr>, NodeIndex)>::new(),
264        constructor,
265    };
266    // Use the builder to transform the expression tree node into a DAG.
267    let root = init.transform_up(|node| builder.mutate(node)).data()?;
268    // Return a tuple containing the root node index and the DAG.
269    Ok((root.data.unwrap(), builder.graph))
270}
271
272/// Recursively extract referenced [`Column`]s within a [`PhysicalExpr`].
273pub fn collect_columns(expr: &Arc<dyn PhysicalExpr>) -> HashSet<Column> {
274    let mut columns = HashSet::<Column>::new();
275    expr.apply(|expr| {
276        if let Some(column) = expr.downcast_ref::<Column>() {
277            columns.get_or_insert_with(column, |c| c.clone());
278        }
279        Ok(TreeNodeRecursion::Continue)
280    })
281    // pre_visit always returns OK, so this will always too
282    .expect("no way to return error during recursion");
283    columns
284}
285
286/// Re-assign indices of [`Column`]s within the given [`PhysicalExpr`] according to
287/// the provided [`Schema`].
288///
289/// This can be useful when attempting to map an expression onto a different schema.
290///
291/// # Errors
292///
293/// This function will return an error if any column in the expression cannot be found
294/// in the provided schema.
295pub fn reassign_expr_columns(
296    expr: Arc<dyn PhysicalExpr>,
297    schema: &Schema,
298) -> Result<Arc<dyn PhysicalExpr>> {
299    expr.transform_down(|expr| {
300        if let Some(column) = expr.downcast_ref::<Column>() {
301            let index = schema.index_of(column.name())?;
302
303            return Ok(Transformed::yes(Arc::new(Column::new(
304                column.name(),
305                index,
306            ))));
307        }
308        Ok(Transformed::no(expr))
309    })
310    .data()
311}
312
313#[cfg(test)]
314pub(crate) mod tests {
315
316    use std::fmt::{Display, Formatter};
317
318    use super::*;
319    use crate::expressions::{Literal, binary, cast, col, in_list, lit};
320
321    use arrow::array::{ArrayRef, Float32Array, Float64Array};
322    use arrow::datatypes::{DataType, Field};
323    use datafusion_common::{ScalarValue, exec_err, internal_datafusion_err};
324    use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
325    use datafusion_expr::{
326        ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
327    };
328
329    use petgraph::visit::Bfs;
330
331    #[derive(Debug, PartialEq, Eq, Hash)]
332    pub struct TestScalarUDF {
333        pub(crate) signature: Signature,
334    }
335
336    impl TestScalarUDF {
337        pub fn new() -> Self {
338            use DataType::*;
339            Self {
340                signature: Signature::uniform(
341                    1,
342                    vec![Float64, Float32],
343                    Volatility::Immutable,
344                ),
345            }
346        }
347    }
348
349    impl ScalarUDFImpl for TestScalarUDF {
350        fn name(&self) -> &str {
351            "test-scalar-udf"
352        }
353
354        fn signature(&self) -> &Signature {
355            &self.signature
356        }
357
358        fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
359            let arg_type = &arg_types[0];
360
361            match arg_type {
362                DataType::Float32 => Ok(DataType::Float32),
363                _ => Ok(DataType::Float64),
364            }
365        }
366
367        fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {
368            Ok(input[0].sort_properties)
369        }
370
371        fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
372            let args = ColumnarValue::values_to_arrays(&args.args)?;
373
374            let arr: ArrayRef = match args[0].data_type() {
375                DataType::Float64 => Arc::new({
376                    let arg = &args[0]
377                        .as_any()
378                        .downcast_ref::<Float64Array>()
379                        .ok_or_else(|| {
380                            internal_datafusion_err!(
381                                "could not cast {} to {}",
382                                self.name(),
383                                std::any::type_name::<Float64Array>()
384                            )
385                        })?;
386
387                    arg.iter()
388                        .map(|a| a.map(f64::floor))
389                        .collect::<Float64Array>()
390                }),
391                DataType::Float32 => Arc::new({
392                    let arg = &args[0]
393                        .as_any()
394                        .downcast_ref::<Float32Array>()
395                        .ok_or_else(|| {
396                            internal_datafusion_err!(
397                                "could not cast {} to {}",
398                                self.name(),
399                                std::any::type_name::<Float32Array>()
400                            )
401                        })?;
402
403                    arg.iter()
404                        .map(|a| a.map(f32::floor))
405                        .collect::<Float32Array>()
406                }),
407                other => {
408                    return exec_err!(
409                        "Unsupported data type {other:?} for function {}",
410                        self.name()
411                    );
412                }
413            };
414            Ok(ColumnarValue::Array(arr))
415        }
416    }
417
418    #[derive(Clone)]
419    struct DummyProperty {
420        expr_type: String,
421    }
422
423    /// This is a dummy node in the DAEG; it stores a reference to the actual
424    /// [PhysicalExpr] as well as a dummy property.
425    #[derive(Clone)]
426    struct PhysicalExprDummyNode {
427        pub expr: Arc<dyn PhysicalExpr>,
428        pub property: DummyProperty,
429    }
430
431    impl Display for PhysicalExprDummyNode {
432        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
433            write!(f, "{}", self.expr)
434        }
435    }
436
437    fn make_dummy_node(node: &ExprTreeNode<NodeIndex>) -> Result<PhysicalExprDummyNode> {
438        let expr = Arc::clone(&node.expr);
439        let dummy_property = if expr.is::<BinaryExpr>() {
440            "Binary"
441        } else if expr.is::<Column>() {
442            "Column"
443        } else if expr.is::<Literal>() {
444            "Literal"
445        } else {
446            "Other"
447        }
448        .to_owned();
449        Ok(PhysicalExprDummyNode {
450            expr,
451            property: DummyProperty {
452                expr_type: dummy_property,
453            },
454        })
455    }
456
457    #[test]
458    fn test_build_dag() -> Result<()> {
459        let schema = Schema::new(vec![
460            Field::new("0", DataType::Int32, true),
461            Field::new("1", DataType::Int32, true),
462            Field::new("2", DataType::Int32, true),
463        ]);
464        let expr = binary(
465            cast(
466                binary(
467                    col("0", &schema)?,
468                    Operator::Plus,
469                    col("1", &schema)?,
470                    &schema,
471                )?,
472                &schema,
473                DataType::Int64,
474            )?,
475            Operator::Gt,
476            binary(
477                cast(col("2", &schema)?, &schema, DataType::Int64)?,
478                Operator::Plus,
479                lit(ScalarValue::Int64(Some(10))),
480                &schema,
481            )?,
482            &schema,
483        )?;
484        let mut vector_dummy_props = vec![];
485        let (root, graph) = build_dag(expr, &make_dummy_node)?;
486        let mut bfs = Bfs::new(&graph, root);
487        while let Some(node_index) = bfs.next(&graph) {
488            let node = &graph[node_index];
489            vector_dummy_props.push(node.property.clone());
490        }
491
492        assert_eq!(
493            vector_dummy_props
494                .iter()
495                .filter(|property| property.expr_type == "Binary")
496                .count(),
497            3
498        );
499        assert_eq!(
500            vector_dummy_props
501                .iter()
502                .filter(|property| property.expr_type == "Column")
503                .count(),
504            3
505        );
506        assert_eq!(
507            vector_dummy_props
508                .iter()
509                .filter(|property| property.expr_type == "Literal")
510                .count(),
511            1
512        );
513        assert_eq!(
514            vector_dummy_props
515                .iter()
516                .filter(|property| property.expr_type == "Other")
517                .count(),
518            2
519        );
520        Ok(())
521    }
522
523    #[test]
524    fn test_convert_to_expr() -> Result<()> {
525        let schema = Schema::new(vec![Field::new("a", DataType::UInt64, false)]);
526        let sort_expr = vec![PhysicalSortExpr {
527            expr: col("a", &schema)?,
528            options: Default::default(),
529        }];
530        assert!(convert_to_expr(&sort_expr)[0].eq(&sort_expr[0].expr));
531        Ok(())
532    }
533
534    #[test]
535    fn test_get_indices_of_exprs_strict() {
536        let list1: Vec<Arc<dyn PhysicalExpr>> = vec![
537            Arc::new(Column::new("a", 0)),
538            Arc::new(Column::new("b", 1)),
539            Arc::new(Column::new("c", 2)),
540            Arc::new(Column::new("d", 3)),
541        ];
542        let list2: Vec<Arc<dyn PhysicalExpr>> = vec![
543            Arc::new(Column::new("b", 1)),
544            Arc::new(Column::new("c", 2)),
545            Arc::new(Column::new("a", 0)),
546        ];
547        assert_eq!(get_indices_of_exprs_strict(&list1, &list2), vec![2, 0, 1]);
548        assert_eq!(get_indices_of_exprs_strict(&list2, &list1), vec![1, 2, 0]);
549    }
550
551    #[test]
552    fn test_reassign_expr_columns_in_list() {
553        let int_field = Field::new("should_not_matter", DataType::Int64, true);
554        let dict_field = Field::new(
555            "id",
556            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
557            true,
558        );
559        let schema_small = Arc::new(Schema::new(vec![dict_field.clone()]));
560        let schema_big = Arc::new(Schema::new(vec![int_field, dict_field]));
561        let pred = in_list(
562            Arc::new(Column::new_with_schema("id", &schema_big).unwrap()),
563            vec![lit(ScalarValue::Dictionary(
564                Box::new(DataType::Int32),
565                Box::new(ScalarValue::from("2")),
566            ))],
567            &false,
568            &schema_big,
569        )
570        .unwrap();
571
572        let actual = reassign_expr_columns(pred, &schema_small).unwrap();
573
574        let expected = in_list(
575            Arc::new(Column::new_with_schema("id", &schema_small).unwrap()),
576            vec![lit(ScalarValue::Dictionary(
577                Box::new(DataType::Int32),
578                Box::new(ScalarValue::from("2")),
579            ))],
580            &false,
581            &schema_small,
582        )
583        .unwrap();
584
585        assert_eq!(actual.as_ref(), expected.as_ref());
586    }
587
588    #[test]
589    fn test_collect_columns() -> Result<()> {
590        let expr1 = Arc::new(Column::new("col1", 2)) as _;
591        let mut expected = HashSet::new();
592        expected.insert(Column::new("col1", 2));
593        assert_eq!(collect_columns(&expr1), expected);
594
595        let expr2 = Arc::new(Column::new("col2", 5)) as _;
596        let mut expected = HashSet::new();
597        expected.insert(Column::new("col2", 5));
598        assert_eq!(collect_columns(&expr2), expected);
599
600        let expr3 = Arc::new(BinaryExpr::new(expr1, Operator::Plus, expr2)) as _;
601        let mut expected = HashSet::new();
602        expected.insert(Column::new("col1", 2));
603        expected.insert(Column::new("col2", 5));
604        assert_eq!(collect_columns(&expr3), expected);
605        Ok(())
606    }
607
608    #[test]
609    fn test_collect_predicate_constants_propagates_uniform_literal_value() -> Result<()> {
610        let schema = Arc::new(Schema::new(vec![Field::new(
611            "ticker",
612            DataType::Utf8,
613            false,
614        )]));
615        let predicate = binary(
616            col("ticker", schema.as_ref())?,
617            Operator::Eq,
618            lit(ScalarValue::Utf8(Some("NGJ26".to_string()))),
619            schema.as_ref(),
620        )?;
621        let eq_properties = EquivalenceProperties::new(schema);
622
623        let constants =
624            ConstExpr::collect_predicate_constants(&eq_properties, &predicate);
625
626        assert_eq!(constants.len(), 1);
627        assert_eq!(
628            constants[0].across_partitions,
629            AcrossPartitions::Uniform(Some(ScalarValue::Utf8(Some("NGJ26".to_string()))))
630        );
631
632        Ok(())
633    }
634}