peter-toth commented on a change in pull request #24831: [SPARK-19799][SQL] 
Better support for WITH clause
URL: https://github.com/apache/spark/pull/24831#discussion_r299179870
 
 

 ##########
 File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CTESubstitution.scala
 ##########
 @@ -0,0 +1,122 @@
+/*
+ * 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.analysis
+
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, With}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Analyze WITH nodes and substitute child plan with CTE definitions.
+ */
+object CTESubstitution extends Rule[LogicalPlan] {
+  def apply(plan: LogicalPlan): LogicalPlan = if 
(SQLConf.get.legacyCTESubstitutionEnabled) {
+    legacyTraverseAndsubstituteCTE(plan)
+  } else {
+    traverseAndSubstituteCTE(plan, false)
+  }
+
+  def legacyTraverseAndsubstituteCTE(plan: LogicalPlan): LogicalPlan = 
plan.resolveOperatorsUp {
+    case With(child, relations) =>
+      // substitute CTE expressions right-to-left to resolve references to 
previous CTEs:
+      // with a as (select * from t), b as (select * from a) select * from b
+      relations.foldRight(child) {
+        case ((cteName, ctePlan), currentPlan) => substituteCTE(currentPlan, 
cteName, ctePlan)
+      }
+    case other => other
+  }
+
+  /**
+   * Traverse the plan and expression nodes as a tree and replace matching 
references to CTE
+   * definitions.
+   * - If the rule encounters a WITH node then it substitutes the child of the 
node with CTE
+   *   definitions of the node right-to-left order as a definition can 
reference to a previous
+   *   one.
+   *   For example the following query is valid:
+   *   WITH
+   *     t AS (SELECT 1),
+   *     t2 AS (SELECT * FROM t)
+   *   SELECT * FROM t2
+   * - If a CTE definition contains an inner WITH node then substitution of 
inner should take
+   *   precedence because it can shadow an outer CTE definition.
+   *   For example the following query should return 2:
+   *   WITH
+   *     t AS (SELECT 1),
+   *     t2 AS (
+   *       WITH t AS (SELECT 2)
+   *       SELECT * FROM t
+   *     )
+   *   SELECT * FROM t2
+   * - If a CTE definition contains a subquery that contains an inner WITH 
node then substitution
+   *   of inner should take precedence because it can shadow an outer CTE 
definition.
+   *   For example the following query should return 2:
+   *   WITH t AS (SELECT 1 AS c)
+   *   SELECT max(c) FROM (
+   *     WITH t AS (SELECT 2 AS c)
+   *     SELECT * FROM t
+   *   )
+   * - If a CTE definition contains a subquery expression that contains an 
inner WITH node then
+   *   substitution of inner should take precedence because it can shadow an 
outer CTE
+   *   definition.
+   *   For example the following query should return 2:
+   *   WITH t AS (SELECT 1)
+   *   SELECT (
+   *     WITH t AS (SELECT 2)
+   *     SELECT * FROM t
+   *   )
+   * @param plan  the plan to be traversed
+   * @param inTraverse whether the current traverse is called from another 
traverse, only in this
+   *                   can name collision occur
+   * @return then plan where CTE substitution is applied
+   */
+  private def traverseAndSubstituteCTE(plan: LogicalPlan, inTraverse: 
Boolean): LogicalPlan =
+    plan.resolveOperatorsUp {
+      case With(child: LogicalPlan, relations) =>
+        val traversedChild = child transformExpressions {
+          case e: SubqueryExpression => 
e.withNewPlan(traverseAndSubstituteCTE(e.plan, true))
+        }
+
+        relations.foldRight(traversedChild) {
+          case ((cteName, ctePlan), currentPlan) =>
+            substituteCTE(currentPlan, cteName, 
traverseAndSubstituteCTE(ctePlan, true))
+        }
+
+      case o if inTraverse =>
+        o.transformExpressions {
+          case e: SubqueryExpression => 
e.withNewPlan(traverseAndSubstituteCTE(e.plan, inTraverse))
+        }
+    }
+
+  // A CTE definition might not be used at all so ctePlan is call by name.
+  private def substituteCTE(
+      plan: LogicalPlan,
+      cteName: String,
+      ctePlan: => LogicalPlan): LogicalPlan = {
+    lazy val lazyCTEPlan = ctePlan
 
 Review comment:
   I remember now why I used lazy here. A CTE definition can be used multiple 
times in `WITH` but the call by name parameter (`ctePlan  = 
traverseAndSubstituteCTE(...)`) should be executed only once.
   But now I believe it is better to use lazy outside of `substituteCTE` than 
inside, please review my commit 
https://github.com/apache/spark/pull/24831/commits/7d6910599134dc992bc841dfd3eff6f46d36647b.

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


With regards,
Apache Git Services

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

Reply via email to