szehon-ho commented on code in PR #60559:
URL: https://github.com/apache/spark/pull/60559#discussion_r4629317525
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala:
##########
@@ -1893,6 +1894,182 @@ abstract class MergeIntoTableSuiteBase extends
RowLevelOperationSuiteBase
}
}
+ test("MERGE defers constant-folding failures in unselected actions") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withTempView("source") {
+ 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 = 1 DIV 0
+ |WHEN MATCHED THEN UPDATE SET salary = s.salary
+ |WHEN NOT MATCHED THEN
+ | INSERT (pk, salary, dep) VALUES (s.pk, 1 DIV 0, s.dep)
+ |WHEN NOT MATCHED BY SOURCE 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"))
+ }
+ }
+ }
+
+ test("MERGE defers constant-folding failures in later clause conditions") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withTempView("source") {
+ createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+ """{ "pk": 1, "salary": 100, "dep": "hr" }""")
+ Seq((1, 10, "hr")).toDF("pk", "salary",
"dep").createOrReplaceTempView("source")
+
+ sql(
+ s"""MERGE INTO $tableNameAsString t
+ |USING source s
+ |ON t.pk = s.pk
+ |WHEN MATCHED AND t.salary > 0 THEN UPDATE SET salary = s.salary
+ |WHEN MATCHED AND 1 DIV 0 = 1 THEN DELETE
+ |WHEN NOT MATCHED AND 1 DIV 0 = 1 THEN
+ | INSERT (pk, salary, dep) VALUES (s.pk, s.salary, s.dep)
+ |WHEN NOT MATCHED BY SOURCE AND 1 DIV 0 = 1 THEN DELETE
+ |""".stripMargin)
+ checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, 10, "hr"))
+ }
+ }
+ }
+
+ gridTest("insert-only MERGE defers constant-folding failures")(for {
Review Comment:
Combined the skipped-action and later-condition cases into one MERGE and
removed the redundant two-clause grid. The old optimizer suite is gone; its
replacement tests the distinct analysis-rewrite decisions.
---
<!-- 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/expressions.scala:
##########
@@ -92,6 +92,9 @@ object ConstantFolding extends Rule[LogicalPlan] {
case c: ConditionalExpression if !c.foldable =>
c.mapChildren(constantFolding(_, isConditionalBranch = true))
+ case i: MergeRows.Instruction =>
+ i.mapChildren(constantFolding(_, isConditionalBranch = true))
Review Comment:
Added the instruction-list evaluation comment and updated the failed-fold
tag and exception comments to include expressions that may be skipped by MERGE.
---
<!-- 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,182 @@ abstract class MergeIntoTableSuiteBase extends
RowLevelOperationSuiteBase
}
}
+ test("MERGE defers constant-folding failures in unselected actions") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ withTempView("source") {
+ createAndInitTable("pk INT NOT NULL, salary BIGINT, dep STRING",
Review Comment:
Added a comment explaining that BIGINT keeps DIVIDE_BY_ZERO from being
wrapped in an assignment-cast overflow error.
---
<!-- 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,
+ Seq(instruction @ Keep(Insert, condition, values)), Nil, false, _,
child), _, _)
+ if !hasUnfoldedConstants(instruction) =>
+ val filtered = condition match {
+ case TrueLiteral => child
+ case _ => filterSource(child, condition).getOrElse(Filter(condition,
child))
+ }
+ val projectList = values.zip(rows.output).map { case (value, attr) =>
+ Alias(value, attr.name)(exprId = attr.exprId, qualifier =
attr.qualifier,
+ explicitMetadata = Some(attr.metadata))
+ }
+ merge.copy(query = Project(projectList, filtered))
+ }
+
+ private def hasUnfoldedConstants(expr: Expression): Boolean = expr match {
+ case _: Literal => false
+ // These failures stay protected by the expression after MergeRows is
removed.
+ case c: ConditionalExpression if !c.foldable => false
+ case e => e.foldable || e.children.exists(hasUnfoldedConstants)
+ }
+
+ private def filterSource(plan: LogicalPlan, condition: Expression):
Option[LogicalPlan] = {
+ plan match {
+ case join @ Join(_, _, LeftAnti, _, _) =>
+ Some(join.copy(left = Filter(condition, join.left)))
+ // Column pruning may put a projection between MergeRows and the anti
join.
Review Comment:
The optimizer comment was removed with OptimizeInsertOnlyMerge. The
AcceptAnySchema comment applies again: a safe single INSERT becomes a Project
during analysis, while multiple INSERT actions use 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]