xuanyuanking commented on a change in pull request #27454: [SPARK-28228][SQL] 
Change the default behavior for name conflict in nested WITH clause
URL: https://github.com/apache/spark/pull/27454#discussion_r375767892
 
 

 ##########
 File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CTESubstitution.scala
 ##########
 @@ -28,13 +29,55 @@ import 
org.apache.spark.sql.internal.SQLConf.LEGACY_CTE_PRECEDENCE_ENABLED
  */
 object CTESubstitution extends Rule[LogicalPlan] {
   def apply(plan: LogicalPlan): LogicalPlan = {
-    if (SQLConf.get.getConf(LEGACY_CTE_PRECEDENCE_ENABLED)) {
+    val isLegacy = SQLConf.get.getConf(LEGACY_CTE_PRECEDENCE_ENABLED)
+    if (isLegacy.isEmpty) {
+      if (detectConflictInNestedCTE(plan, inTraverse = false)) {
+        throw new AnalysisException("Name collision in nested CTE was founded 
in current plan, " +
+          s"please select the CTE precedence via 
${LEGACY_CTE_PRECEDENCE_ENABLED.key}, " +
+          "see more detail in SPARK-28228.")
+      } else {
+        traverseAndSubstituteCTE(plan, inTraverse = false)
+      }
+    } else if (isLegacy.get) {
       legacyTraverseAndSubstituteCTE(plan)
     } else {
-      traverseAndSubstituteCTE(plan, false)
+      traverseAndSubstituteCTE(plan, inTraverse = false)
     }
   }
 
+  /**
+   * Check the plan to be traversed has naming conflicts in nested CTE or not, 
traverse through
+   * child, innerChildren and subquery for the current plan.
+   */
+  private def detectConflictInNestedCTE(
+      plan: LogicalPlan,
+      inTraverse: Boolean,
+      cteNames: Set[String] = Set.empty): Boolean = {
+    plan.foreach {
+      case w @ With(child, relations) =>
+        val newNames = relations.map {
+          case (cteName, _) =>
+            if (cteNames.contains(cteName)) {
+              return true
 
 Review comment:
   Thanks, done in c03920a.

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