Skip to main content

datafusion_expr/logical_plan/
invariants.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 crate::logical_plan::MaterializedCtePlan;
6use datafusion_common::{
7    DFSchemaRef, Result, assert_or_internal_err, plan_err,
8    tree_node::{TreeNode, TreeNodeRecursion},
9};
10
11use crate::{
12    Aggregate, DmlStatement, Expr, Filter, Join, JoinType, LogicalPlan, Window, WriteOp,
13    expr::{Exists, InSubquery, SetComparison, in_subquery_tuple_values},
14    expr_rewriter::strip_outer_reference,
15    utils::{collect_subquery_cols, split_conjunction},
16};
17
18use super::Extension;
19
20#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Hash)]
21pub enum InvariantLevel {
22    /// Invariants that are always true in DataFusion `LogicalPlan`s
23    /// such as the number of expected children and no duplicated output fields
24    Always,
25    /// Invariants that must hold true for the plan to be "executable"
26    /// such as the type and number of function arguments are correct and
27    /// that wildcards have been expanded
28    ///
29    /// To ensure a LogicalPlan satisfies the `Executable` invariants, run the
30    /// `Analyzer`
31    Executable,
32}
33
34/// Apply the [`InvariantLevel::Always`] check at the current plan node only.
35///
36/// This does not recurs to any child nodes.
37pub fn assert_always_invariants_at_current_node(plan: &LogicalPlan) -> Result<()> {
38    // Refer to <https://datafusion.apache.org/contributor-guide/specification/invariants.html#relation-name-tuples-in-logical-fields-and-logical-columns-are-unique>
39    assert_unique_field_names(plan)?;
40
41    Ok(())
42}
43
44/// Visit the plan nodes, and confirm the [`InvariantLevel::Executable`]
45/// as well as the less stringent [`InvariantLevel::Always`] checks.
46pub fn assert_executable_invariants(plan: &LogicalPlan) -> Result<()> {
47    // Always invariants
48    assert_always_invariants_at_current_node(plan)?;
49    assert_valid_extension_nodes(plan, InvariantLevel::Always)?;
50
51    // Executable invariants
52    assert_valid_extension_nodes(plan, InvariantLevel::Executable)?;
53    assert_valid_semantic_plan(plan)?;
54    Ok(())
55}
56
57/// Asserts that the query plan, and subplan, extension nodes have valid invariants.
58///
59/// Refer to [`UserDefinedLogicalNode::check_invariants`](super::UserDefinedLogicalNode)
60/// for more details of user-provided extension node invariants.
61fn assert_valid_extension_nodes(plan: &LogicalPlan, check: InvariantLevel) -> Result<()> {
62    plan.apply_with_subqueries(|plan: &LogicalPlan| {
63        if let LogicalPlan::Extension(Extension { node }) = plan {
64            node.check_invariants(check)?;
65        }
66        plan.apply_expressions(|expr| {
67            // recursively look for subqueries
68            expr.apply(|expr| {
69                match expr {
70                    Expr::Exists(Exists { subquery, .. })
71                    | Expr::InSubquery(InSubquery { subquery, .. })
72                    | Expr::SetComparison(SetComparison { subquery, .. })
73                    | Expr::ScalarSubquery(subquery) => {
74                        assert_valid_extension_nodes(&subquery.subquery, check)?;
75                    }
76                    _ => {}
77                }
78                Ok(TreeNodeRecursion::Continue)
79            })
80        })
81    })
82    .map(|_| ())
83}
84
85/// Returns an error if plan, and subplans, do not have unique fields.
86///
87/// This invariant is subject to change.
88/// refer: <https://github.com/apache/datafusion/issues/13525#issuecomment-2494046463>
89fn assert_unique_field_names(plan: &LogicalPlan) -> Result<()> {
90    plan.schema().check_names()
91}
92
93/// Returns an error if the plan is not semantically valid.
94fn assert_valid_semantic_plan(plan: &LogicalPlan) -> Result<()> {
95    assert_subqueries_are_valid(plan)?;
96
97    Ok(())
98}
99
100/// Returns an error if the plan does not have the expected schema.
101/// Ignores metadata and nullability.
102pub fn assert_expected_schema(schema: &DFSchemaRef, plan: &LogicalPlan) -> Result<()> {
103    let compatible = plan.schema().logically_equivalent_names_and_types(schema);
104
105    assert_or_internal_err!(
106        compatible,
107        "Failed due to a difference in schemas: original schema: {:?}, new schema: {:?}",
108        schema,
109        plan.schema()
110    );
111    Ok(())
112}
113
114/// Asserts that the subqueries are structured properly with valid node placement.
115///
116/// Refer to [`check_subquery_expr`] for more details of the internal invariants.
117fn assert_subqueries_are_valid(plan: &LogicalPlan) -> Result<()> {
118    plan.apply_with_subqueries(|plan: &LogicalPlan| {
119        plan.apply_expressions(|expr| {
120            // recursively look for subqueries
121            expr.apply(|expr| {
122                match expr {
123                    Expr::Exists(Exists { subquery, .. })
124                    | Expr::InSubquery(InSubquery { subquery, .. })
125                    | Expr::SetComparison(SetComparison { subquery, .. })
126                    | Expr::ScalarSubquery(subquery) => {
127                        check_subquery_expr(plan, &subquery.subquery, expr)?;
128                    }
129                    _ => {}
130                }
131                Ok(TreeNodeRecursion::Continue)
132            })
133        })
134    })
135    .map(|_| ())
136}
137
138/// Do necessary check on subquery expressions and fail the invalid plan
139/// 1) Check whether the outer plan is in the allowed outer plans list to use subquery expressions,
140///    the allowed while list: [Projection, Filter, Window, Aggregate, Join].
141/// 2) Check whether the inner plan is in the allowed inner plans list to use correlated(outer) expressions.
142/// 3) Check and validate unsupported cases to use the correlated(outer) expressions inside the subquery(inner) plans/inner expressions.
143///    For example, we do not want to support to use correlated expressions as the Join conditions in the subquery plan when the Join
144///    is a Full Out Join
145pub fn check_subquery_expr(
146    outer_plan: &LogicalPlan,
147    inner_plan: &LogicalPlan,
148    expr: &Expr,
149) -> Result<()> {
150    assert_subqueries_are_valid(inner_plan)?;
151    if let Expr::ScalarSubquery(subquery) = expr {
152        // Scalar subquery should only return one column
153        if subquery.subquery.schema().fields().len() > 1 {
154            return plan_err!(
155                "Scalar subquery should only return one column, but found {}: {}",
156                subquery.subquery.schema().fields().len(),
157                subquery.subquery.schema().field_names().join(", ")
158            );
159        }
160        // Correlated scalar subquery must be aggregated to return at most one row
161        if !subquery.outer_ref_columns.is_empty() {
162            match strip_inner_query(inner_plan) {
163                LogicalPlan::Aggregate(agg) => {
164                    check_aggregation_in_scalar_subquery(inner_plan, agg)
165                }
166                LogicalPlan::Filter(Filter { input, .. })
167                    if matches!(input.as_ref(), LogicalPlan::Aggregate(_)) =>
168                {
169                    if let LogicalPlan::Aggregate(agg) = input.as_ref() {
170                        check_aggregation_in_scalar_subquery(inner_plan, agg)
171                    } else {
172                        Ok(())
173                    }
174                }
175                _ => {
176                    if inner_plan.max_rows().is_some_and(|max_row| max_row <= 1) {
177                        Ok(())
178                    } else {
179                        plan_err!(
180                            "Correlated scalar subquery must be aggregated to return at most one row"
181                        )
182                    }
183                }
184            }?;
185            match outer_plan {
186                LogicalPlan::Projection(_)
187                | LogicalPlan::Filter(_)
188                | LogicalPlan::Dml(DmlStatement {
189                    op: WriteOp::MergeInto(_),
190                    ..
191                }) => Ok(()),
192                LogicalPlan::Aggregate(Aggregate {
193                    group_expr,
194                    aggr_expr,
195                    ..
196                }) => {
197                    if group_expr.contains(expr) && !aggr_expr.contains(expr) {
198                        // TODO revisit this validation logic
199                        plan_err!(
200                            "Correlated scalar subquery in the GROUP BY clause must \
201                            also be in the aggregate expressions"
202                        )
203                    } else {
204                        Ok(())
205                    }
206                }
207                _ => plan_err!(
208                    "Correlated scalar subquery can only be used in Projection, \
209                    Filter, Aggregate and MERGE DML plan nodes"
210                ),
211            }?;
212        }
213    } else {
214        if let Expr::InSubquery(subquery) = expr {
215            // InSubquery should only return one column, unless it is a
216            // multi-column `(a, b) IN (SELECT x, y ...)` with one tuple element
217            // per subquery column.
218            let num_subquery_cols = subquery.subquery.subquery.schema().fields().len();
219            match in_subquery_tuple_values(&subquery.expr, &subquery.subquery.subquery)? {
220                Some(_) => {}
221                None if num_subquery_cols > 1 => {
222                    return plan_err!(
223                        "InSubquery should only return one column, but found {}: {}",
224                        num_subquery_cols,
225                        subquery.subquery.subquery.schema().field_names().join(", ")
226                    );
227                }
228                None => {}
229            }
230        }
231        if let Expr::SetComparison(set_comparison) = expr
232            && set_comparison.subquery.subquery.schema().fields().len() > 1
233        {
234            return plan_err!(
235                "Set comparison subquery should only return one column, but found {}: {}",
236                set_comparison.subquery.subquery.schema().fields().len(),
237                set_comparison
238                    .subquery
239                    .subquery
240                    .schema()
241                    .field_names()
242                    .join(", ")
243            );
244        }
245        match outer_plan {
246            LogicalPlan::Projection(_)
247            | LogicalPlan::Filter(_)
248            | LogicalPlan::TableScan(_)
249            | LogicalPlan::Window(_)
250            | LogicalPlan::Aggregate(_)
251            | LogicalPlan::Join(_)
252            | LogicalPlan::Dml(DmlStatement {
253                op: WriteOp::MergeInto(_),
254                ..
255            }) => Ok(()),
256            _ => plan_err!(
257                "In/Exist/SetComparison subquery can only be used in \
258                Projection, Filter, TableScan, Window functions, Aggregate and Join plan nodes, \
259                but was used in [{}]",
260                outer_plan.display()
261            ),
262        }?;
263    }
264    check_correlations_in_subquery(inner_plan)
265}
266
267// Recursively check the unsupported outer references in the sub query plan.
268fn check_correlations_in_subquery(inner_plan: &LogicalPlan) -> Result<()> {
269    check_inner_plan(inner_plan)
270}
271
272// Recursively check the unsupported outer references in the sub query plan.
273#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
274fn check_inner_plan(inner_plan: &LogicalPlan) -> Result<()> {
275    // We want to support as many operators as possible inside the correlated subquery
276    match inner_plan {
277        LogicalPlan::Aggregate(_) => {
278            inner_plan.apply_children(|plan| {
279                check_inner_plan(plan)?;
280                Ok(TreeNodeRecursion::Continue)
281            })?;
282            Ok(())
283        }
284        LogicalPlan::Filter(Filter { input, .. }) => check_inner_plan(input),
285        LogicalPlan::Window(window) => {
286            check_mixed_out_refer_in_window(window)?;
287            inner_plan.apply_children(|plan| {
288                check_inner_plan(plan)?;
289                Ok(TreeNodeRecursion::Continue)
290            })?;
291            Ok(())
292        }
293        LogicalPlan::Projection(_)
294        | LogicalPlan::Distinct(_)
295        | LogicalPlan::Sort(_)
296        | LogicalPlan::Union(_)
297        | LogicalPlan::TableScan(_)
298        | LogicalPlan::EmptyRelation(_)
299        | LogicalPlan::Limit(_)
300        | LogicalPlan::Values(_)
301        | LogicalPlan::Subquery(_)
302        | LogicalPlan::SubqueryAlias(_)
303        | LogicalPlan::Unnest(_) => {
304            inner_plan.apply_children(|plan| {
305                check_inner_plan(plan)?;
306                Ok(TreeNodeRecursion::Continue)
307            })?;
308            Ok(())
309        }
310        LogicalPlan::Join(Join {
311            left,
312            right,
313            join_type,
314            ..
315        }) => match join_type {
316            JoinType::Inner => {
317                inner_plan.apply_children(|plan| {
318                    check_inner_plan(plan)?;
319                    Ok(TreeNodeRecursion::Continue)
320                })?;
321                Ok(())
322            }
323            JoinType::Left
324            | JoinType::LeftSemi
325            | JoinType::LeftAnti
326            | JoinType::LeftMark => {
327                check_inner_plan(left)?;
328                check_no_outer_references(right)
329            }
330            JoinType::Right
331            | JoinType::RightSemi
332            | JoinType::RightAnti
333            | JoinType::RightMark => {
334                check_no_outer_references(left)?;
335                check_inner_plan(right)
336            }
337            JoinType::Full => {
338                inner_plan.apply_children(|plan| {
339                    check_no_outer_references(plan)?;
340                    Ok(TreeNodeRecursion::Continue)
341                })?;
342                Ok(())
343            }
344        },
345        LogicalPlan::Extension(_) => Ok(()),
346        // A materialized CTE is not checked, as when it was an extension
347        // node. `PullUpCorrelatedExpr` rewrites its continuation, or stops.
348        LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_)) => Ok(()),
349        plan => check_no_outer_references(plan),
350    }
351}
352
353fn check_no_outer_references(inner_plan: &LogicalPlan) -> Result<()> {
354    if inner_plan.contains_outer_reference() {
355        plan_err!(
356            "Accessing outer reference columns is not allowed in the plan: {}",
357            inner_plan.display()
358        )
359    } else {
360        Ok(())
361    }
362}
363
364fn check_aggregation_in_scalar_subquery(
365    inner_plan: &LogicalPlan,
366    agg: &Aggregate,
367) -> Result<()> {
368    if agg.aggr_expr.is_empty() {
369        return plan_err!(
370            "Correlated scalar subquery must be aggregated to return at most one row"
371        );
372    }
373    if !agg.group_expr.is_empty() {
374        let correlated_exprs = get_correlated_expressions(inner_plan)?;
375        let inner_subquery_cols =
376            collect_subquery_cols(&correlated_exprs, agg.input.schema())?;
377        let mut group_columns =
378            agg.group_expr.iter().flat_map(|group| group.column_refs());
379
380        if !group_columns.all(|group| inner_subquery_cols.contains(group)) {
381            // Group BY columns must be a subset of columns in the correlated expressions
382            return plan_err!(
383                "A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"
384            );
385        }
386    }
387    Ok(())
388}
389
390fn strip_inner_query(inner_plan: &LogicalPlan) -> &LogicalPlan {
391    match inner_plan {
392        LogicalPlan::Projection(projection) => {
393            strip_inner_query(projection.input.as_ref())
394        }
395        LogicalPlan::SubqueryAlias(alias) => strip_inner_query(alias.input.as_ref()),
396        other => other,
397    }
398}
399
400fn get_correlated_expressions(inner_plan: &LogicalPlan) -> Result<Vec<Expr>> {
401    let mut exprs = vec![];
402    inner_plan.apply_with_subqueries(|plan| {
403        if let LogicalPlan::Filter(Filter { predicate, .. }) = plan {
404            let (correlated, _): (Vec<_>, Vec<_>) = split_conjunction(predicate)
405                .into_iter()
406                .partition(|e| e.contains_outer());
407
408            for expr in correlated {
409                exprs.push(strip_outer_reference(expr.clone()));
410            }
411        }
412        Ok(TreeNodeRecursion::Continue)
413    })?;
414    Ok(exprs)
415}
416
417/// Check whether the window expressions contain a mixture of out reference columns and inner columns
418fn check_mixed_out_refer_in_window(window: &Window) -> Result<()> {
419    let mixed = window
420        .window_expr
421        .iter()
422        .any(|win_expr| win_expr.contains_outer() && win_expr.any_column_refs());
423    if mixed {
424        plan_err!(
425            "Window expressions should not contain a mixed of outer references and inner columns"
426        )
427    } else {
428        Ok(())
429    }
430}
431
432#[cfg(test)]
433mod test {
434    use std::cmp::Ordering;
435    use std::sync::Arc;
436
437    use crate::{Extension, UserDefinedLogicalNodeCore};
438    use datafusion_common::{DFSchema, DFSchemaRef};
439
440    use super::*;
441
442    #[derive(Debug, PartialEq, Eq, Hash)]
443    struct MockUserDefinedLogicalPlan {
444        empty_schema: DFSchemaRef,
445    }
446
447    impl PartialOrd for MockUserDefinedLogicalPlan {
448        fn partial_cmp(&self, _other: &Self) -> Option<Ordering> {
449            None
450        }
451    }
452
453    impl UserDefinedLogicalNodeCore for MockUserDefinedLogicalPlan {
454        fn name(&self) -> &str {
455            "MockUserDefinedLogicalPlan"
456        }
457
458        fn inputs(&self) -> Vec<&LogicalPlan> {
459            vec![]
460        }
461
462        fn schema(&self) -> &DFSchemaRef {
463            &self.empty_schema
464        }
465
466        fn expressions(&self) -> Vec<Expr> {
467            vec![]
468        }
469
470        fn fmt_for_explain(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
471            write!(f, "MockUserDefinedLogicalPlan")
472        }
473
474        fn with_exprs_and_inputs(
475            &self,
476            _exprs: Vec<Expr>,
477            _inputs: Vec<LogicalPlan>,
478        ) -> Result<Self> {
479            Ok(Self {
480                empty_schema: Arc::clone(&self.empty_schema),
481            })
482        }
483
484        fn supports_limit_pushdown(&self) -> bool {
485            false // Disallow limit push-down by default
486        }
487    }
488
489    #[test]
490    fn wont_fail_extension_plan() {
491        let plan = LogicalPlan::Extension(Extension {
492            node: Arc::new(MockUserDefinedLogicalPlan {
493                empty_schema: DFSchemaRef::new(DFSchema::empty()),
494            }),
495        });
496
497        check_inner_plan(&plan).unwrap();
498    }
499}