peter-toth commented on a change in pull request #32298:
URL: https://github.com/apache/spark/pull/32298#discussion_r629183378



##########
File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/MergeScalarSubqueries.scala
##########
@@ -0,0 +1,184 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LeafNode, 
LogicalPlan, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{MULTI_SCALAR_SUBQUERY, 
SCALAR_SUBQUERY}
+
+/**
+ * This rule tries to merge multiple non-correlated [[ScalarSubquery]]s into a
+ * [[MultiScalarSubquery]] to compute multiple scalar values once.
+ *
+ * The process is the following:
+ * - While traversing through the plan each [[ScalarSubquery]] plan is tried 
to merge into the cache
+ *   of already seen subquery plans. If merge is possible then cache is 
updated with the merged
+ *   subquery plan, if not then the new subquery plan is added to the cache.
+ * - The original [[ScalarSubquery]] expression is replaced to a reference 
pointing to its cached
+ *   version in this form: 
`GetStructField(MultiScalarSubquery(SubqueryReference(...)))`.
+ * - A second traversal checks if a [[SubqueryReference]] is pointing to a 
subquery plan that
+ *   returns multiple values and either replaces only [[SubqueryReference]] to 
the cached plan or
+ *   restores the whole expression to its original [[ScalarSubquery]] form.
+ * - [[ReuseSubquery]] rule makes sure that merged subqueries are computed 
once.
+ *
+ * Eg. the following query:
+ *
+ * SELECT
+ *   (SELECT avg(a) FROM t GROUP BY b),
+ *   (SELECT sum(b) FROM t GROUP BY b)
+ *
+ * is optimized from:
+ *
+ * Project [scalar-subquery#231 [] AS scalarsubquery()#241,
+ *   scalar-subquery#232 [] AS scalarsubquery()#242L]
+ * :  :- Aggregate [b#234], [avg(a#233) AS avg(a)#236]
+ * :  :  +- Relation default.t[a#233,b#234] parquet
+ * :  +- Aggregate [b#240], [sum(b#240) AS sum(b)#238L]
+ * :     +- Project [b#240]
+ * :        +- Relation default.t[a#239,b#240] parquet

Review comment:
       > For instance, someone could implement a new Strategy that internally 
calls ColumnPruning after exploring one logical plan alternative. By the time 
such a Strategy is implemented, the authors wouldn't be aware of the fact that 
ColumnPruning should not be called after MergeScalarSubqueries.
   
   I see, thanks. I've never seen such transformations in `SparkStrategy`s. 
   
   But, if we followed (2) with non-correlated subqueries like this example:
   ```
   SELECT t1.*
   FROM t as t1
   JOIN t as t2 ON t2.a = t1.a
   WHERE
     t1.b = (SELECT sum(a) FROM t)
     AND t2.b = (SELECT count(a) FROM t)
   ```
   and if I get your (2) right the rewritten query is:
   ```
   SELECT t12.a, t12.b
   FROM (
     SELECT
       t1.*,
       (SELECT STRUCT(sum(a) AS sum_a, count(a) AS count_a) FROM t) AS st,
       t1.b AS t1_b,
       t2.b AS t2_b
     FROM t as t1
     JOIN t as t2 ON t2.a = t1.a
   ) t12
   WHERE
     t1_b = st.sum_a
     AND t2_b = st.count_a
   ```
   so we basically add an extra project node under `Filter`. The analyzed plan 
is:
   ```
   Project [a#237, b#238]
   +- Filter ((cast(t1_b#235 as bigint) = st#234.sum_a) AND (cast(t2_b#236 as 
bigint) = st#234.count_a))
      +- SubqueryAlias t12
         +- Project [a#237, b#238, scalar-subquery#233 [] AS st#234, b#238 AS 
t1_b#235, b#240 AS t2_b#236]
            :  +- Aggregate [struct(sum_a, sum(a#244), count_a, count(a#244)) 
AS struct(sum(a) AS sum_a, count(a) AS count_a)#243]
            :     +- SubqueryAlias spark_catalog.default.t
            :        +- Relation default.t[a#244,b#245] parquet
            +- Join Inner, (a#239 = a#237)
               :- SubqueryAlias t1
               :  +- SubqueryAlias spark_catalog.default.t
               :     +- Relation default.t[a#237,b#238] parquet
               +- SubqueryAlias t2
                  +- SubqueryAlias spark_catalog.default.t
                     +- Relation default.t[a#239,b#240] parquet
   ```
   The optimzer (`PushDownPredicates`) would duplicate and push down the 
subquery under both sides of the join:
   ```
   Project [a#237, b#238]
   +- Join Inner, (a#239 = a#237)
      :- Filter ((isnotnull(b#238) AND (cast(b#238 as bigint) = 
scalar-subquery#233 [].sum_a)) AND isnotnull(a#237))
      :  :  +- Aggregate [struct(sum_a, sum(a#244), count_a, count(a#244)) AS 
struct(sum(a) AS sum_a, count(a) AS count_a)#243]
      :  :     +- Project [a#244]
      :  :        +- Relation default.t[a#244,b#245] parquet
      :  +- Relation default.t[a#237,b#238] parquet
      +- Project [a#239]
         +- Filter ((isnotnull(b#240) AND (cast(b#240 as bigint) = 
scalar-subquery#233 [].count_a)) AND isnotnull(a#239))
            :  +- Aggregate [struct(sum_a, sum(a#244), count_a, count(a#244)) 
AS struct(sum(a) AS sum_a, count(a) AS count_a)#243]
            :     +- Project [a#244]
            :        +- Relation default.t[a#244,b#245] parquet
            +- Relation default.t[a#239,b#240] parquet
   ```
   Doesn't that mean that (2) also assumes that:
   - no subsequent transformation changes the 2 instances differently and 
   - `ReuseSubquery` does the dedup?
   




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to