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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -171,6 +145,56 @@ object RewriteMergeIntoTable extends 
RewriteRowLevelCommand with PredicateHelper
     case _ => false
   }
 
+  /**
+   * Tries to build a Project/Filter plan for a single INSERT action.
+   *
+   * Note: Pushing the action condition below the anti join can evaluate it 
for source rows that
+   * match the target. Failures deferred inside IF/CASE in that condition must 
stay in MergeRows
+   * so matching rows skip the condition.
+   *
+   * Note: Later optimizer rules may introduce failing constants that this 
check cannot see.
+   */
+  private def tryBuildInsertOnlyMergeProject(
+      relation: DataSourceV2Relation,
+      source: LogicalPlan,
+      cond: Expression,
+      insertAction: InsertAction): Option[Project] = {
+    // Run ReplaceExpressions, ComputeCurrentTime and SpecialDatetimeValues 
before ConstantFolding
+    // to detect failures that Project/Filter would expose. A failed fold can 
throw directly or
+    // be tagged for runtime evaluation. MergeRows evaluates instructions 
conditionally, like
+    // IF/CASE branches, so failures occur only if the failing expression is 
reached.
+    val folded = try {
+      val replaced = ReplaceExpressions.replace(insertAction.clone())
+      val withCurrentTime = ComputeCurrentTime.applyForExpression(replaced)
+      val rewritten = SpecialDatetimeValues.applyForExpression(withCurrentTime)
+      ConstantFolding.constantFolding(rewritten).asInstanceOf[InsertAction]

Review Comment:
   Successful stable folds are now used in the planned expressions, including 
when another value requires MergeRows. Expressions changed by current-time or 
special-datetime preparation retain their originals so the optimizer can 
establish its query-wide snapshot. A counting-expression regression checks that 
a successful stable constant is evaluated once across rewriting and subsequent 
constant folding.
   
   ---
   <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub 
MCP. -->
   _This comment was generated with [GitHub MCP](http://go/mcps)._



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala:
##########
@@ -1893,6 +1894,257 @@ abstract class MergeIntoTableSuiteBase extends 
RowLevelOperationSuiteBase
     }
   }
 
+  test("MERGE defers constant-folding failures in unselected actions and 
conditions") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTempView("source") {
+        // BIGINT avoids wrapping DIVIDE_BY_ZERO in an assignment-cast 
overflow error.
+        createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+        Seq((1, 10L, "hr")).toDF("pk", "salary", 
"dep").createOrReplaceTempView("source")
+
+        val merge =
+          s"""MERGE INTO $tableNameAsString t
+             |USING source s
+             |ON t.pk = s.pk
+             |WHEN MATCHED AND s.salary < 0 THEN
+             | UPDATE SET salary = nullif(s.salary + 1 DIV 0, 0)
+             |WHEN MATCHED AND t.salary > 0 THEN UPDATE SET salary = s.salary
+             |WHEN MATCHED AND s.salary + 1 DIV 0 BETWEEN 1 AND 10 THEN DELETE
+             |WHEN NOT MATCHED AND 1 DIV 0 = 1 THEN
+             | INSERT (pk, salary, dep) VALUES (s.pk, 1 DIV 0, s.dep)
+             |WHEN NOT MATCHED BY SOURCE AND 1 DIV 0 = 1 THEN UPDATE SET 
salary = 1 DIV 0
+             |""".stripMargin
+        sql(merge)
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 10L, 
"hr"))
+
+        Seq((1, -1L, "hr")).toDF("pk", "salary", 
"dep").createOrReplaceTempView("source")
+        val error = intercept[SparkArithmeticException] {
+          sql(merge)
+        }
+        assert(error.getCondition == "DIVIDE_BY_ZERO")
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 10L, 
"hr"))
+      }
+    }
+  }
+
+  gridTest("insert-only MERGE defers constant-folding failures")(Seq(
+    "" -> "1 DIV 0",
+    "AND 1 DIV 0 = 1" -> "s.salary",
+    "AND IF(1 DIV 0 = 1, s.salary > 0, s.salary < 0)" -> "s.salary",
+    "AND IF(s.salary > 0, 1 DIV 0 = 1, FALSE)" -> "s.salary"
+  )) { case (condition, salary) =>
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTempView("source") {
+        // BIGINT avoids wrapping DIVIDE_BY_ZERO in an assignment-cast 
overflow error.
+        createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+
+        val merge =
+          s"""MERGE INTO $tableNameAsString t
+             |USING source s
+             |ON t.pk = s.pk
+             |WHEN NOT MATCHED $condition THEN
+             | INSERT (pk, salary, dep) VALUES (s.pk, $salary, s.dep)
+             |""".stripMargin
+
+        Seq((1, 10L, "hr")).toDF("pk", "salary", 
"dep").createOrReplaceTempView("source")
+        sql(merge)
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 100L, 
"hr"))
+
+        Seq((1, 10L, "hr"), (2, 20L, "hr"))
+          .toDF("pk", "salary", "dep").createOrReplaceTempView("source")
+        val error = intercept[SparkArithmeticException] {
+          sql(merge)
+        }
+        assert(error.getCondition == "DIVIDE_BY_ZERO")
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 100L, 
"hr"))
+      }
+    }
+  }
+
+  test("insert-only MERGE preserves condition pushdown with CHECK 
constraints") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTempView("source") {
+        createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+        sql(s"ALTER TABLE $tableNameAsString ADD CONSTRAINT positive_pk CHECK 
(pk > 0)")
+        spark.range(1, 4).selectExpr("CAST(id AS INT) AS pk", "id * 10 AS 
salary", "'hr' AS dep")
+          .createOrReplaceTempView("source")
+
+        val Seq(qe) = withQueryExecutionsCaptured(spark) {
+          sql(
+            s"""MERGE INTO $tableNameAsString t
+               |USING source s
+               |ON t.pk = s.pk
+               |WHEN NOT MATCHED AND s.salary < CAST('25' AS BIGINT) THEN
+               | INSERT (pk, salary, dep) VALUES (s.pk, s.salary, s.dep)
+               |""".stripMargin)
+        }
+        assert(qe.analyzed.collect { case m: MergeRows => m }.isEmpty)
+        val joins = qe.optimizedPlan.collect {
+          case j @ Join(_, _, LeftAnti, _, _) => j
+        }
+        assert(joins.size == 1, qe.optimizedPlan.treeString)
+        val sourceFilters = joins.head.left.collect { case Filter(condition, 
_) => condition }
+        assert(sourceFilters.exists(_.exists {
+          case LessThan(_, Literal(25L, _)) => true
+          case _ => false
+        }), qe.optimizedPlan.treeString)
+        assert(qe.optimizedPlan.collect { case m: MergeRows => m }.isEmpty)
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"),
+          Seq(Row(1, 100L, "hr"), Row(2, 20L, "hr")))
+      }
+    }
+  }
+
+  gridTest("single-insert MERGE accepts nondeterministic values")(Seq(false, 
true)) {
+      failingCondition =>
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTempView("source") {
+        createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+        val sourceKey = if (failingCondition) 1 else 2
+        Seq((sourceKey, "hr")).toDF("pk", 
"dep").createOrReplaceTempView("source")
+        val condition = if (failingCondition) "1 DIV 0 = 1" else "s.pk > 0"
+
+        sql(
+          s"""MERGE INTO $tableNameAsString t
+             |USING source s
+             |ON t.pk = s.pk
+             |WHEN NOT MATCHED AND $condition THEN
+             | INSERT (pk, salary, dep) VALUES (s.pk, CAST(rand() * 0 AS 
BIGINT), s.dep)
+             |""".stripMargin)
+
+        val expected = if (failingCondition) {
+          Seq(Row(1, 100L, "hr"))
+        } else {
+          Seq(Row(1, 100L, "hr"), Row(2, 0L, "hr"))
+        }
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), expected)
+      }
+    }
+  }
+
+  gridTest("MERGE rejects nondeterministic values outside the single-insert 
path")(Seq(
+    "WHEN MATCHED THEN UPDATE SET salary = s.salary",
+    "WHEN NOT MATCHED AND s.pk < 0 THEN INSERT *"
+  )) { extraClause =>
+    withTempView("source") {
+      createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING",
+        """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+      Seq((2, 20L, "hr")).toDF("pk", "salary", 
"dep").createOrReplaceTempView("source")
+
+      val error = intercept[AnalysisException] {
+        sql(
+          s"""MERGE INTO $tableNameAsString t
+             |USING source s ON t.pk = s.pk
+             |$extraClause
+             |WHEN NOT MATCHED THEN
+             | INSERT (pk, salary, dep) VALUES (s.pk, CAST(rand() * 0 AS 
BIGINT), s.dep)
+             |""".stripMargin)
+      }
+      assert(error.getCondition == "INVALID_NON_DETERMINISTIC_EXPRESSIONS")
+    }
+  }
+
+  gridTest("single-insert MERGE supports subqueries and window values")(for {
+    (value, expectedSalary) <- Seq(
+      "(SELECT max(o.salary) FROM other o WHERE o.dep = s.dep)" -> 20,
+      "IF(s.pk IN (SELECT o.pk FROM other o), 1, 0)" -> 1,
+      "IF(EXISTS(SELECT 1 FROM other o WHERE o.pk = s.pk), 1, 0)" -> 1,
+      "row_number() OVER (ORDER BY s.pk)" -> 1)
+    conditional <- Seq(false, true)
+  } yield (value, expectedSalary, conditional)) { case (value, expectedSalary, 
conditional) =>
+    withTempView("source", "other") {
+      createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+        """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+      Seq((2, "hr")).toDF("pk", "dep").createOrReplaceTempView("source")
+      Seq((2, 20, "hr")).toDF("pk", "salary", 
"dep").createOrReplaceTempView("other")
+      val salary = if (conditional) s"IF(s.pk > 0, $value, 1 DIV 0)" else value
+
+      val Seq(qe) = withQueryExecutionsCaptured(spark) {
+        sql(
+          s"""MERGE INTO $tableNameAsString t
+             |USING source s ON t.pk = s.pk
+             |WHEN NOT MATCHED THEN
+             | INSERT (pk, salary, dep) VALUES (s.pk, $salary, s.dep)
+             |""".stripMargin)
+      }
+      assert(qe.analyzed.collect { case m: MergeRows => m }.isEmpty)
+      checkAnswer(sql(s"SELECT * FROM $tableNameAsString"),
+        Seq(Row(1, 100, "hr"), Row(2, expectedSalary, "hr")))
+    }
+  }
+
+  gridTest("single-insert MERGE preserves nullable UDF values with CHECK 
constraints")(
+      Seq(false, true)) { failingConstant =>
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTempView("source") {
+        withUserDefinedFunction("merge_plus_one" -> true) {
+          spark.udf.register("merge_plus_one", (value: Int) => value + 1)
+          createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+            """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+          sql(s"ALTER TABLE $tableNameAsString ADD CONSTRAINT positive_pk 
CHECK (pk > 0)")
+          Seq((2, None: Option[Int], "hr")).toDF("pk", "salary", "dep")
+            .createOrReplaceTempView("source")
+          val condition = if (failingConstant) "s.pk > 0 OR 1 DIV 0 = 1" else 
"s.pk > 0"
+
+          val Seq(qe) = withQueryExecutionsCaptured(spark) {
+            sql(
+              s"""MERGE INTO $tableNameAsString t
+                 |USING source s ON t.pk = s.pk
+                 |WHEN NOT MATCHED AND ($condition) THEN
+                 | INSERT (pk, salary, dep) VALUES (s.pk, 
merge_plus_one(s.salary), s.dep)
+                 |""".stripMargin)
+          }
+          val rows = qe.analyzed.collect { case m: MergeRows => m }
+          assert(rows.nonEmpty == failingConstant)
+          checkAnswer(sql(s"SELECT * FROM $tableNameAsString"),
+            Seq(Row(1, 100, "hr"), Row(2, null, "hr")))
+        }
+      }
+    }
+  }
+
+  gridTest("MERGE rejects non-boolean action conditions")(Seq("s.salary", 
"s.salary + 1 DIV 0")) {

Review Comment:
   Expanded the non-boolean grid to cover MATCHED and NOT MATCHED BY SOURCE 
conditions, in addition to the single NOT MATCHED path. All assert 
FILTER_NOT_BOOLEAN during analysis.
   
   ---
   <!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub 
MCP. -->
   _This comment was generated with [GitHub MCP](http://go/mcps)._



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTableSuite.scala:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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 java.util.Collections
+
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, 
TrueLiteral}
+import org.apache.spark.sql.catalyst.optimizer.ConstantFolding
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.connector.catalog.InMemoryRowLevelOperationTable
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, DateType, DoubleType, 
LongType, StructType}
+
+class RewriteMergeIntoTableSuite extends PlanTest {
+  private val source = LocalRelation($"sourceId".long)
+  private val key = source.output.head
+  private val table = new InMemoryRowLevelOperationTable(
+    "target", new StructType().add("id", LongType), Array.empty, 
Collections.emptyMap())
+  private val target = DataSourceV2Relation.create(table, None, None)
+  private val joinCondition = key === target.output.head
+
+  private def rewrite(actions: Seq[InsertAction]): InsertOnlyMerge = {
+    val plan = MergeIntoTable(target, source, joinCondition, Nil, actions, Nil,
+      withSchemaEvolution = false)
+    assert(plan.resolved && plan.aligned)
+    RewriteMergeIntoTable(plan).asInstanceOf[InsertOnlyMerge]
+  }
+
+  private def insert(condition: Expression, value: Expression = key): 
InsertAction = {
+    InsertAction(Some(condition), Seq(Assignment(target.output.head, value)))
+  }
+
+  gridTest("preserve the projection when prepared constants fold")(Seq(
+    key > Cast(Literal("5"), LongType),
+    Cast(key, DoubleType) > new TryDivide(Literal(10.0), Literal(2.0)),
+    CurrentDate(Some("UTC")) === Cast(Literal("today"), DateType, Some("UTC"))

Review Comment:
   Added a condition containing current_timezone(), which is Unevaluable until 
ComputeCurrentTime replaces it. The Catalyst test requires the Project path, so 
removing the ComputeCurrentTime step now fails that assertion. SQL coverage 
also checks a failing cast built from current_timezone().
   
   ---
   <!-- 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:
##########
@@ -171,6 +145,56 @@ object RewriteMergeIntoTable extends 
RewriteRowLevelCommand with PredicateHelper
     case _ => false
   }
 
+  /**
+   * Tries to build a Project/Filter plan for a single INSERT action.
+   *
+   * Note: Pushing the action condition below the anti join can evaluate it 
for source rows that
+   * match the target. Failures deferred inside IF/CASE in that condition must 
stay in MergeRows
+   * so matching rows skip the condition.
+   *
+   * Note: Later optimizer rules may introduce failing constants that this 
check cannot see.
+   */
+  private def tryBuildInsertOnlyMergeProject(
+      relation: DataSourceV2Relation,
+      source: LogicalPlan,
+      cond: Expression,
+      insertAction: InsertAction): Option[Project] = {
+    // Run ReplaceExpressions, ComputeCurrentTime and SpecialDatetimeValues 
before ConstantFolding
+    // to detect failures that Project/Filter would expose. A failed fold can 
throw directly or
+    // be tagged for runtime evaluation. MergeRows evaluates instructions 
conditionally, like
+    // IF/CASE branches, so failures occur only if the failing expression is 
reached.
+    val folded = try {
+      val replaced = ReplaceExpressions.replace(insertAction.clone())
+      val withCurrentTime = ComputeCurrentTime.applyForExpression(replaced)
+      val rewritten = SpecialDatetimeValues.applyForExpression(withCurrentTime)
+      ConstantFolding.constantFolding(rewritten).asInstanceOf[InsertAction]
+    } catch {
+      case NonFatal(e) =>
+        logInfo(log"Keeping MergeRows for insert-only MERGE because expression 
preparation " +

Review Comment:
   Kept the expected preparation/folding fallback message at INFO and removed 
the exception argument, so it no longer emits a stack trace.
   
   ---
   <!-- 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