Skip to main content

datafusion_optimizer/
utils.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Utility functions leveraged by the query optimizer rules
6
7use std::collections::{BTreeSet, HashMap, HashSet};
8
9use crate::analyzer::type_coercion::TypeCoercionRewriter;
10use arrow::array::{Array, RecordBatch, new_null_array};
11use arrow::datatypes::{DataType, Field, Schema};
12use datafusion_common::TableReference;
13use datafusion_common::cast::as_boolean_array;
14use datafusion_common::tree_node::{TransformedResult, TreeNode, TreeNodeRecursion};
15use datafusion_common::{Column, DFSchema, Result, ScalarValue};
16use datafusion_expr::execution_props::ExecutionProps;
17use datafusion_expr::expr::{Exists, InSubquery, SetComparison};
18use datafusion_expr::expr_rewriter::replace_col;
19use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
20use datafusion_expr::{
21    ColumnarValue, DistinctHandling, Expr, WriteOp, logical_plan::LogicalPlan,
22};
23use datafusion_physical_expr::create_physical_expr;
24use log::{debug, trace};
25use std::sync::Arc;
26
27/// Re-export of `NamesPreserver` for backwards compatibility,
28/// as it was initially placed here and then moved elsewhere.
29pub use datafusion_expr::expr_rewriter::NamePreserver;
30
31/// Whether an expression is free of volatile functions and subqueries.
32/// Subqueries are conservative barriers because their plans may contain
33/// volatile expressions that [`Expr::is_volatile`] does not visit.
34pub(crate) fn is_repeatable(expr: &Expr) -> bool {
35    !expr
36        .exists(|expr| {
37            Ok(expr.is_volatile_node()
38                || matches!(
39                    expr,
40                    Expr::Exists(_)
41                        | Expr::InSubquery(_)
42                        | Expr::SetComparison(_)
43                        | Expr::ScalarSubquery(_)
44                ))
45        })
46        .expect("expression traversal is infallible")
47}
48
49/// Whether an aggregate can safely ignore repeated input rows. This holds when
50/// the function declares [`DistinctHandling::Insensitive`], or when it is
51/// called with `DISTINCT` and declares [`DistinctHandling::Sensitive`], so that
52/// its accumulator removes the repeated rows itself. Arguments, FILTER, and
53/// ORDER BY must also be repeatable: MIN(random()) still observes repetitions.
54pub(crate) fn is_duplicate_insensitive_aggregate(mut expr: &Expr) -> bool {
55    while let Expr::Alias(alias) = expr {
56        expr = &alias.expr;
57    }
58    let Expr::AggregateFunction(aggregate) = expr else {
59        return false;
60    };
61    let ignores_duplicates = match aggregate.func.distinct_handling() {
62        DistinctHandling::Insensitive => true,
63        DistinctHandling::Sensitive => aggregate.params.distinct,
64        // The accumulator does not implement `DISTINCT` and may silently
65        // compute the non-distinct answer, so the flag proves nothing.
66        // Variants added in the future are treated the same way.
67        _ => false,
68    };
69    ignores_duplicates && is_repeatable(expr)
70}
71
72/// Return the expression schema for a MERGE DML node.
73pub(crate) fn merge_into_schema(plan: &LogicalPlan) -> Result<Option<DFSchema>> {
74    let LogicalPlan::Dml(dml) = plan else {
75        return Ok(None);
76    };
77    let WriteOp::MergeInto(_) = &dml.op else {
78        return Ok(None);
79    };
80    dml.merge_schema().map(Some)
81}
82
83/// Invokes `f` with the index, within `schema`, of every column referenced by
84/// `expr` — including columns reached through a correlated subquery's outer
85/// references. Columns absent from `schema` are skipped.
86///
87/// A subquery's own plan is intentionally not traversed: its internal columns
88/// index into its own schema, not `schema`; only the outer (correlated) columns
89/// it references from `schema` are relevant. The comparison expression of an
90/// `IN`/set-comparison subquery is reached by the normal expression walk.
91///
92/// This is the shared primitive behind the top-down "which of a node's output
93/// columns does an ancestor still need" analyses, namely
94/// [`OptimizeProjections`](crate::optimize_projections::OptimizeProjections)
95/// and [`EliminateJoin`](crate::eliminate_join::EliminateJoin). The two keep
96/// their own required-index containers (an ordered set vs. a hash set), so this
97/// reports indices through a callback rather than populating a shared type.
98pub(crate) fn for_each_referenced_index(
99    expr: &Expr,
100    schema: &DFSchema,
101    mut f: impl FnMut(usize),
102) -> Result<()> {
103    visit_referenced_indices(expr, schema, &mut f)
104}
105
106fn visit_referenced_indices(
107    expr: &Expr,
108    schema: &DFSchema,
109    f: &mut dyn FnMut(usize),
110) -> Result<()> {
111    expr.apply(|expr| {
112        match expr {
113            Expr::Column(column) | Expr::OuterReferenceColumn(_, column) => {
114                if let Some(idx) = schema.maybe_index_of_column(column) {
115                    f(idx);
116                }
117            }
118            Expr::Exists(Exists { subquery, .. })
119            | Expr::InSubquery(InSubquery { subquery, .. })
120            | Expr::SetComparison(SetComparison { subquery, .. })
121            | Expr::ScalarSubquery(subquery) => {
122                for outer in &subquery.outer_ref_columns {
123                    visit_referenced_indices(outer, schema, f)?;
124                }
125            }
126            _ => {}
127        }
128        Ok(TreeNodeRecursion::Continue)
129    })?;
130    Ok(())
131}
132
133/// Returns true if `expr` contains all columns in `schema_cols`
134pub(crate) fn has_all_column_refs(
135    expr: &Expr,
136    schema_cols: &HashSet<ColumnReference>,
137) -> bool {
138    let column_refs = expr.column_refs();
139    // note can't use HashSet::intersect because of different types (owned vs References)
140    column_refs
141        .iter()
142        .filter(|c| {
143            schema_cols.contains(&ColumnReference::new(c.relation.as_ref(), c.name()))
144        })
145        .count()
146        == column_refs.len()
147}
148
149pub(crate) fn replace_qualified_name(
150    expr: Expr,
151    cols: &BTreeSet<Column>,
152    subquery_alias: &str,
153) -> Result<Expr> {
154    let alias_cols: Vec<Column> = cols
155        .iter()
156        .map(|col| Column::new(Some(subquery_alias), &col.name))
157        .collect();
158    let replace_map: HashMap<&Column, &Column> =
159        cols.iter().zip(alias_cols.iter()).collect();
160
161    replace_col(expr, &replace_map)
162}
163
164/// Column reference to avoid copying string around
165#[derive(PartialEq, Eq, Hash, Debug)]
166pub(crate) struct ColumnReference<'a> {
167    pub relation: Option<&'a TableReference>,
168    pub name: &'a str,
169}
170
171impl<'a> ColumnReference<'a> {
172    pub fn new(relation: Option<&'a TableReference>, name: &'a str) -> Self {
173        Self { relation, name }
174    }
175
176    pub fn new_unqualified(name: &'a str) -> Self {
177        Self {
178            relation: None,
179            name,
180        }
181    }
182}
183
184/// Returns references to all columns in the schema
185pub(crate) fn schema_columns(schema: &DFSchema) -> HashSet<ColumnReference<'_>> {
186    schema
187        .iter()
188        .flat_map(|(qualifier, field)| {
189            [
190                ColumnReference::new(qualifier, field.name()),
191                // we need to push down filter using unqualified column as well
192                ColumnReference::new_unqualified(field.name()),
193            ]
194        })
195        .collect::<HashSet<_>>()
196}
197
198/// Log the plan in debug/tracing mode after some part of the optimizer runs
199pub fn log_plan(description: &str, plan: &LogicalPlan) {
200    debug!("{description}:\n{}\n", plan.display_indent());
201    trace!("{description}::\n{}\n", plan.display_indent_schema());
202}
203
204/// Determine whether a predicate can restrict NULLs. e.g.
205/// `c0 > 8` return true;
206/// `c0 IS NULL` return false.
207pub fn is_restrict_null_predicate<'a>(
208    predicate: Expr,
209    join_cols_of_predicate: impl IntoIterator<Item = &'a Column>,
210) -> Result<bool> {
211    if matches!(predicate, Expr::Column(_)) {
212        return Ok(true);
213    }
214
215    // If result is single `true`, return false;
216    // If result is single `NULL` or `false`, return true;
217    Ok(
218        match evaluate_expr_with_null_column(predicate, join_cols_of_predicate)? {
219            ColumnarValue::Array(array) => {
220                if array.len() == 1 {
221                    let boolean_array = as_boolean_array(&array)?;
222                    boolean_array.is_null(0) || !boolean_array.value(0)
223                } else {
224                    false
225                }
226            }
227            ColumnarValue::Scalar(scalar) => matches!(
228                scalar,
229                ScalarValue::Boolean(None) | ScalarValue::Boolean(Some(false))
230            ),
231        },
232    )
233}
234
235/// Determines if an expression will always evaluate to null.
236/// `c0 + 8` return true
237/// `c0 IS NULL` return false
238/// `CASE WHEN c0 > 1 then 0 else 1` return false
239pub fn evaluates_to_null<'a>(
240    predicate: Expr,
241    null_columns: impl IntoIterator<Item = &'a Column>,
242) -> Result<bool> {
243    if matches!(predicate, Expr::Column(_)) {
244        return Ok(true);
245    }
246
247    Ok(
248        match evaluate_expr_with_null_column(predicate, null_columns)? {
249            ColumnarValue::Array(_) => false,
250            ColumnarValue::Scalar(scalar) => scalar.is_null(),
251        },
252    )
253}
254
255fn evaluate_expr_with_null_column<'a>(
256    predicate: Expr,
257    null_columns: impl IntoIterator<Item = &'a Column>,
258) -> Result<ColumnarValue> {
259    static DUMMY_COL_NAME: &str = "?";
260    let schema = Arc::new(Schema::new(vec![Field::new(
261        DUMMY_COL_NAME,
262        DataType::Null,
263        true,
264    )]));
265    let input_schema = DFSchema::try_from(Arc::clone(&schema))?;
266    let column = new_null_array(&DataType::Null, 1);
267    let input_batch = RecordBatch::try_new(schema, vec![column])?;
268    let execution_props = ExecutionProps::default();
269    let null_column = Column::from_name(DUMMY_COL_NAME);
270
271    let join_cols_to_replace = null_columns
272        .into_iter()
273        .map(|column| (column, &null_column))
274        .collect::<HashMap<_, _>>();
275
276    let replaced_predicate = replace_col(predicate, &join_cols_to_replace)?;
277    let coerced_predicate = coerce(replaced_predicate, &input_schema)?;
278    create_physical_expr(
279        &coerced_predicate,
280        &input_schema,
281        &execution_props,
282        &PhysicalPlanningContext::default(),
283    )?
284    .evaluate(&input_batch)
285}
286
287/// No session timezone is threaded in here on purpose. This runs over a plan the
288/// `TypeCoercion` analyzer has already coerced, so every binary operand pair
289/// already shares a type; the only type this helper introduces is the `Null` of
290/// the dummy column in `evaluate_expr_with_null_column`, and `Null` against a
291/// timestamp is short-circuited by `null_coercion` before the aware/naive rule.
292fn coerce(expr: Expr, schema: &DFSchema) -> Result<Expr> {
293    let mut expr_rewrite = TypeCoercionRewriter::new(schema);
294    expr.rewrite(&mut expr_rewrite).data()
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use crate::test::test_table_scan_with_name;
301    use datafusion_common::Spans;
302    use datafusion_expr::expr::SetQuantifier;
303    use datafusion_expr::logical_plan::builder::LogicalPlanBuilder;
304    use datafusion_expr::{
305        Operator, Subquery, binary_expr, case, col, in_list, is_null, lit,
306    };
307
308    #[test]
309    fn set_comparison_is_not_repeatable() {
310        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("t2").unwrap())
311            .project(vec![col("b")])
312            .unwrap()
313            .build()
314            .unwrap();
315        let expr = Expr::SetComparison(SetComparison::new(
316            Box::new(col("a")),
317            Subquery {
318                subquery: Arc::new(subquery),
319                outer_ref_columns: vec![],
320                spans: Spans::new(),
321            },
322            Operator::Gt,
323            SetQuantifier::Any,
324        ));
325
326        assert!(!is_repeatable(&expr));
327    }
328
329    #[test]
330    fn expr_is_restrict_null_predicate() -> Result<()> {
331        let test_cases = vec![
332            // a
333            (col("a"), true),
334            // a IS NULL
335            (is_null(col("a")), false),
336            // a IS NOT NULL
337            (Expr::IsNotNull(Box::new(col("a"))), true),
338            // a = NULL
339            (
340                binary_expr(
341                    col("a"),
342                    Operator::Eq,
343                    Expr::Literal(ScalarValue::Null, None),
344                ),
345                true,
346            ),
347            // a > 8
348            (binary_expr(col("a"), Operator::Gt, lit(8i64)), true),
349            // a <= 8
350            (binary_expr(col("a"), Operator::LtEq, lit(8i32)), true),
351            // CASE a WHEN 1 THEN true WHEN 0 THEN false ELSE NULL END
352            (
353                case(col("a"))
354                    .when(lit(1i64), lit(true))
355                    .when(lit(0i64), lit(false))
356                    .otherwise(lit(ScalarValue::Null))?,
357                true,
358            ),
359            // CASE a WHEN 1 THEN true ELSE false END
360            (
361                case(col("a"))
362                    .when(lit(1i64), lit(true))
363                    .otherwise(lit(false))?,
364                true,
365            ),
366            // CASE a WHEN 0 THEN false ELSE true END
367            (
368                case(col("a"))
369                    .when(lit(0i64), lit(false))
370                    .otherwise(lit(true))?,
371                false,
372            ),
373            // (CASE a WHEN 0 THEN false ELSE true END) OR false
374            (
375                binary_expr(
376                    case(col("a"))
377                        .when(lit(0i64), lit(false))
378                        .otherwise(lit(true))?,
379                    Operator::Or,
380                    lit(false),
381                ),
382                false,
383            ),
384            // (CASE a WHEN 0 THEN true ELSE false END) OR false
385            (
386                binary_expr(
387                    case(col("a"))
388                        .when(lit(0i64), lit(true))
389                        .otherwise(lit(false))?,
390                    Operator::Or,
391                    lit(false),
392                ),
393                true,
394            ),
395            // a IN (1, 2, 3)
396            (
397                in_list(col("a"), vec![lit(1i64), lit(2i64), lit(3i64)], false),
398                true,
399            ),
400            // a NOT IN (1, 2, 3)
401            (
402                in_list(col("a"), vec![lit(1i64), lit(2i64), lit(3i64)], true),
403                true,
404            ),
405            // a IN (NULL)
406            (
407                in_list(
408                    col("a"),
409                    vec![Expr::Literal(ScalarValue::Null, None)],
410                    false,
411                ),
412                true,
413            ),
414            // a NOT IN (NULL)
415            (
416                in_list(col("a"), vec![Expr::Literal(ScalarValue::Null, None)], true),
417                true,
418            ),
419        ];
420
421        let column_a = Column::from_name("a");
422        for (predicate, expected) in test_cases {
423            let join_cols_of_predicate = std::iter::once(&column_a);
424            let actual =
425                is_restrict_null_predicate(predicate.clone(), join_cols_of_predicate)?;
426            assert_eq!(actual, expected, "{predicate}");
427        }
428
429        Ok(())
430    }
431}