dongjoon-hyun commented on code in PR #60559:
URL: https://github.com/apache/spark/pull/60559#discussion_r4637215776


##########
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 " +
+          log"or constant folding failed.", e)
+        return None
+    }
+
+    if (folded.condition.exists(

Review Comment:
   **[16] A failed fold in the condition makes subqueries and window functions 
in the values fail analysis.**
   
   With the check that [4] asked for, a condition that keeps a 
`FAILED_TO_EVALUATE` tag now keeps `MergeRows`, and `MergeRows` cannot hold 
what the `Project` handles ([2]). So this single-clause MERGE, which master 
runs, fails analysis (ANSI on; the target holds (1, 100, 'hr'); `source` and 
`other` hold (2, 20, 'hr')):
   
   ```sql
   MERGE INTO t USING source s ON t.pk = s.pk
   WHEN NOT MATCHED AND IF(s.pk > 0, TRUE, 1 DIV 0 = 1) THEN
     INSERT (pk, salary, dep)
     VALUES (s.pk, (SELECT max(o.salary) FROM other o WHERE o.dep = s.dep), 
s.dep)
   ```
   
   master inserts (2, 20, 'hr'), and this PR fails with 
`UNSUPPORTED_CORRELATED_SCALAR_SUBQUERY`. With the same condition, `IF(s.pk IN 
(SELECT o.pk FROM other o), 1, 0)` and the `EXISTS` form fail with 
`UNSUPPORTED_IN_EXISTS_SUBQUERY`, and `row_number() OVER (ORDER BY s.pk)` fails 
with `UNSUPPORTED_EXPR_FOR_OPERATOR`. The condition is also no longer pushed 
down: for `AND s.salary < 25 AND CASE WHEN s.dep = 'hr' THEN TRUE ELSE CAST('x' 
AS INT) > 0 END`, master filters the source below the anti join, and this PR 
evaluates the whole condition in `MergeRowsExec` after the full anti join. When 
a value fails to fold instead, a subquery in another value changes the error 
from `DIVIDE_BY_ZERO` to the same analysis errors. The test at 
`MergeIntoTableSuiteBase.scala` L2050 covers these values only with a condition 
that folds.
   
   The branch does fix what [4] was about, the pushed condition running on 
matched rows. Could it apply only when `MergeRows` can plan the values, and 
fall back to the `Project` and `Filter` when the action holds a subquery or a 
window expression? Those statements would then behave as on master.



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

Review Comment:
   **[17] `ReplaceCurrentLike` is missing from the rules that run before 
folding.**
   
   The optimizer runs `ComputeCurrentTime`, `ReplaceCurrentLike` and 
`SpecialDatetimeValues` before `ConstantFolding`, and this replays the first 
and the last. `current_database()`, `current_catalog()`, `current_user()` and 
`current_path()` are `Unevaluable`, so the check does not fold them and picks 
the `Project`. The optimizer then replaces them with literals and folds the 
expressions around them. With ANSI on and every source row matched:
   
   ```sql
   MERGE INTO t USING source s ON t.pk = s.pk
   WHEN NOT MATCHED THEN
     INSERT (pk, salary, dep) VALUES (s.pk, CAST(current_database() AS BIGINT), 
s.dep)
   ```
   
   fails during optimization with `CAST_INVALID_INPUT` for 'default', although 
no row is inserted. The same clause after `WHEN NOT MATCHED AND s.pk < 0 THEN 
INSERT ...` completes with this PR. This is close to the limitation in the 
reply to [5], but the check already replays the other two rules of that batch. 
`ReplaceCurrentLike` needs the `CatalogManager`; if that is not available here, 
keeping `MergeRows` for an action that still has the `CURRENT_LIKE` pattern 
after `ComputeCurrentTime` would also work.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -119,7 +87,13 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand 
with PredicateHelper
             output = generateExpandOutput(dataAttrs(r), outputs),
             joinPlan)
 
-          InsertOnlyMerge(r, mergeRows)
+          val query = dataNotMatchedActions match {
+            case Seq(insertAction: InsertAction) =>
+              tryBuildInsertOnlyMergeProject(r, source, cond, 
insertAction).getOrElse(mergeRows)

Review Comment:
   **[18] When only a value fails to fold, the condition is no longer pushed 
down.**
   
   `tryBuildInsertOnlyMergeProject` returns `None` for any failure, also when 
the condition is clean, so the condition then stays in the `Keep` instruction 
above `Join(source, r, LeftAnti)`. For example, with ANSI on and a date column 
`dt` in the source:
   
   ```sql
   WHEN NOT MATCHED AND s.dt = '2026-11-19' THEN
     INSERT (pk, salary, dep) VALUES (s.pk, 1 DIV 0, s.dep)
   ```
   
   the source is scanned without the `dt` filter or partition pruning, and 
every source row goes through the anti join. master fails this statement, so it 
is not a regression, but it is one of the cases this PR makes work. A condition 
that passes the check is as safe to push as on the `Project` path, so 
`MergeRows` could keep only the values, as in `Keep(Insert, TrueLiteral, 
values)` over `Join(Filter(cond, source), r, LeftAnti)`. This is the shape [5] 
suggested for another reason.



##########
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:
   **[19] The check evaluates every constant of the action once more and drops 
the result.**
   
   `ConstantFolding.constantFolding` evaluates each foldable subexpression of 
the cloned action here, and the optimizer folds the same expressions again 
later, so an expensive constant costs twice on the driver. For example, `VALUES 
(s.pk, size(sequence(1, 50000000)), s.dep)` builds the 50-million-element array 
once here and once in `ConstantFolding`; a large `repeat` or `array_repeat` 
constant is the same. For an action without current-time functions or special 
datetime strings, the folded copy could replace the original in the `Project`, 
so that each constant is evaluated once.



##########
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:
   **[22] Nit: the expected fallback logs a stack trace at INFO.**
   
   Every single-clause MERGE with a constant that fails to fold, which is the 
case this PR handles, writes the stack trace of `DIVIDE_BY_ZERO` or a similar 
error into the driver log at the default INFO level, although the statement 
succeeds. Logging only the message, or the stack trace at DEBUG, would avoid 
output that looks like a failure.



##########
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:
   **[20] The non-boolean test does not cover the clauses whose error changes.**
   
   Both cases here are a single NOT MATCHED clause. The `s.salary` case already 
failed with `DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN` on master, through the 
source `Filter`, and it passes without the new check in 
`checkMergeIntoCondition`, since the `Project` path still builds that `Filter`. 
The user-visible change is in the row-level paths: `WHEN MATCHED AND s.salary 
THEN DELETE WHEN NOT MATCHED THEN INSERT *` fails on master during execution 
with a Janino `CompileException` ("Not a boolean expression"), and with this PR 
during analysis with `FILTER_NOT_BOOLEAN`. Could the grid also include a 
MATCHED and a NOT MATCHED BY SOURCE condition, the clauses that [7] described 
as already going through `MergeRows`?



##########
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:
   **[21] No test depends on the `ComputeCurrentTime` step.**
   
   `CurrentDate` is foldable and has an `eval`, so the comparison at L55 folds 
the same way without `ComputeCurrentTime`; `SpecialDatetimeValues` is the step 
that this case needs. Reading the code, every new test still passes when 
`ComputeCurrentTime.applyForExpression` is dropped, and no SQL test uses a 
current-time function. A case that fails to fold only after the time is fixed 
would cover the step; if there is no such case, the step could be dropped.



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