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: [email protected]

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

Reply via email to