You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "mingmwang (via GitHub)" <gi...@apache.org> on 2023/04/21 09:59:00 UTC

[GitHub] [arrow-datafusion] mingmwang opened a new pull request, #6084: Move Scalar Subquery validation logic to the Analyzer

mingmwang opened a new pull request, #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   # Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   # Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   # Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang merged pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang merged PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177516037


##########
datafusion/core/tests/sql/subqueries.rs:
##########
@@ -203,7 +203,202 @@ async fn subquery_not_allowed() -> Result<()> {
     let err = dataframe.into_optimized_plan().err().unwrap();
 
     assert_eq!(
-        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can not be used in Sort plan nodes"))"#,
+        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can only be used in Projection, Filter, Window functions, Aggregate and Join plan nodes"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1_int group by t2_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery_with_limit() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 2) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery_with_single_row() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:UInt32;N]",
+        "  Subquery: [t2_int:UInt32;N]",
+        "    Limit: skip=0, fetch=1 [t2_int:UInt32;N]",
+        "      Projection: t2.t2_int [t2_int:UInt32;N]",
+        "        Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "          TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    let sql = "SELECT t1_id from t1 where t1_int = (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1)";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id [t1_id:UInt32;N]",
+        "  Filter: t1.t1_int = (<subquery>) [t1_id:UInt32;N, t1_int:UInt32;N]",
+        "    Subquery: [t2_int:UInt32;N]",
+        "      Limit: skip=0, fetch=1 [t2_int:UInt32;N]",
+        "        Projection: t2.t2_int [t2_int:UInt32;N]",
+        "          Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "            TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "    TableScan: t1 projection=[t1_id, t1_int] [t1_id:UInt32;N, t1_int:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    let sql = "SELECT t1_id, (SELECT a FROM (select 1 as a) WHERE a = t1.t1_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:Int64]",
+        "  Subquery: [a:Int64]",
+        "    Projection: a [a:Int64]",
+        "      Filter: a = CAST(outer_ref(t1.t1_int) AS Int64) [a:Int64]",
+        "        Projection: Int64(1) AS a [a:Int64]",
+        "          EmptyRelation []",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_equal_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id < t1.t1_id) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated column is not allowed in predicate: t2.t2_id < outer_ref(t1.t1_id)"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn aggregated_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_sum [t1_id:UInt32;N, t2_sum:UInt64;N]",
+        "  Subquery: [SUM(t2.t2_int):UInt64;N]",
+        "    Projection: SUM(t2.t2_int) [SUM(t2.t2_int):UInt64;N]",
+        "      Aggregate: groupBy=[[]], aggr=[[SUM(t2.t2_int)]] [SUM(t2.t2_int):UInt64;N]",
+        "        Filter: t2.t2_id = outer_ref(t1.t1_id) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "          TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn aggregated_correlated_scalar_subquery_with_extra_group_by_columns() -> Result<()>
+{
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id group by t2_name) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+

Review Comment:
   Done



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177296225


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,
+                            };
+                            Some((left_max * right_max).max(min_rows))
+                        }
+                        _ => None,
+                    }
+                }
+                JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),
+                JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),
+            },
+            LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
+                match (left.max_rows(), right.max_rows()) {
+                    (Some(left_max), Some(right_max)) => Some(left_max * right_max),
+                    _ => None,
+                }
+            }
+            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
+            LogicalPlan::Union(Union { inputs, .. }) => inputs
+                .iter()
+                .map(|plan| plan.max_rows())
+                .try_fold(0usize, |mut acc, input_max| {
+                    if let Some(i_max) = input_max {
+                        acc += i_max;
+                        Some(acc)
+                    } else {
+                        None
+                    }
+                }),
+            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,
+            LogicalPlan::EmptyRelation(_) => Some(0),
+            LogicalPlan::Subquery(_) => None,
+            LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.max_rows(),
+            LogicalPlan::Limit(Limit { fetch, .. }) => *fetch,
+            LogicalPlan::Distinct(Distinct { input }) => input.max_rows(),
+            LogicalPlan::Unnest(_) => None,
+            LogicalPlan::CreateMemoryTable(_)
+            | LogicalPlan::CreateExternalTable(_)
+            | LogicalPlan::CreateView(_)
+            | LogicalPlan::CreateCatalogSchema(_)
+            | LogicalPlan::CreateCatalog(_)
+            | LogicalPlan::DropTable(_)
+            | LogicalPlan::DropView(_)
+            | LogicalPlan::Explain(_)
+            | LogicalPlan::Analyze(_)
+            | LogicalPlan::Dml(_)
+            | LogicalPlan::DescribeTable(_)
+            | LogicalPlan::Prepare(_)
+            | LogicalPlan::Statement(_)
+            | LogicalPlan::Values(_)

Review Comment:
   Will add.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177464518


##########
datafusion/core/tests/sql/subqueries.rs:
##########
@@ -203,7 +203,202 @@ async fn subquery_not_allowed() -> Result<()> {
     let err = dataframe.into_optimized_plan().err().unwrap();
 
     assert_eq!(
-        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can not be used in Sort plan nodes"))"#,
+        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can only be used in Projection, Filter, Window functions, Aggregate and Join plan nodes"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1_int group by t2_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery_with_limit() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 2) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery_with_single_row() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:UInt32;N]",
+        "  Subquery: [t2_int:UInt32;N]",
+        "    Limit: skip=0, fetch=1 [t2_int:UInt32;N]",
+        "      Projection: t2.t2_int [t2_int:UInt32;N]",
+        "        Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "          TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    let sql = "SELECT t1_id from t1 where t1_int = (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1)";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id [t1_id:UInt32;N]",
+        "  Filter: t1.t1_int = (<subquery>) [t1_id:UInt32;N, t1_int:UInt32;N]",
+        "    Subquery: [t2_int:UInt32;N]",
+        "      Limit: skip=0, fetch=1 [t2_int:UInt32;N]",
+        "        Projection: t2.t2_int [t2_int:UInt32;N]",
+        "          Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "            TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "    TableScan: t1 projection=[t1_id, t1_int] [t1_id:UInt32;N, t1_int:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    let sql = "SELECT t1_id, (SELECT a FROM (select 1 as a) WHERE a = t1.t1_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:Int64]",
+        "  Subquery: [a:Int64]",
+        "    Projection: a [a:Int64]",
+        "      Filter: a = CAST(outer_ref(t1.t1_int) AS Int64) [a:Int64]",
+        "        Projection: Int64(1) AS a [a:Int64]",
+        "          EmptyRelation []",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_equal_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id < t1.t1_id) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated column is not allowed in predicate: t2.t2_id < outer_ref(t1.t1_id)"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn aggregated_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_sum [t1_id:UInt32;N, t2_sum:UInt64;N]",
+        "  Subquery: [SUM(t2.t2_int):UInt64;N]",
+        "    Projection: SUM(t2.t2_int) [SUM(t2.t2_int):UInt64;N]",
+        "      Aggregate: groupBy=[[]], aggr=[[SUM(t2.t2_int)]] [SUM(t2.t2_int):UInt64;N]",
+        "        Filter: t2.t2_id = outer_ref(t1.t1_id) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "          TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn aggregated_correlated_scalar_subquery_with_extra_group_by_columns() -> Result<()>
+{
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id group by t2_name) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+

Review Comment:
   Sure, will add.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1176640402


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,

Review Comment:
   I think the minimum number of rows for an inner join  is `None` (for unknown) in the case of an Inner join, rather than 0. 



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.

Review Comment:
   ```suggestion
       /// Returns the maximum number of rows that this plan can output, if known.
       ///
       /// If `None`, the plan can return any number of rows. 
       /// If `Some(n)` then the plan can return at most `n` rows
       /// but may return fewer.
   ```



##########
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(),

Review Comment:
   It would be nice to return the output schema / columns in this message to help users -- maybe something like this (untested)
   
   ```suggestion
                   format!("Scalar subquery should only return one column, found {}: {}", 
                   subquery.subquery.schema().fields().len(),
                   subquery.subquery.schema().field_names()
                   )
   ```



##########
datafusion/optimizer/src/decorrelate_where_in.rs:
##########
@@ -602,7 +596,7 @@ mod tests {
             .build()?;
 
         let expected = "Projection: customer.c_custkey [c_custkey:Int64]\
-        \n  LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]\

Review Comment:
   this seems like an improvement to me



##########
datafusion/optimizer/src/test/mod.rs:
##########
@@ -171,6 +190,23 @@ pub fn assert_optimized_plan_eq_display_indent(
     assert_eq!(formatted_plan, expected);
 }
 
+pub fn assert_multi_rules_optimized_plan_eq_display_indent(
+    rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
+    plan: &LogicalPlan,
+    expected: &str,
+) {
+    let optimizer = Optimizer::with_rules(rules);
+    let mut optimized_plan = plan.clone();
+    for rule in &optimizer.rules {
+        optimized_plan = optimizer
+            .optimize_recursively(rule, &optimized_plan, &OptimizerContext::new())
+            .expect("failed to optimize plan")
+            .unwrap_or_else(|| optimized_plan.clone());
+    }
+    let formatted_plan = format!("{}", optimized_plan.display_indent_schema());

Review Comment:
   ```suggestion
       let formatted_plan = optimized_plan.display_indent_schema().to_string();
   ```



##########
datafusion/optimizer/src/test/mod.rs:
##########
@@ -134,6 +134,25 @@ pub fn assert_analyzed_plan_eq_display_indent(
 
     Ok(())
 }
+
+pub fn assert_analyzer_check_err(
+    rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>,
+    plan: &LogicalPlan,
+    expected: &str,
+) {
+    let options = ConfigOptions::default();
+    let analyzed_plan =
+        Analyzer::with_rules(rules).execute_and_check(plan, &options, |_, _| {});
+    match analyzed_plan {
+        Ok(plan) => assert_eq!(format!("{}", plan.display_indent()), "An error"),
+        Err(ref e) => {
+            let actual = format!("{e}");
+            if expected.is_empty() || !actual.contains(expected) {
+                assert_eq!(actual, expected)
+            }
+        }

Review Comment:
   ```suggestion
           Err(e) => {assert_contains!(e.to_string(), expected);},
   ```



##########
datafusion/optimizer/src/decorrelate_where_in.rs:
##########
@@ -557,7 +548,7 @@ mod tests {
         let sq = Arc::new(
             LogicalPlanBuilder::from(scan_tpch_table("orders"))
                 .filter(
-                    col("customer.c_custkey")
+                    out_ref_col(DataType::Int64, "customer.c_custkey")

Review Comment:
   I do like the idea that when creating expressions directly outer references must be annotated explicitly



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,
+                            };
+                            Some((left_max * right_max).max(min_rows))
+                        }
+                        _ => None,
+                    }
+                }
+                JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),
+                JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),
+            },
+            LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
+                match (left.max_rows(), right.max_rows()) {
+                    (Some(left_max), Some(right_max)) => Some(left_max * right_max),
+                    _ => None,
+                }
+            }
+            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
+            LogicalPlan::Union(Union { inputs, .. }) => inputs
+                .iter()
+                .map(|plan| plan.max_rows())
+                .try_fold(0usize, |mut acc, input_max| {
+                    if let Some(i_max) = input_max {
+                        acc += i_max;
+                        Some(acc)
+                    } else {
+                        None
+                    }
+                }),
+            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,
+            LogicalPlan::EmptyRelation(_) => Some(0),
+            LogicalPlan::Subquery(_) => None,
+            LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.max_rows(),
+            LogicalPlan::Limit(Limit { fetch, .. }) => *fetch,
+            LogicalPlan::Distinct(Distinct { input }) => input.max_rows(),
+            LogicalPlan::Unnest(_) => None,
+            LogicalPlan::CreateMemoryTable(_)
+            | LogicalPlan::CreateExternalTable(_)
+            | LogicalPlan::CreateView(_)
+            | LogicalPlan::CreateCatalogSchema(_)
+            | LogicalPlan::CreateCatalog(_)
+            | LogicalPlan::DropTable(_)
+            | LogicalPlan::DropView(_)
+            | LogicalPlan::Explain(_)
+            | LogicalPlan::Analyze(_)
+            | LogicalPlan::Dml(_)
+            | LogicalPlan::DescribeTable(_)
+            | LogicalPlan::Prepare(_)
+            | LogicalPlan::Statement(_)
+            | LogicalPlan::Values(_)

Review Comment:
   The number of rows that comes out of `Values` is known. Something like:
   
   ```
               | LogicalPlan::Values(v) => Some(v.values.len())
   ```



##########
datafusion/optimizer/src/scalar_subquery_to_join.rs:
##########
@@ -511,16 +500,17 @@ mod tests {
 
         // it will optimize, but fail for the same reason the unoptimized query would
         let expected = "Projection: customer.c_custkey [c_custkey:Int64]\
-        \n  Filter: customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, __value:Int64;N]\
-        \n    CrossJoin: [c_custkey:Int64, c_name:Utf8, __value:Int64;N]\
-        \n      TableScan: customer [c_custkey:Int64, c_name:Utf8]\
-        \n      SubqueryAlias: __scalar_sq_1 [__value:Int64;N]\
-        \n        Projection: MAX(orders.o_custkey) AS __value [__value:Int64;N]\
-        \n          Aggregate: groupBy=[[]], aggr=[[MAX(orders.o_custkey)]] [MAX(orders.o_custkey):Int64;N]\
-        \n            Filter: customer.c_custkey = customer.c_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]\
-        \n              TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";
-        assert_optimized_plan_eq_display_indent(
-            Arc::new(ScalarSubqueryToJoin::new()),
+        \n  Inner Join: customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, __value:Int64;N]\

Review Comment:
   that looks like a better plan to me



##########
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:
   it seems like you might be able to include this logic in `LogicalPlan::max_rows()` and avoid having a special check for aggregates



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177411640


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,

Review Comment:
   Why it is `None`(unknown) for inner join ? I think it is 0. 
   In the case the left max and right max are already known, if the inner join prune all the results(no match tuples), the `min_row` should be 0.
   



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#issuecomment-1523223141

   🚀 


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177431598


##########
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() {
+        return Err(DataFusionError::Plan(
+            "Correlated scalar subquery must be aggregated to return at most one row"
+                .to_string(),
+        ));
+    }
+    if !agg.group_expr.is_empty() {
+        let correlated_exprs = get_correlated_expressions(inner_plan)?;
+        let inner_subquery_cols =
+            collect_subquery_cols(&correlated_exprs, agg.input.schema().clone())?;
+        let mut group_columns = agg
+            .group_expr
+            .iter()
+            .map(|group| Ok(group.to_columns()?.into_iter().collect::<Vec<_>>()))
+            .collect::<Result<Vec<_>>>()?
+            .into_iter()
+            .flatten();
+
+        if !group_columns.all(|group| inner_subquery_cols.contains(&group)) {
+            // Group BY columns must be a subset of columns in the correlated expressions
+            return Err(DataFusionError::Plan(
+                "A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"
+                    .to_string(),
+            ));
+        }
+    }
+    Ok(())
+}
+
+fn strip_inner_query(inner_plan: &LogicalPlan) -> &LogicalPlan {
+    match inner_plan {
+        LogicalPlan::Projection(projection) => {
+            strip_inner_query(projection.input.as_ref())
+        }
+        LogicalPlan::SubqueryAlias(alias) => strip_inner_query(alias.input.as_ref()),
+        other => other,
+    }
+}
+
+fn get_correlated_expressions(inner_plan: &LogicalPlan) -> Result<Vec<Expr>> {
+    let mut exprs = vec![];
+    inner_plan.apply(&mut |plan| {
+        if let LogicalPlan::Filter(Filter { predicate, .. }) = plan {
+            let (correlated, _): (Vec<_>, Vec<_>) = split_conjunction(predicate)
+                .into_iter()
+                .partition(|e| e.contains_outer());
+
+            correlated
+                .into_iter()
+                .for_each(|expr| exprs.push(strip_outer_reference(expr.clone())));
+            return Ok(VisitRecursion::Continue);
+        }
+        Ok(VisitRecursion::Continue)
+    })?;
+    Ok(exprs)
+}
+
+/// Check whether the expression can pull up over the aggregation without change the result of the query
+fn can_pullup_over_aggregation(expr: &Expr) -> bool {
+    if let Expr::BinaryExpr(BinaryExpr {
+        left,
+        op: Operator::Eq,
+        right,
+    }) = expr
+    {
+        match (left.deref(), right.deref()) {
+            (Expr::Column(_), right) if right.to_columns().unwrap().is_empty() => true,
+            (left, Expr::Column(_)) if left.to_columns().unwrap().is_empty() => true,
+            (Expr::Cast(Cast { expr, .. }), right)
+                if matches!(expr.deref(), Expr::Column(_))
+                    && right.to_columns().unwrap().is_empty() =>
+            {
+                true
+            }
+            (left, Expr::Cast(Cast { expr, .. }))
+                if matches!(expr.deref(), Expr::Column(_))
+                    && left.to_columns().unwrap().is_empty() =>
+            {
+                true
+            }
+            (_, _) => false,
+        }
+    } else {
+        false
+    }
+}
+
+/// Check whether the window expressions contain a mixture of out reference columns and inner columns
+fn check_mixed_out_refer_in_window(window: &Window) -> Result<()> {
+    let mixed = window.window_expr.iter().any(|win_expr| {
+        win_expr.contains_outer() && !win_expr.to_columns().unwrap().is_empty()

Review Comment:
   I'm afraid I can not use the `?` inside the closure `iter().any(|| )`



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177421423


##########
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(),
+                        ))
+                    }

Review Comment:
   Yes, you are right. 
   Some of the systems introduced additional operator like `MaxNumRows` operator to do the runtime check.  
   I'm not very familiar with Presto/Trino, would you please share me the code ?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
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:
   I think the the special check for aggregate is required, the `max_rows` is a default path if the top non projection sub query plan is not an aggregate.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177530091


##########
datafusion/optimizer/src/decorrelate_where_in.rs:
##########
@@ -602,7 +596,7 @@ mod tests {
             .build()?;
 
         let expected = "Projection: customer.c_custkey [c_custkey:Int64]\
-        \n  LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]\

Review Comment:
   Yes, a redundant filter was removed.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#issuecomment-1521890083

   I am reviewing this now 


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] yukkit commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177745258


##########
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(),
+                        ))
+                    }

Review Comment:
   If it is checked at runtime, additional operators need to be introduced. The current pr is much better than before, and this feature can be implemented in future plans. The code of presto is here https://github.com/prestodb/presto/blob/master/presto-main/src/main/java/com/facebook/presto/sql/planner/iterative/rule/TransformCorrelatedScalarSubquery.java



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177295506


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }

Review Comment:
   Good point. I will try add this in this PR.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177514606


##########
datafusion/optimizer/src/test/mod.rs:
##########
@@ -134,6 +134,25 @@ pub fn assert_analyzed_plan_eq_display_indent(
 
     Ok(())
 }
+
+pub fn assert_analyzer_check_err(
+    rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>,
+    plan: &LogicalPlan,
+    expected: &str,
+) {
+    let options = ConfigOptions::default();
+    let analyzed_plan =
+        Analyzer::with_rules(rules).execute_and_check(plan, &options, |_, _| {});
+    match analyzed_plan {
+        Ok(plan) => assert_eq!(format!("{}", plan.display_indent()), "An error"),
+        Err(ref e) => {
+            let actual = format!("{e}");
+            if expected.is_empty() || !actual.contains(expected) {
+                assert_eq!(actual, expected)
+            }
+        }

Review Comment:
   Done



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#issuecomment-1523577000

   I will merge this PR and continue working on following improvement.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#issuecomment-1521377142

   @jackwener 
   Would you please help to take a look at this PR? 


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] jackwener commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "jackwener (via GitHub)" <gi...@apache.org>.
jackwener commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1174520433


##########
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() {
+        return Err(DataFusionError::Plan(
+            "Correlated scalar subquery must be aggregated to return at most one row"
+                .to_string(),
+        ));
+    }
+    if !agg.group_expr.is_empty() {
+        let correlated_exprs = get_correlated_expressions(inner_plan)?;
+        let inner_subquery_cols =
+            collect_subquery_cols(&correlated_exprs, agg.input.schema().clone())?;
+        let mut group_columns = agg
+            .group_expr
+            .iter()
+            .map(|group| Ok(group.to_columns()?.into_iter().collect::<Vec<_>>()))
+            .collect::<Result<Vec<_>>>()?
+            .into_iter()
+            .flatten();
+
+        if !group_columns.all(|group| inner_subquery_cols.contains(&group)) {
+            // Group BY columns must be a subset of columns in the correlated expressions
+            return Err(DataFusionError::Plan(
+                "A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"
+                    .to_string(),
+            ));
+        }
+    }
+    Ok(())
+}
+
+fn strip_inner_query(inner_plan: &LogicalPlan) -> &LogicalPlan {
+    match inner_plan {
+        LogicalPlan::Projection(projection) => {
+            strip_inner_query(projection.input.as_ref())
+        }
+        LogicalPlan::SubqueryAlias(alias) => strip_inner_query(alias.input.as_ref()),
+        other => other,
+    }
+}
+
+fn get_correlated_expressions(inner_plan: &LogicalPlan) -> Result<Vec<Expr>> {
+    let mut exprs = vec![];
+    inner_plan.apply(&mut |plan| {
+        if let LogicalPlan::Filter(Filter { predicate, .. }) = plan {
+            let (correlated, _): (Vec<_>, Vec<_>) = split_conjunction(predicate)
+                .into_iter()
+                .partition(|e| e.contains_outer());
+
+            correlated
+                .into_iter()
+                .for_each(|expr| exprs.push(strip_outer_reference(expr.clone())));
+            return Ok(VisitRecursion::Continue);
+        }
+        Ok(VisitRecursion::Continue)
+    })?;
+    Ok(exprs)
+}
+
+/// Check whether the expression can pull up over the aggregation without change the result of the query
+fn can_pullup_over_aggregation(expr: &Expr) -> bool {
+    if let Expr::BinaryExpr(BinaryExpr {
+        left,
+        op: Operator::Eq,
+        right,
+    }) = expr
+    {
+        match (left.deref(), right.deref()) {
+            (Expr::Column(_), right) if right.to_columns().unwrap().is_empty() => true,
+            (left, Expr::Column(_)) if left.to_columns().unwrap().is_empty() => true,
+            (Expr::Cast(Cast { expr, .. }), right)
+                if matches!(expr.deref(), Expr::Column(_))
+                    && right.to_columns().unwrap().is_empty() =>
+            {
+                true
+            }
+            (left, Expr::Cast(Cast { expr, .. }))
+                if matches!(expr.deref(), Expr::Column(_))
+                    && left.to_columns().unwrap().is_empty() =>
+            {
+                true
+            }
+            (_, _) => false,
+        }
+    } else {
+        false
+    }
+}
+
+/// Check whether the window expressions contain a mixture of out reference columns and inner columns
+fn check_mixed_out_refer_in_window(window: &Window) -> Result<()> {
+    let mixed = window.window_expr.iter().any(|win_expr| {
+        win_expr.contains_outer() && !win_expr.to_columns().unwrap().is_empty()

Review Comment:
   ```suggestion
           win_expr.contains_outer() && !win_expr.to_columns()?.is_empty()
   ```



##########
datafusion/core/tests/sql/subqueries.rs:
##########
@@ -203,7 +203,202 @@ async fn subquery_not_allowed() -> Result<()> {
     let err = dataframe.into_optimized_plan().err().unwrap();
 
     assert_eq!(
-        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can not be used in Sort plan nodes"))"#,
+        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can only be used in Projection, Filter, Window functions, Aggregate and Join plan nodes"))"#,

Review Comment:
   👍



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,
+                            };
+                            Some((left_max * right_max).max(min_rows))
+                        }
+                        _ => None,
+                    }
+                }
+                JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),
+                JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),
+            },
+            LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
+                match (left.max_rows(), right.max_rows()) {
+                    (Some(left_max), Some(right_max)) => Some(left_max * right_max),
+                    _ => None,
+                }
+            }
+            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
+            LogicalPlan::Union(Union { inputs, .. }) => inputs
+                .iter()
+                .map(|plan| plan.max_rows())
+                .try_fold(0usize, |mut acc, input_max| {
+                    if let Some(i_max) = input_max {
+                        acc += i_max;
+                        Some(acc)
+                    } else {
+                        None
+                    }
+                }),
+            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,

Review Comment:
   I'm not sure about whether `fetch` is accurate.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
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:
   I think the the special check for aggregate is required, the `max_rows` is a default fallback path if the top non projection sub query plan is not an aggregate.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177491136


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.

Review Comment:
   Done



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,
+                            };
+                            Some((left_max * right_max).max(min_rows))
+                        }
+                        _ => None,
+                    }
+                }
+                JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),
+                JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),
+            },
+            LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
+                match (left.max_rows(), right.max_rows()) {
+                    (Some(left_max), Some(right_max)) => Some(left_max * right_max),
+                    _ => None,
+                }
+            }
+            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
+            LogicalPlan::Union(Union { inputs, .. }) => inputs
+                .iter()
+                .map(|plan| plan.max_rows())
+                .try_fold(0usize, |mut acc, input_max| {
+                    if let Some(i_max) = input_max {
+                        acc += i_max;
+                        Some(acc)
+                    } else {
+                        None
+                    }
+                }),
+            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,
+            LogicalPlan::EmptyRelation(_) => Some(0),
+            LogicalPlan::Subquery(_) => None,
+            LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.max_rows(),
+            LogicalPlan::Limit(Limit { fetch, .. }) => *fetch,
+            LogicalPlan::Distinct(Distinct { input }) => input.max_rows(),
+            LogicalPlan::Unnest(_) => None,
+            LogicalPlan::CreateMemoryTable(_)
+            | LogicalPlan::CreateExternalTable(_)
+            | LogicalPlan::CreateView(_)
+            | LogicalPlan::CreateCatalogSchema(_)
+            | LogicalPlan::CreateCatalog(_)
+            | LogicalPlan::DropTable(_)
+            | LogicalPlan::DropView(_)
+            | LogicalPlan::Explain(_)
+            | LogicalPlan::Analyze(_)
+            | LogicalPlan::Dml(_)
+            | LogicalPlan::DescribeTable(_)
+            | LogicalPlan::Prepare(_)
+            | LogicalPlan::Statement(_)
+            | LogicalPlan::Values(_)

Review Comment:
   Done



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] yukkit commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177293592


##########
datafusion/core/tests/sql/subqueries.rs:
##########
@@ -203,7 +203,202 @@ async fn subquery_not_allowed() -> Result<()> {
     let err = dataframe.into_optimized_plan().err().unwrap();
 
     assert_eq!(
-        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can not be used in Sort plan nodes"))"#,
+        r#"Context("check_analyzed_plan", Plan("In/Exist subquery can only be used in Projection, Filter, Window functions, Aggregate and Join plan nodes"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1_int group by t2_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery_with_limit() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 2) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_aggregated_correlated_scalar_subquery_with_single_row() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:UInt32;N]",
+        "  Subquery: [t2_int:UInt32;N]",
+        "    Limit: skip=0, fetch=1 [t2_int:UInt32;N]",
+        "      Projection: t2.t2_int [t2_int:UInt32;N]",
+        "        Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "          TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    let sql = "SELECT t1_id from t1 where t1_int = (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1)";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id [t1_id:UInt32;N]",
+        "  Filter: t1.t1_int = (<subquery>) [t1_id:UInt32;N, t1_int:UInt32;N]",
+        "    Subquery: [t2_int:UInt32;N]",
+        "      Limit: skip=0, fetch=1 [t2_int:UInt32;N]",
+        "        Projection: t2.t2_int [t2_int:UInt32;N]",
+        "          Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "            TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "    TableScan: t1 projection=[t1_id, t1_int] [t1_id:UInt32;N, t1_int:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    let sql = "SELECT t1_id, (SELECT a FROM (select 1 as a) WHERE a = t1.t1_int) as t2_int from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:Int64]",
+        "  Subquery: [a:Int64]",
+        "    Projection: a [a:Int64]",
+        "      Filter: a = CAST(outer_ref(t1.t1_int) AS Int64) [a:Int64]",
+        "        Projection: Int64(1) AS a [a:Int64]",
+        "          EmptyRelation []",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn non_equal_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id < t1.t1_id) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("Correlated column is not allowed in predicate: t2.t2_id < outer_ref(t1.t1_id)"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn aggregated_correlated_scalar_subquery() -> Result<()> {
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let plan = dataframe.into_optimized_plan()?;
+
+    let expected = vec![
+        "Projection: t1.t1_id, (<subquery>) AS t2_sum [t1_id:UInt32;N, t2_sum:UInt64;N]",
+        "  Subquery: [SUM(t2.t2_int):UInt64;N]",
+        "    Projection: SUM(t2.t2_int) [SUM(t2.t2_int):UInt64;N]",
+        "      Aggregate: groupBy=[[]], aggr=[[SUM(t2.t2_int)]] [SUM(t2.t2_int):UInt64;N]",
+        "        Filter: t2.t2_id = outer_ref(t1.t1_id) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "          TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",
+        "  TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",
+    ];
+    let formatted = plan.display_indent_schema().to_string();
+    let actual: Vec<&str> = formatted.trim().lines().collect();
+    assert_eq!(
+        expected, actual,
+        "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"
+    );
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn aggregated_correlated_scalar_subquery_with_extra_group_by_columns() -> Result<()>
+{
+    let ctx = create_join_context("t1_id", "t2_id", true)?;
+
+    let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id group by t2_name) as t2_sum from t1";
+    let msg = format!("Creating logical plan for '{sql}'");
+    let dataframe = ctx.sql(sql).await.expect(&msg);
+    let err = dataframe.into_optimized_plan().err().unwrap();
+
+    assert_eq!(
+        r#"Context("check_analyzed_plan", Plan("A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"))"#,
+        &format!("{err:?}")
+    );
+
+    Ok(())
+}
+

Review Comment:
   An `aggregated_correlated_scalar_subquery_with_extra_group_by_constant` case could be added



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }

Review Comment:
   if is aggregation with GROUP BY 'a constant', It also always returns single row



##########
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(),
+                        ))
+                    }

Review Comment:
   IMO. When the number of returned results is unknown, can the checking logic be put into execution,I have seen that some databases do this, similar to presto. Of course, this has little effect.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] jackwener commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "jackwener (via GitHub)" <gi...@apache.org>.
jackwener commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177380859


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,

Review Comment:
   Agree it



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177416526


##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,
+                            };
+                            Some((left_max * right_max).max(min_rows))
+                        }
+                        _ => None,
+                    }
+                }
+                JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),
+                JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),
+            },
+            LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
+                match (left.max_rows(), right.max_rows()) {
+                    (Some(left_max), Some(right_max)) => Some(left_max * right_max),
+                    _ => None,
+                }
+            }
+            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
+            LogicalPlan::Union(Union { inputs, .. }) => inputs
+                .iter()
+                .map(|plan| plan.max_rows())
+                .try_fold(0usize, |mut acc, input_max| {
+                    if let Some(i_max) = input_max {
+                        acc += i_max;
+                        Some(acc)
+                    } else {
+                        None
+                    }
+                }),
+            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,

Review Comment:
   I think this `fetch` is set due to `limit` push down, if the `limit` is accurate,  I think it is OK
   for the scan nodes to return more than required.



##########
datafusion/expr/src/logical_plan/plan.rs:
##########
@@ -484,6 +484,97 @@ impl LogicalPlan {
             _ => Ok(self),
         }
     }
+
+    /// Returns the maximum number of rows that this plan can output.
+    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
+        match self {
+            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
+            LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),
+            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
+            LogicalPlan::Aggregate(Aggregate {
+                input, group_expr, ..
+            }) => {
+                if group_expr.is_empty() {
+                    Some(1)
+                } else {
+                    input.max_rows()
+                }
+            }
+            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
+                match (fetch, input.max_rows()) {
+                    (Some(fetch_limit), Some(input_max)) => {
+                        Some(input_max.min(*fetch_limit))
+                    }
+                    (Some(fetch_limit), None) => Some(*fetch_limit),
+                    (None, Some(input_max)) => Some(input_max),
+                    (None, None) => None,
+                }
+            }
+            LogicalPlan::Join(Join {
+                left,
+                right,
+                join_type,
+                ..
+            }) => match join_type {
+                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
+                    match (left.max_rows(), right.max_rows()) {
+                        (Some(left_max), Some(right_max)) => {
+                            let min_rows = match join_type {
+                                JoinType::Left => left_max,
+                                JoinType::Right => right_max,
+                                JoinType::Full => left_max + right_max,
+                                _ => 0,
+                            };
+                            Some((left_max * right_max).max(min_rows))
+                        }
+                        _ => None,
+                    }
+                }
+                JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),
+                JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),
+            },
+            LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
+                match (left.max_rows(), right.max_rows()) {
+                    (Some(left_max), Some(right_max)) => Some(left_max * right_max),
+                    _ => None,
+                }
+            }
+            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
+            LogicalPlan::Union(Union { inputs, .. }) => inputs
+                .iter()
+                .map(|plan| plan.max_rows())
+                .try_fold(0usize, |mut acc, input_max| {
+                    if let Some(i_max) = input_max {
+                        acc += i_max;
+                        Some(acc)
+                    } else {
+                        None
+                    }
+                }),
+            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,

Review Comment:
   I think this `fetch` is set due to `limit` push down, if the `limit` is accurate,  I think it is OK for the scan nodes to return more than required.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "mingmwang (via GitHub)" <gi...@apache.org>.
mingmwang commented on code in PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#discussion_r1177490594


##########
datafusion/optimizer/src/test/mod.rs:
##########
@@ -171,6 +190,23 @@ pub fn assert_optimized_plan_eq_display_indent(
     assert_eq!(formatted_plan, expected);
 }
 
+pub fn assert_multi_rules_optimized_plan_eq_display_indent(
+    rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
+    plan: &LogicalPlan,
+    expected: &str,
+) {
+    let optimizer = Optimizer::with_rules(rules);
+    let mut optimized_plan = plan.clone();
+    for rule in &optimizer.rules {
+        optimized_plan = optimizer
+            .optimize_recursively(rule, &optimized_plan, &OptimizerContext::new())
+            .expect("failed to optimize plan")
+            .unwrap_or_else(|| optimized_plan.clone());
+    }
+    let formatted_plan = format!("{}", optimized_plan.display_indent_schema());

Review Comment:
   Done



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] yukkit commented on pull request #6084: Move Scalar Subquery validation logic to the Analyzer

Posted by "yukkit (via GitHub)" <gi...@apache.org>.
yukkit commented on PR #6084:
URL: https://github.com/apache/arrow-datafusion/pull/6084#issuecomment-1522006261

   I will help review this PR tomorrow morning


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org