Skip to main content

datafusion_physical_expr/
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::sync::Arc;
6
7use crate::expressions::{self, Column};
8use crate::{LexOrdering, PhysicalSortExpr, create_physical_expr};
9
10use arrow::compute::SortOptions;
11use arrow::datatypes::{DataType, Schema, SchemaRef};
12use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
13use datafusion_common::{DFSchema, HashMap, ScalarValue, SplitPoint};
14use datafusion_common::{Result, plan_err};
15use datafusion_expr::execution_props::ExecutionProps;
16use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
17use datafusion_expr::{Expr, Partitioning as LogicalPartitioning, SortExpr};
18use datafusion_expr_common::casts::try_cast_literal_to_type;
19
20use itertools::izip;
21// Exports:
22use crate::{Partitioning, RangePartitioning};
23pub(crate) use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
24
25/// Adds the `offset` value to `Column` indices inside `expr`. This function is
26/// generally used during the update of the right table schema in join operations.
27pub fn add_offset_to_expr(
28    expr: Arc<dyn PhysicalExpr>,
29    offset: isize,
30) -> Result<Arc<dyn PhysicalExpr>> {
31    expr.transform_down(|e| match e.downcast_ref::<Column>() {
32        Some(col) => {
33            let Some(idx) = col.index().checked_add_signed(offset) else {
34                return plan_err!("Column index overflow");
35            };
36            Ok(Transformed::yes(Arc::new(Column::new(col.name(), idx))))
37        }
38        None => Ok(Transformed::no(e)),
39    })
40    .data()
41}
42
43/// This function is similar to the `contains` method of `Vec`. It finds
44/// whether `expr` is among `physical_exprs`.
45pub fn physical_exprs_contains(
46    physical_exprs: &[Arc<dyn PhysicalExpr>],
47    expr: &Arc<dyn PhysicalExpr>,
48) -> bool {
49    physical_exprs
50        .iter()
51        .any(|physical_expr| physical_expr.as_ref().eq(expr.as_ref()))
52}
53
54/// Checks whether the given physical expression slices are equal.
55pub fn physical_exprs_equal(
56    lhs: &[Arc<dyn PhysicalExpr>],
57    rhs: &[Arc<dyn PhysicalExpr>],
58) -> bool {
59    lhs.len() == rhs.len()
60        && izip!(lhs, rhs).all(|(lhs, rhs)| lhs.as_ref().eq(rhs.as_ref()))
61}
62
63/// Checks whether the given physical expression slices are equal in the sense
64/// of bags (multi-sets), disregarding their orderings.
65pub fn physical_exprs_bag_equal(
66    lhs: &[Arc<dyn PhysicalExpr>],
67    rhs: &[Arc<dyn PhysicalExpr>],
68) -> bool {
69    let mut multi_set_lhs: HashMap<_, usize> = HashMap::with_capacity(lhs.len());
70    let mut multi_set_rhs: HashMap<_, usize> = HashMap::with_capacity(rhs.len());
71    for expr in lhs {
72        *multi_set_lhs.entry(expr).or_insert(0) += 1;
73    }
74    for expr in rhs {
75        *multi_set_rhs.entry(expr).or_insert(0) += 1;
76    }
77    multi_set_lhs == multi_set_rhs
78}
79
80/// Converts logical sort expressions to physical sort expressions.
81///
82/// This function transforms a collection of logical sort expressions into their
83/// physical representation that can be used during query execution.
84///
85/// # Arguments
86///
87/// * `schema` - The schema containing column definitions.
88/// * `sort_order` - A collection of logical sort expressions grouped into
89///   lexicographic orderings.
90///
91/// # Returns
92///
93/// A vector of lexicographic orderings for physical execution, or an error if
94/// the transformation fails.
95///
96/// # Examples
97///
98/// ```
99/// // Create orderings from columns "id" and "name"
100/// # use arrow::datatypes::{Schema, Field, DataType};
101/// # use datafusion_physical_expr::create_ordering;
102/// # use datafusion_common::Column;
103/// # use datafusion_expr::{Expr, SortExpr};
104/// #
105/// // Create a schema with two fields
106/// let schema = Schema::new(vec![
107///     Field::new("id", DataType::Int32, false),
108///     Field::new("name", DataType::Utf8, false),
109/// ]);
110///
111/// let sort_exprs = vec![
112///     vec![SortExpr {
113///         expr: Expr::Column(Column::new(Some("t"), "id")),
114///         asc: true,
115///         nulls_first: false,
116///     }],
117///     vec![SortExpr {
118///         expr: Expr::Column(Column::new(Some("t"), "name")),
119///         asc: false,
120///         nulls_first: true,
121///     }],
122/// ];
123/// let result = create_ordering(&schema, &sort_exprs).unwrap();
124/// ```
125pub fn create_ordering(
126    schema: &Schema,
127    sort_order: &[Vec<SortExpr>],
128) -> Result<Vec<LexOrdering>> {
129    let mut all_sort_orders = Vec::with_capacity(sort_order.len());
130
131    for (group_idx, exprs) in sort_order.iter().enumerate() {
132        // Construct PhysicalSortExpr objects from Expr objects:
133        let mut sort_exprs = Vec::with_capacity(exprs.len());
134        for (expr_idx, sort) in exprs.iter().enumerate() {
135            match &sort.expr {
136                Expr::Column(col) => match expressions::col(&col.name, schema) {
137                    Ok(expr) => {
138                        let opts = SortOptions::new(!sort.asc, sort.nulls_first);
139                        sort_exprs.push(PhysicalSortExpr::new(expr, opts));
140                    }
141                    // Cannot find expression in the projected_schema, stop iterating
142                    // since rest of the orderings are violated
143                    Err(_) => break,
144                },
145                expr => {
146                    return plan_err!(
147                        "Expected single column reference in sort_order[{}][{}], got {}",
148                        group_idx,
149                        expr_idx,
150                        expr
151                    );
152                }
153            }
154        }
155        all_sort_orders.extend(LexOrdering::new(sort_exprs));
156    }
157    Ok(all_sort_orders)
158}
159
160/// Creates a vector of [LexOrdering] from a vector of logical expression
161pub fn create_lex_ordering(
162    schema: &SchemaRef,
163    sort_order: &[Vec<SortExpr>],
164    execution_props: &ExecutionProps,
165) -> Result<Vec<LexOrdering>> {
166    // Try the fast path that only supports column references first
167    // This avoids creating a DFSchema
168    if let Ok(ordering) = create_ordering(schema, sort_order) {
169        return Ok(ordering);
170    }
171
172    let df_schema = DFSchema::try_from(Arc::clone(schema))?;
173
174    let mut all_sort_orders = Vec::with_capacity(sort_order.len());
175
176    for exprs in sort_order.iter() {
177        all_sort_orders.extend(LexOrdering::new(create_physical_sort_exprs(
178            exprs,
179            &df_schema,
180            execution_props,
181            &PhysicalPlanningContext::default(),
182        )?));
183    }
184    Ok(all_sort_orders)
185}
186
187/// Create a physical sort expression from a logical expression
188///
189/// See [`create_physical_expr`] for details on the `planning_ctx` argument.
190pub fn create_physical_sort_expr(
191    e: &SortExpr,
192    input_dfschema: &DFSchema,
193    execution_props: &ExecutionProps,
194    planning_ctx: &PhysicalPlanningContext,
195) -> Result<PhysicalSortExpr> {
196    create_physical_expr(&e.expr, input_dfschema, execution_props, planning_ctx).map(
197        |expr| {
198            let options = SortOptions::new(!e.asc, e.nulls_first);
199            PhysicalSortExpr::new(expr, options)
200        },
201    )
202}
203
204/// Create vector of physical sort expression from a vector of logical expression
205///
206/// See [`create_physical_expr`] for details on the `planning_ctx` argument.
207pub fn create_physical_sort_exprs(
208    exprs: &[SortExpr],
209    input_dfschema: &DFSchema,
210    execution_props: &ExecutionProps,
211    planning_ctx: &PhysicalPlanningContext,
212) -> Result<Vec<PhysicalSortExpr>> {
213    exprs
214        .iter()
215        .map(|e| {
216            create_physical_sort_expr(e, input_dfschema, execution_props, planning_ctx)
217        })
218        .collect()
219}
220
221/// Create physical partitioning from logical partitioning.
222///
223/// See [`create_physical_expr`] for details on the `planning_ctx` argument.
224pub fn create_physical_partitioning(
225    partitioning: &LogicalPartitioning,
226    input_dfschema: &DFSchema,
227    execution_props: &ExecutionProps,
228    planning_ctx: &PhysicalPlanningContext,
229) -> Result<Partitioning> {
230    match partitioning {
231        LogicalPartitioning::RoundRobinBatch(n) => Ok(Partitioning::RoundRobinBatch(*n)),
232        LogicalPartitioning::Hash(exprs, partition_count) => {
233            let exprs = exprs
234                .iter()
235                .map(|expr| {
236                    create_physical_expr(
237                        expr,
238                        input_dfschema,
239                        execution_props,
240                        planning_ctx,
241                    )
242                })
243                .collect::<Result<Vec<_>>>()?;
244            Ok(Partitioning::Hash(exprs, *partition_count))
245        }
246        LogicalPartitioning::Range(range) => {
247            let ordering = create_physical_sort_exprs(
248                range.ordering(),
249                input_dfschema,
250                execution_props,
251                planning_ctx,
252            )?;
253            let Some(ordering) = LexOrdering::new(ordering) else {
254                return plan_err!("Range partitioning requires non-empty ordering");
255            };
256            let split_points = normalize_range_split_points(
257                &ordering,
258                range.split_points(),
259                input_dfschema.as_arrow(),
260            )?;
261            let range = RangePartitioning::try_new(ordering, split_points)?;
262            Ok(Partitioning::Range(range))
263        }
264        LogicalPartitioning::DistributeBy(_) => {
265            datafusion_common::not_impl_err!(
266                "Physical plan does not support DistributeBy partitioning"
267            )
268        }
269    }
270}
271
272fn normalize_range_split_points(
273    ordering: &LexOrdering,
274    split_points: &[SplitPoint],
275    schema: &Schema,
276) -> Result<Vec<SplitPoint>> {
277    split_points
278        .iter()
279        .enumerate()
280        .map(|(split_idx, split_point)| {
281            let values = split_point
282                .values()
283                .iter()
284                .zip(ordering.iter())
285                .enumerate()
286                .map(|(value_idx, (value, sort_expr))| {
287                    let target_type = sort_expr.expr.data_type(schema)?;
288                    normalize_range_split_point_value(
289                        value,
290                        &target_type,
291                        split_idx,
292                        value_idx,
293                    )
294                })
295                .collect::<Result<Vec<_>>>()?;
296            Ok(SplitPoint::new(values))
297        })
298        .collect()
299}
300
301fn normalize_range_split_point_value(
302    value: &ScalarValue,
303    target_type: &DataType,
304    split_idx: usize,
305    value_idx: usize,
306) -> Result<ScalarValue> {
307    let value_type = value.data_type();
308    if &value_type == target_type {
309        return Ok(value.clone());
310    }
311
312    if let Some(casted) = try_cast_literal_to_type(value, target_type) {
313        // Split points define physical partition boundaries, so normalization
314        // must reject casts that would change the advertised boundary.
315        if try_cast_literal_to_type(&casted, &value_type).as_ref() == Some(value) {
316            return Ok(casted);
317        }
318    }
319
320    plan_err!(
321        "Range output partitioning split point {split_idx} value {value_idx} with type {value_type} cannot be represented exactly as ordering expression type {target_type}"
322    )
323}
324
325pub fn add_offset_to_physical_sort_exprs(
326    sort_exprs: impl IntoIterator<Item = PhysicalSortExpr>,
327    offset: isize,
328) -> Result<Vec<PhysicalSortExpr>> {
329    sort_exprs
330        .into_iter()
331        .map(|mut sort_expr| {
332            sort_expr.expr = add_offset_to_expr(sort_expr.expr, offset)?;
333            Ok(sort_expr)
334        })
335        .collect()
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    use crate::expressions::{BinaryExpr, Literal, UnKnownColumn};
343    use crate::physical_expr::{
344        physical_exprs_bag_equal, physical_exprs_contains, physical_exprs_equal,
345    };
346    use datafusion_physical_expr_common::physical_expr::is_volatile;
347
348    use arrow::datatypes::DataType;
349    use arrow::record_batch::RecordBatch;
350    use datafusion_common::ScalarValue;
351    use datafusion_expr::ColumnarValue;
352    use datafusion_expr::Operator;
353    use std::fmt;
354
355    #[test]
356    fn test_physical_exprs_contains() {
357        let lit_true = Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))
358            as Arc<dyn PhysicalExpr>;
359        let lit_false = Arc::new(Literal::new(ScalarValue::Boolean(Some(false))))
360            as Arc<dyn PhysicalExpr>;
361        let lit4 =
362            Arc::new(Literal::new(ScalarValue::Int32(Some(4)))) as Arc<dyn PhysicalExpr>;
363        let lit2 =
364            Arc::new(Literal::new(ScalarValue::Int32(Some(2)))) as Arc<dyn PhysicalExpr>;
365        let lit1 =
366            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))) as Arc<dyn PhysicalExpr>;
367        let col_a_expr = Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>;
368        let col_b_expr = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;
369        let col_c_expr = Arc::new(Column::new("c", 2)) as Arc<dyn PhysicalExpr>;
370
371        // lit(true), lit(false), lit(4), lit(2), Col(a), Col(b)
372        let physical_exprs: Vec<Arc<dyn PhysicalExpr>> = vec![
373            Arc::clone(&lit_true),
374            Arc::clone(&lit_false),
375            Arc::clone(&lit4),
376            Arc::clone(&lit2),
377            Arc::clone(&col_a_expr),
378            Arc::clone(&col_b_expr),
379        ];
380        // below expressions are inside physical_exprs
381        assert!(physical_exprs_contains(&physical_exprs, &lit_true));
382        assert!(physical_exprs_contains(&physical_exprs, &lit2));
383        assert!(physical_exprs_contains(&physical_exprs, &col_b_expr));
384
385        // below expressions are not inside physical_exprs
386        assert!(!physical_exprs_contains(&physical_exprs, &col_c_expr));
387        assert!(!physical_exprs_contains(&physical_exprs, &lit1));
388
389        let unknown = Arc::new(UnKnownColumn::new("unknown")) as Arc<dyn PhysicalExpr>;
390        assert!(!physical_exprs_contains(
391            std::slice::from_ref(&unknown),
392            &unknown
393        ));
394    }
395
396    #[test]
397    fn test_physical_exprs_equal() {
398        let lit_true = Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))
399            as Arc<dyn PhysicalExpr>;
400        let lit_false = Arc::new(Literal::new(ScalarValue::Boolean(Some(false))))
401            as Arc<dyn PhysicalExpr>;
402        let lit1 =
403            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))) as Arc<dyn PhysicalExpr>;
404        let lit2 =
405            Arc::new(Literal::new(ScalarValue::Int32(Some(2)))) as Arc<dyn PhysicalExpr>;
406        let col_b_expr = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;
407
408        let vec1 = vec![Arc::clone(&lit_true), Arc::clone(&lit_false)];
409        let vec2 = vec![Arc::clone(&lit_true), Arc::clone(&col_b_expr)];
410        let vec3 = vec![Arc::clone(&lit2), Arc::clone(&lit1)];
411        let vec4 = vec![Arc::clone(&lit_true), Arc::clone(&lit_false)];
412
413        // these vectors are same
414        assert!(physical_exprs_equal(&vec1, &vec1));
415        assert!(physical_exprs_equal(&vec1, &vec4));
416        assert!(physical_exprs_bag_equal(&vec1, &vec1));
417        assert!(physical_exprs_bag_equal(&vec1, &vec4));
418
419        // these vectors are different
420        assert!(!physical_exprs_equal(&vec1, &vec2));
421        assert!(!physical_exprs_equal(&vec1, &vec3));
422        assert!(!physical_exprs_bag_equal(&vec1, &vec2));
423        assert!(!physical_exprs_bag_equal(&vec1, &vec3));
424
425        let unknown = Arc::new(UnKnownColumn::new("unknown")) as Arc<dyn PhysicalExpr>;
426        assert!(!physical_exprs_equal(
427            std::slice::from_ref(&unknown),
428            std::slice::from_ref(&unknown)
429        ));
430    }
431
432    #[test]
433    fn test_physical_exprs_set_equal() {
434        let list1: Vec<Arc<dyn PhysicalExpr>> = vec![
435            Arc::new(Column::new("a", 0)),
436            Arc::new(Column::new("a", 0)),
437            Arc::new(Column::new("b", 1)),
438        ];
439        let list2: Vec<Arc<dyn PhysicalExpr>> = vec![
440            Arc::new(Column::new("b", 1)),
441            Arc::new(Column::new("b", 1)),
442            Arc::new(Column::new("a", 0)),
443        ];
444        assert!(!physical_exprs_bag_equal(
445            list1.as_slice(),
446            list2.as_slice()
447        ));
448        assert!(!physical_exprs_bag_equal(
449            list2.as_slice(),
450            list1.as_slice()
451        ));
452        assert!(!physical_exprs_equal(list1.as_slice(), list2.as_slice()));
453        assert!(!physical_exprs_equal(list2.as_slice(), list1.as_slice()));
454
455        let list3: Vec<Arc<dyn PhysicalExpr>> = vec![
456            Arc::new(Column::new("a", 0)),
457            Arc::new(Column::new("b", 1)),
458            Arc::new(Column::new("c", 2)),
459            Arc::new(Column::new("a", 0)),
460            Arc::new(Column::new("b", 1)),
461        ];
462        let list4: Vec<Arc<dyn PhysicalExpr>> = vec![
463            Arc::new(Column::new("b", 1)),
464            Arc::new(Column::new("b", 1)),
465            Arc::new(Column::new("a", 0)),
466            Arc::new(Column::new("c", 2)),
467            Arc::new(Column::new("a", 0)),
468        ];
469        assert!(physical_exprs_bag_equal(list3.as_slice(), list4.as_slice()));
470        assert!(physical_exprs_bag_equal(list4.as_slice(), list3.as_slice()));
471        assert!(physical_exprs_bag_equal(list3.as_slice(), list3.as_slice()));
472        assert!(physical_exprs_bag_equal(list4.as_slice(), list4.as_slice()));
473        assert!(!physical_exprs_equal(list3.as_slice(), list4.as_slice()));
474        assert!(!physical_exprs_equal(list4.as_slice(), list3.as_slice()));
475        assert!(physical_exprs_bag_equal(list3.as_slice(), list3.as_slice()));
476        assert!(physical_exprs_bag_equal(list4.as_slice(), list4.as_slice()));
477    }
478
479    #[test]
480    fn test_is_volatile_default_behavior() {
481        // Test that default PhysicalExpr implementations are not volatile
482        let literal =
483            Arc::new(Literal::new(ScalarValue::Int32(Some(42)))) as Arc<dyn PhysicalExpr>;
484        let column = Arc::new(Column::new("test", 0)) as Arc<dyn PhysicalExpr>;
485
486        // Test is_volatile_node() - should return false by default
487        assert!(!literal.is_volatile_node());
488        assert!(!column.is_volatile_node());
489
490        // Test is_volatile() - should return false for non-volatile expressions
491        assert!(!is_volatile(&literal));
492        assert!(!is_volatile(&column));
493    }
494
495    /// Mock volatile PhysicalExpr for testing purposes
496    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
497    struct MockVolatileExpr {
498        volatile: bool,
499    }
500
501    impl MockVolatileExpr {
502        fn new(volatile: bool) -> Self {
503            Self { volatile }
504        }
505    }
506
507    impl fmt::Display for MockVolatileExpr {
508        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
509            write!(f, "MockVolatile({})", self.volatile)
510        }
511    }
512
513    impl PhysicalExpr for MockVolatileExpr {
514        fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
515            Ok(DataType::Boolean)
516        }
517
518        fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
519            Ok(false)
520        }
521
522        fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
523            Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(
524                self.volatile,
525            ))))
526        }
527
528        fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
529            vec![]
530        }
531
532        fn with_new_children(
533            self: Arc<Self>,
534            _children: Vec<Arc<dyn PhysicalExpr>>,
535        ) -> Result<Arc<dyn PhysicalExpr>> {
536            Ok(self)
537        }
538
539        fn is_volatile_node(&self) -> bool {
540            self.volatile
541        }
542
543        fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544            write!(f, "mock_volatile({})", self.volatile)
545        }
546    }
547
548    #[test]
549    fn test_nested_expression_volatility() {
550        // Test that is_volatile() recursively detects volatility in expression trees
551
552        // Create a volatile mock expression
553        let volatile_expr =
554            Arc::new(MockVolatileExpr::new(true)) as Arc<dyn PhysicalExpr>;
555        assert!(volatile_expr.is_volatile_node());
556        assert!(is_volatile(&volatile_expr));
557
558        // Create a non-volatile mock expression
559        let stable_expr = Arc::new(MockVolatileExpr::new(false)) as Arc<dyn PhysicalExpr>;
560        assert!(!stable_expr.is_volatile_node());
561        assert!(!is_volatile(&stable_expr));
562
563        // Create a literal (non-volatile)
564        let literal =
565            Arc::new(Literal::new(ScalarValue::Int32(Some(42)))) as Arc<dyn PhysicalExpr>;
566        assert!(!literal.is_volatile_node());
567        assert!(!is_volatile(&literal));
568
569        // Test composite expression: volatile_expr AND literal
570        // The BinaryExpr itself is not volatile, but contains a volatile child
571        let composite_expr = Arc::new(BinaryExpr::new(
572            Arc::clone(&volatile_expr),
573            Operator::And,
574            Arc::clone(&literal),
575        )) as Arc<dyn PhysicalExpr>;
576
577        assert!(!composite_expr.is_volatile_node()); // BinaryExpr itself is not volatile
578        assert!(is_volatile(&composite_expr)); // But it contains a volatile child
579
580        // Test composite expression with all non-volatile children
581        let stable_composite = Arc::new(BinaryExpr::new(
582            Arc::clone(&stable_expr),
583            Operator::And,
584            Arc::clone(&literal),
585        )) as Arc<dyn PhysicalExpr>;
586
587        assert!(!stable_composite.is_volatile_node());
588        assert!(!is_volatile(&stable_composite)); // No volatile children
589    }
590}