mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177422260


##########
datafusion/optimizer/src/analyzer/subquery.rs:
##########
@@ -0,0 +1,340 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::analyzer::check_plan;
+use crate::utils::{collect_subquery_cols, split_conjunction};
+use datafusion_common::tree_node::{TreeNode, VisitRecursion};
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::expr_rewriter::strip_outer_reference;
+use datafusion_expr::{
+    Aggregate, BinaryExpr, Cast, Expr, Filter, Join, JoinType, LogicalPlan, 
Operator,
+    Window,
+};
+use std::ops::Deref;
+
+/// Do necessary check on subquery expressions and fail the invalid plan
+/// 1) Check whether the outer plan is in the allowed outer plans list to use 
subquery expressions,
+///    the allowed while list: [Projection, Filter, Window, Aggregate, Join].
+/// 2) Check whether the inner plan is in the allowed inner plans list to use 
correlated(outer) expressions.
+/// 3) Check and validate unsupported cases to use the correlated(outer) 
expressions inside the subquery(inner) plans/inner expressions.
+/// For example, we do not want to support to use correlated expressions as 
the Join conditions in the subquery plan when the Join
+/// is a Full Out Join
+pub fn check_subquery_expr(
+    outer_plan: &LogicalPlan,
+    inner_plan: &LogicalPlan,
+    expr: &Expr,
+) -> Result<()> {
+    check_plan(inner_plan)?;
+    if let Expr::ScalarSubquery(subquery) = expr {
+        // Scalar subquery should only return one column
+        if subquery.subquery.schema().fields().len() > 1 {
+            return Err(datafusion_common::DataFusionError::Plan(
+                "Scalar subquery should only return one column".to_string(),
+            ));
+        }
+        // Correlated scalar subquery must be aggregated to return at most one 
row
+        if !subquery.outer_ref_columns.is_empty() {
+            match strip_inner_query(inner_plan) {
+                LogicalPlan::Aggregate(agg) => {
+                    check_aggregation_in_scalar_subquery(inner_plan, agg)
+                }
+                LogicalPlan::Filter(Filter { input, .. })
+                    if matches!(input.as_ref(), LogicalPlan::Aggregate(_)) =>
+                {
+                    if let LogicalPlan::Aggregate(agg) = input.as_ref() {
+                        check_aggregation_in_scalar_subquery(inner_plan, agg)
+                    } else {
+                        Ok(())
+                    }
+                }
+                _ => {
+                    if inner_plan
+                        .max_rows()
+                        .filter(|max_row| *max_row <= 1)
+                        .is_some()
+                    {
+                        Ok(())
+                    } else {
+                        Err(DataFusionError::Plan(
+                            "Correlated scalar subquery must be aggregated to 
return at most one row"
+                                .to_string(),
+                        ))
+                    }
+                }
+            }?;
+            match outer_plan {
+                LogicalPlan::Projection(_)
+                | LogicalPlan::Filter(_) => Ok(()),
+                LogicalPlan::Aggregate(Aggregate {group_expr, aggr_expr,..}) 
=> {
+                    if group_expr.contains(expr) && !aggr_expr.contains(expr) {
+                        // TODO revisit this validation logic
+                        Err(DataFusionError::Plan(
+                            "Correlated scalar subquery in the GROUP BY clause 
must also be in the aggregate expressions"
+                                .to_string(),
+                        ))
+                    } else {
+                        Ok(())
+                    }
+                },
+                _ => Err(DataFusionError::Plan(
+                    "Correlated scalar subquery can only be used in 
Projection, Filter, Aggregate plan nodes"
+                        .to_string(),
+                ))
+            }?;
+        }
+        check_correlations_in_subquery(inner_plan, true)
+    } else {
+        match outer_plan {
+            LogicalPlan::Projection(_)
+            | LogicalPlan::Filter(_)
+            | LogicalPlan::Window(_)
+            | LogicalPlan::Aggregate(_)
+            | LogicalPlan::Join(_) => Ok(()),
+            _ => Err(DataFusionError::Plan(
+                "In/Exist subquery can only be used in \
+            Projection, Filter, Window functions, Aggregate and Join plan 
nodes"
+                    .to_string(),
+            )),
+        }?;
+        check_correlations_in_subquery(inner_plan, false)
+    }
+}
+
+// Recursively check the unsupported outer references in the sub query plan.
+fn check_correlations_in_subquery(
+    inner_plan: &LogicalPlan,
+    is_scalar: bool,
+) -> Result<()> {
+    check_inner_plan(inner_plan, is_scalar, false, true)
+}
+
+// Recursively check the unsupported outer references in the sub query plan.
+fn check_inner_plan(
+    inner_plan: &LogicalPlan,
+    is_scalar: bool,
+    is_aggregate: bool,
+    can_contain_outer_ref: bool,
+) -> Result<()> {
+    if !can_contain_outer_ref && contains_outer_reference(inner_plan) {
+        return Err(DataFusionError::Plan(
+            "Accessing outer reference columns is not allowed in the 
plan".to_string(),
+        ));
+    }
+    // We want to support as many operators as possible inside the correlated 
subquery
+    match inner_plan {
+        LogicalPlan::Aggregate(_) => {
+            inner_plan.apply_children(&mut |plan| {
+                check_inner_plan(plan, is_scalar, true, 
can_contain_outer_ref)?;
+                Ok(VisitRecursion::Continue)
+            })?;
+            Ok(())
+        }
+        LogicalPlan::Filter(Filter {
+            predicate, input, ..
+        }) => {
+            let (correlated, _): (Vec<_>, Vec<_>) = 
split_conjunction(predicate)
+                .into_iter()
+                .partition(|e| e.contains_outer());
+            let maybe_unsupport = correlated
+                .into_iter()
+                .filter(|expr| !can_pullup_over_aggregation(expr))
+                .collect::<Vec<_>>();
+            if is_aggregate && is_scalar && !maybe_unsupport.is_empty() {
+                return Err(DataFusionError::Plan(format!(
+                    "Correlated column is not allowed in predicate: {:?}",
+                    predicate
+                )));
+            }
+            check_inner_plan(input, is_scalar, is_aggregate, 
can_contain_outer_ref)
+        }
+        LogicalPlan::Window(window) => {
+            check_mixed_out_refer_in_window(window)?;
+            inner_plan.apply_children(&mut |plan| {
+                check_inner_plan(plan, is_scalar, is_aggregate, 
can_contain_outer_ref)?;
+                Ok(VisitRecursion::Continue)
+            })?;
+            Ok(())
+        }
+        LogicalPlan::Projection(_)
+        | LogicalPlan::Distinct(_)
+        | LogicalPlan::Sort(_)
+        | LogicalPlan::CrossJoin(_)
+        | LogicalPlan::Union(_)
+        | LogicalPlan::TableScan(_)
+        | LogicalPlan::EmptyRelation(_)
+        | LogicalPlan::Limit(_)
+        | LogicalPlan::Values(_)
+        | LogicalPlan::Subquery(_)
+        | LogicalPlan::SubqueryAlias(_) => {
+            inner_plan.apply_children(&mut |plan| {
+                check_inner_plan(plan, is_scalar, is_aggregate, 
can_contain_outer_ref)?;
+                Ok(VisitRecursion::Continue)
+            })?;
+            Ok(())
+        }
+        LogicalPlan::Join(Join {
+            left,
+            right,
+            join_type,
+            ..
+        }) => match join_type {
+            JoinType::Inner => {
+                inner_plan.apply_children(&mut |plan| {
+                    check_inner_plan(
+                        plan,
+                        is_scalar,
+                        is_aggregate,
+                        can_contain_outer_ref,
+                    )?;
+                    Ok(VisitRecursion::Continue)
+                })?;
+                Ok(())
+            }
+            JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => {
+                check_inner_plan(left, is_scalar, is_aggregate, 
can_contain_outer_ref)?;
+                check_inner_plan(right, is_scalar, is_aggregate, false)
+            }
+            JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => {
+                check_inner_plan(left, is_scalar, is_aggregate, false)?;
+                check_inner_plan(right, is_scalar, is_aggregate, 
can_contain_outer_ref)
+            }
+            JoinType::Full => {
+                inner_plan.apply_children(&mut |plan| {
+                    check_inner_plan(plan, is_scalar, is_aggregate, false)?;
+                    Ok(VisitRecursion::Continue)
+                })?;
+                Ok(())
+            }
+        },
+        _ => Err(DataFusionError::Plan(
+            "Unsupported operator in the subquery plan.".to_string(),
+        )),
+    }
+}
+
+fn contains_outer_reference(inner_plan: &LogicalPlan) -> bool {
+    inner_plan
+        .expressions()
+        .iter()
+        .any(|expr| expr.contains_outer())
+}
+
+fn check_aggregation_in_scalar_subquery(
+    inner_plan: &LogicalPlan,
+    agg: &Aggregate,
+) -> Result<()> {
+    if agg.aggr_expr.is_empty() {

Review Comment:
   Yes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to