zinking commented on a change in pull request #32298:
URL: https://github.com/apache/spark/pull/32298#discussion_r709869699



##########
File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/MergeScalarSubqueries.scala
##########
@@ -0,0 +1,413 @@
+/*
+ * 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.ListBuffer
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, 
CommonScalarSubqueries, Filter, Join, LogicalPlan, Project, Subquery}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{SCALAR_SUBQUERY, 
SCALAR_SUBQUERY_REFERENCE, TreePattern}
+import org.apache.spark.sql.types.DataType
+
+/**
+ * This rule tries to merge multiple non-correlated [[ScalarSubquery]]s 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.
+ *   During this first traversal each [[ScalarSubquery]] expression is 
replaced to a
+ *   [[ScalarSubqueryReference]] pointing to its cached version.
+ *   The cache uses a flag to keep track of if a cache entry is a results of 
merging 2 or more
+ *   plans, or it is a plan that was seen only once.
+ *   Merged plans in the cache get a "header" that is is basically
+ *   `CreateNamedStructure(name1, attribute1, name2, attribute2, ...)`
+ *   expression in new root [[Project]] node. This expression ensures that the 
merged plan is a
+ *   valid scalar subquery that returns only one value.
+ * - A second traversal checks if a [[ScalarSubqueryReference]] is pointing to 
a merged subquery
+ *   plan or not and either keeps the reference or restores the original 
[[ScalarSubquery]].
+ *   If there are [[ScalarSubqueryReference]] nodes remained a 
[[CommonScalarSubqueries]] root node
+ *   is added to the plan with the referenced scalar subqueries.
+ * - [[PlanSubqueries]] or [[PlanAdaptiveSubqueries]] rule does the physical 
planning of scalar
+ *   subqueries including the ones under [[CommonScalarSubqueriesExec]] node 
and replaces
+ *   each [[ScalarSubqueryReference]] to their referenced physical plan in
+ *   `GetStructField(ScalarSubquery(merged plan with CreateNamedStruct() 
header))` form.
+ *   It is important that references pointing to the same merged subquery are 
replaced to the same
+ *   planned instance to make sure that each merged subquery runs only once 
(even without a wrapping
+ *   [[ReuseSubquery]] node).
+ *   Finally, the [[CommonScalarSubqueriesExec]] node is removed from the 
physical plan.
+ * - The [[ReuseExchangeAndSubquery]] rule wraps the second, third, ... 
instances of the same
+ *   subquery into a [[ReuseSubquery]] node, but this just a cosmetic change 
in the plan.
+ *
+ * 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
+ * +- OneRowRelation
+ *
+ * to:
+ *
+ * CommonScalarSubqueries [scalar-subquery#250 []]
+ * :  +- Project [named_struct(avg(a), avg(a)#236, sum(b), sum(b)#238L) AS 
mergedValue#249]
+ * :     +- Aggregate [b#234], [avg(a#233) AS avg(a)#236, sum(b#234) AS 
sum(b)#238L]
+ * :        +- Project [a#233, b#234]
+ * :           +- Relation default.t[a#233,b#234] parquet
+ * +- Project [scalarsubqueryreference(0, 0, DoubleType, 231) AS 
scalarsubquery()#241,
+ *             scalarsubqueryreference(0, 1, LongType, 232) AS 
scalarsubquery()#242L]
+ *    +- OneRowRelation
+ */
+object MergeScalarSubqueries extends Rule[LogicalPlan] with PredicateHelper {
+  def apply(plan: LogicalPlan): LogicalPlan = {
+    if (conf.subqueryReuseEnabled) {
+      plan match {
+        case Subquery(_: CommonScalarSubqueries, _) => plan
+        case s: Subquery => s.copy(child = 
extractCommonScalarSubqueries(s.child))
+        case _: CommonScalarSubqueries => plan
+        case _ => extractCommonScalarSubqueries(plan)
+      }
+    } else {
+      plan
+    }
+  }
+
+  private def extractCommonScalarSubqueries(plan: LogicalPlan) = {
+    // Plan of subqueries and a flag is the plan is merged
+    val cache = ListBuffer.empty[(Project, Boolean)]

Review comment:
       is it worthwhile to alias Project to some different type name that hint 
this is the merged header of scalar query ?




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



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

Reply via email to