szehon-ho commented on code in PR #60559:
URL: https://github.com/apache/spark/pull/60559#discussion_r4629311749


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -107,8 +69,6 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand 
with PredicateHelper
           }
 
           val outputs = notMatchedInstructions.flatMap(_.outputs)
-
-          // merge rows as there are multiple NOT MATCHED actions
           val mergeRows = MergeRows(

Review Comment:
   Merged master's SPARK-61934 nullability fix (9c0bfc16481), which widens 
MergeRows output nullability after UDF null handling. Kept the 
CHECK-constrained regression covering both the Project path and the failed-fold 
MergeRows path.
   
   ---
   <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub 
MCP. -->
   _This comment was generated with [GitHub MCP](http://go/mcps)._



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -47,42 +47,6 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand 
with PredicateHelper
   override def apply(plan: LogicalPlan): LogicalPlan = 
plan.resolveOperatorsWithPruning(
     _.containsPattern(MERGE_INTO_TABLE)) {
     // aligned is false when schema evolution is pending (see 
ResolveRowLevelCommandAssignments)
-    case m @ MergeIntoTable(aliasedTable, source, cond, matchedActions, 
notMatchedActions,
-        notMatchedBySourceActions, _) if m.resolved && m.rewritable && 
m.aligned &&
-        matchedActions.isEmpty && notMatchedActions.size == 1 &&
-        notMatchedBySourceActions.isEmpty =>
-
-      EliminateSubqueryAliases(aliasedTable) match {
-        case r: DataSourceV2Relation =>
-          checkNoGeneratedColumns(r, MERGE)
-          validateMergeIntoConditions(m)
-
-          // NOT MATCHED conditions may only refer to columns in source so 
they can be pushed down
-          val insertAction = removeMetadataAssignments(notMatchedActions).head
-            .asInstanceOf[InsertAction]
-          val filteredSource = insertAction.condition match {
-            case Some(insertCond) => Filter(insertCond, source)
-            case None => source
-          }
-
-          // there is only one NOT MATCHED action, use a left anti join to 
remove any matching rows
-          // and switch to using a regular append instead of a row-level MERGE 
operation
-          // only unmatched source rows that match the condition are appended 
to the table
-          val joinPlan = Join(filteredSource, r, LeftAnti, Some(cond), 
JoinHint.NONE)
-
-          val output = insertAction.assignments.map(_.value)
-          val outputColNames = r.output.map(_.name)
-          val projectList = output.zip(outputColNames).map { case (expr, name) 
=>
-            Alias(expr, name)()
-          }
-          val project = Project(projectList, joinPlan)
-
-          InsertOnlyMerge(r, project)
-
-        case _ =>
-          m
-      }
-
     case m @ MergeIntoTable(aliasedTable, source, cond, matchedActions, 
notMatchedActions,

Review Comment:
   Restored the Project/Filter path during analysis when expression preparation 
and constant folding succeed, rather than waiting for an optimizer rule. Added 
regressions for correlated scalar, IN and EXISTS subqueries and window values, 
both directly and inside IF with a failing unused branch.
   
   ---
   <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub 
MCP. -->
   _This comment was generated with [GitHub MCP](http://go/mcps)._



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/OptimizeInsertOnlyMerge.scala:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Alias, AliasHelper, 
ConditionalExpression, Expression, Literal}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, 
TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.LeftAnti
+import org.apache.spark.sql.catalyst.plans.logical.{Filter, InsertOnlyMerge, 
Join, LogicalPlan, MergeRows, Project}
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.{Insert, Keep}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+
+/**
+ * Replaces a single insert instruction with a projection and source filter 
after constant folding.
+ */
+object OptimizeInsertOnlyMerge extends Rule[LogicalPlan] with AliasHelper {
+  override def apply(plan: LogicalPlan): LogicalPlan = 
plan.transformUpWithPruning(
+    _.containsPattern(COMMAND), ruleId) {
+    case merge @ InsertOnlyMerge(_, rows @ MergeRows(TrueLiteral, 
FalseLiteral, Nil,

Review Comment:
   Removed OptimizeInsertOnlyMerge. The Project/Filter decision now happens in 
RewriteMergeIntoTable, before CHECK wrapping or V1 analyzed-query 
reoptimization. The CHECK regression captures the actual execution and verifies 
the source predicate and absence of MergeRows.
   
   ---
   <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub 
MCP. -->
   _This comment was generated with [GitHub MCP](http://go/mcps)._



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