datafusion-optimizer 56.0.0

DataFusion Query Optimizer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Utility functions leveraged by the query optimizer rules

use std::collections::{BTreeSet, HashMap, HashSet};

use crate::analyzer::type_coercion::TypeCoercionRewriter;
use arrow::array::{Array, RecordBatch, new_null_array};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::TableReference;
use datafusion_common::cast::as_boolean_array;
use datafusion_common::tree_node::{TransformedResult, TreeNode, TreeNodeRecursion};
use datafusion_common::{Column, DFSchema, Result, ScalarValue};
use datafusion_expr::execution_props::ExecutionProps;
use datafusion_expr::expr::{Exists, InSubquery, SetComparison};
use datafusion_expr::expr_rewriter::replace_col;
use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
use datafusion_expr::{
    ColumnarValue, DistinctHandling, Expr, WriteOp, logical_plan::LogicalPlan,
};
use datafusion_physical_expr::create_physical_expr;
use log::{debug, trace};
use std::sync::Arc;

/// Re-export of `NamesPreserver` for backwards compatibility,
/// as it was initially placed here and then moved elsewhere.
pub use datafusion_expr::expr_rewriter::NamePreserver;

/// Whether an expression is free of volatile functions and subqueries.
/// Subqueries are conservative barriers because their plans may contain
/// volatile expressions that [`Expr::is_volatile`] does not visit.
pub(crate) fn is_repeatable(expr: &Expr) -> bool {
    !expr
        .exists(|expr| {
            Ok(expr.is_volatile_node()
                || matches!(
                    expr,
                    Expr::Exists(_)
                        | Expr::InSubquery(_)
                        | Expr::SetComparison(_)
                        | Expr::ScalarSubquery(_)
                ))
        })
        .expect("expression traversal is infallible")
}

/// Whether an aggregate can safely ignore repeated input rows. This holds when
/// the function declares [`DistinctHandling::Insensitive`], or when it is
/// called with `DISTINCT` and declares [`DistinctHandling::Sensitive`], so that
/// its accumulator removes the repeated rows itself. Arguments, FILTER, and
/// ORDER BY must also be repeatable: MIN(random()) still observes repetitions.
pub(crate) fn is_duplicate_insensitive_aggregate(mut expr: &Expr) -> bool {
    while let Expr::Alias(alias) = expr {
        expr = &alias.expr;
    }
    let Expr::AggregateFunction(aggregate) = expr else {
        return false;
    };
    let ignores_duplicates = match aggregate.func.distinct_handling() {
        DistinctHandling::Insensitive => true,
        DistinctHandling::Sensitive => aggregate.params.distinct,
        // The accumulator does not implement `DISTINCT` and may silently
        // compute the non-distinct answer, so the flag proves nothing.
        // Variants added in the future are treated the same way.
        _ => false,
    };
    ignores_duplicates && is_repeatable(expr)
}

/// Return the expression schema for a MERGE DML node.
pub(crate) fn merge_into_schema(plan: &LogicalPlan) -> Result<Option<DFSchema>> {
    let LogicalPlan::Dml(dml) = plan else {
        return Ok(None);
    };
    let WriteOp::MergeInto(_) = &dml.op else {
        return Ok(None);
    };
    dml.merge_schema().map(Some)
}

/// Invokes `f` with the index, within `schema`, of every column referenced by
/// `expr` — including columns reached through a correlated subquery's outer
/// references. Columns absent from `schema` are skipped.
///
/// A subquery's own plan is intentionally not traversed: its internal columns
/// index into its own schema, not `schema`; only the outer (correlated) columns
/// it references from `schema` are relevant. The comparison expression of an
/// `IN`/set-comparison subquery is reached by the normal expression walk.
///
/// This is the shared primitive behind the top-down "which of a node's output
/// columns does an ancestor still need" analyses, namely
/// [`OptimizeProjections`](crate::optimize_projections::OptimizeProjections)
/// and [`EliminateJoin`](crate::eliminate_join::EliminateJoin). The two keep
/// their own required-index containers (an ordered set vs. a hash set), so this
/// reports indices through a callback rather than populating a shared type.
pub(crate) fn for_each_referenced_index(
    expr: &Expr,
    schema: &DFSchema,
    mut f: impl FnMut(usize),
) -> Result<()> {
    visit_referenced_indices(expr, schema, &mut f)
}

fn visit_referenced_indices(
    expr: &Expr,
    schema: &DFSchema,
    f: &mut dyn FnMut(usize),
) -> Result<()> {
    expr.apply(|expr| {
        match expr {
            Expr::Column(column) | Expr::OuterReferenceColumn(_, column) => {
                if let Some(idx) = schema.maybe_index_of_column(column) {
                    f(idx);
                }
            }
            Expr::Exists(Exists { subquery, .. })
            | Expr::InSubquery(InSubquery { subquery, .. })
            | Expr::SetComparison(SetComparison { subquery, .. })
            | Expr::ScalarSubquery(subquery) => {
                for outer in &subquery.outer_ref_columns {
                    visit_referenced_indices(outer, schema, f)?;
                }
            }
            _ => {}
        }
        Ok(TreeNodeRecursion::Continue)
    })?;
    Ok(())
}

/// Returns true if `expr` contains all columns in `schema_cols`
pub(crate) fn has_all_column_refs(
    expr: &Expr,
    schema_cols: &HashSet<ColumnReference>,
) -> bool {
    let column_refs = expr.column_refs();
    // note can't use HashSet::intersect because of different types (owned vs References)
    column_refs
        .iter()
        .filter(|c| {
            schema_cols.contains(&ColumnReference::new(c.relation.as_ref(), c.name()))
        })
        .count()
        == column_refs.len()
}

pub(crate) fn replace_qualified_name(
    expr: Expr,
    cols: &BTreeSet<Column>,
    subquery_alias: &str,
) -> Result<Expr> {
    let alias_cols: Vec<Column> = cols
        .iter()
        .map(|col| Column::new(Some(subquery_alias), &col.name))
        .collect();
    let replace_map: HashMap<&Column, &Column> =
        cols.iter().zip(alias_cols.iter()).collect();

    replace_col(expr, &replace_map)
}

/// Column reference to avoid copying string around
#[derive(PartialEq, Eq, Hash, Debug)]
pub(crate) struct ColumnReference<'a> {
    pub relation: Option<&'a TableReference>,
    pub name: &'a str,
}

impl<'a> ColumnReference<'a> {
    pub fn new(relation: Option<&'a TableReference>, name: &'a str) -> Self {
        Self { relation, name }
    }

    pub fn new_unqualified(name: &'a str) -> Self {
        Self {
            relation: None,
            name,
        }
    }
}

/// Returns references to all columns in the schema
pub(crate) fn schema_columns(schema: &DFSchema) -> HashSet<ColumnReference<'_>> {
    schema
        .iter()
        .flat_map(|(qualifier, field)| {
            [
                ColumnReference::new(qualifier, field.name()),
                // we need to push down filter using unqualified column as well
                ColumnReference::new_unqualified(field.name()),
            ]
        })
        .collect::<HashSet<_>>()
}

/// Log the plan in debug/tracing mode after some part of the optimizer runs
pub fn log_plan(description: &str, plan: &LogicalPlan) {
    debug!("{description}:\n{}\n", plan.display_indent());
    trace!("{description}::\n{}\n", plan.display_indent_schema());
}

/// Determine whether a predicate can restrict NULLs. e.g.
/// `c0 > 8` return true;
/// `c0 IS NULL` return false.
pub fn is_restrict_null_predicate<'a>(
    predicate: Expr,
    join_cols_of_predicate: impl IntoIterator<Item = &'a Column>,
) -> Result<bool> {
    if matches!(predicate, Expr::Column(_)) {
        return Ok(true);
    }

    // If result is single `true`, return false;
    // If result is single `NULL` or `false`, return true;
    Ok(
        match evaluate_expr_with_null_column(predicate, join_cols_of_predicate)? {
            ColumnarValue::Array(array) => {
                if array.len() == 1 {
                    let boolean_array = as_boolean_array(&array)?;
                    boolean_array.is_null(0) || !boolean_array.value(0)
                } else {
                    false
                }
            }
            ColumnarValue::Scalar(scalar) => matches!(
                scalar,
                ScalarValue::Boolean(None) | ScalarValue::Boolean(Some(false))
            ),
        },
    )
}

/// Determines if an expression will always evaluate to null.
/// `c0 + 8` return true
/// `c0 IS NULL` return false
/// `CASE WHEN c0 > 1 then 0 else 1` return false
pub fn evaluates_to_null<'a>(
    predicate: Expr,
    null_columns: impl IntoIterator<Item = &'a Column>,
) -> Result<bool> {
    if matches!(predicate, Expr::Column(_)) {
        return Ok(true);
    }

    Ok(
        match evaluate_expr_with_null_column(predicate, null_columns)? {
            ColumnarValue::Array(_) => false,
            ColumnarValue::Scalar(scalar) => scalar.is_null(),
        },
    )
}

fn evaluate_expr_with_null_column<'a>(
    predicate: Expr,
    null_columns: impl IntoIterator<Item = &'a Column>,
) -> Result<ColumnarValue> {
    static DUMMY_COL_NAME: &str = "?";
    let schema = Arc::new(Schema::new(vec![Field::new(
        DUMMY_COL_NAME,
        DataType::Null,
        true,
    )]));
    let input_schema = DFSchema::try_from(Arc::clone(&schema))?;
    let column = new_null_array(&DataType::Null, 1);
    let input_batch = RecordBatch::try_new(schema, vec![column])?;
    let execution_props = ExecutionProps::default();
    let null_column = Column::from_name(DUMMY_COL_NAME);

    let join_cols_to_replace = null_columns
        .into_iter()
        .map(|column| (column, &null_column))
        .collect::<HashMap<_, _>>();

    let replaced_predicate = replace_col(predicate, &join_cols_to_replace)?;
    let coerced_predicate = coerce(replaced_predicate, &input_schema)?;
    create_physical_expr(
        &coerced_predicate,
        &input_schema,
        &execution_props,
        &PhysicalPlanningContext::default(),
    )?
    .evaluate(&input_batch)
}

/// No session timezone is threaded in here on purpose. This runs over a plan the
/// `TypeCoercion` analyzer has already coerced, so every binary operand pair
/// already shares a type; the only type this helper introduces is the `Null` of
/// the dummy column in `evaluate_expr_with_null_column`, and `Null` against a
/// timestamp is short-circuited by `null_coercion` before the aware/naive rule.
fn coerce(expr: Expr, schema: &DFSchema) -> Result<Expr> {
    let mut expr_rewrite = TypeCoercionRewriter::new(schema);
    expr.rewrite(&mut expr_rewrite).data()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test::test_table_scan_with_name;
    use datafusion_common::Spans;
    use datafusion_expr::expr::SetQuantifier;
    use datafusion_expr::logical_plan::builder::LogicalPlanBuilder;
    use datafusion_expr::{
        Operator, Subquery, binary_expr, case, col, in_list, is_null, lit,
    };

    #[test]
    fn set_comparison_is_not_repeatable() {
        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("t2").unwrap())
            .project(vec![col("b")])
            .unwrap()
            .build()
            .unwrap();
        let expr = Expr::SetComparison(SetComparison::new(
            Box::new(col("a")),
            Subquery {
                subquery: Arc::new(subquery),
                outer_ref_columns: vec![],
                spans: Spans::new(),
            },
            Operator::Gt,
            SetQuantifier::Any,
        ));

        assert!(!is_repeatable(&expr));
    }

    #[test]
    fn expr_is_restrict_null_predicate() -> Result<()> {
        let test_cases = vec![
            // a
            (col("a"), true),
            // a IS NULL
            (is_null(col("a")), false),
            // a IS NOT NULL
            (Expr::IsNotNull(Box::new(col("a"))), true),
            // a = NULL
            (
                binary_expr(
                    col("a"),
                    Operator::Eq,
                    Expr::Literal(ScalarValue::Null, None),
                ),
                true,
            ),
            // a > 8
            (binary_expr(col("a"), Operator::Gt, lit(8i64)), true),
            // a <= 8
            (binary_expr(col("a"), Operator::LtEq, lit(8i32)), true),
            // CASE a WHEN 1 THEN true WHEN 0 THEN false ELSE NULL END
            (
                case(col("a"))
                    .when(lit(1i64), lit(true))
                    .when(lit(0i64), lit(false))
                    .otherwise(lit(ScalarValue::Null))?,
                true,
            ),
            // CASE a WHEN 1 THEN true ELSE false END
            (
                case(col("a"))
                    .when(lit(1i64), lit(true))
                    .otherwise(lit(false))?,
                true,
            ),
            // CASE a WHEN 0 THEN false ELSE true END
            (
                case(col("a"))
                    .when(lit(0i64), lit(false))
                    .otherwise(lit(true))?,
                false,
            ),
            // (CASE a WHEN 0 THEN false ELSE true END) OR false
            (
                binary_expr(
                    case(col("a"))
                        .when(lit(0i64), lit(false))
                        .otherwise(lit(true))?,
                    Operator::Or,
                    lit(false),
                ),
                false,
            ),
            // (CASE a WHEN 0 THEN true ELSE false END) OR false
            (
                binary_expr(
                    case(col("a"))
                        .when(lit(0i64), lit(true))
                        .otherwise(lit(false))?,
                    Operator::Or,
                    lit(false),
                ),
                true,
            ),
            // a IN (1, 2, 3)
            (
                in_list(col("a"), vec![lit(1i64), lit(2i64), lit(3i64)], false),
                true,
            ),
            // a NOT IN (1, 2, 3)
            (
                in_list(col("a"), vec![lit(1i64), lit(2i64), lit(3i64)], true),
                true,
            ),
            // a IN (NULL)
            (
                in_list(
                    col("a"),
                    vec![Expr::Literal(ScalarValue::Null, None)],
                    false,
                ),
                true,
            ),
            // a NOT IN (NULL)
            (
                in_list(col("a"), vec![Expr::Literal(ScalarValue::Null, None)], true),
                true,
            ),
        ];

        let column_a = Column::from_name("a");
        for (predicate, expected) in test_cases {
            let join_cols_of_predicate = std::iter::once(&column_a);
            let actual =
                is_restrict_null_predicate(predicate.clone(), join_cols_of_predicate)?;
            assert_eq!(actual, expected, "{predicate}");
        }

        Ok(())
    }
}