dongjoon-hyun commented on code in PR #60559:
URL: https://github.com/apache/spark/pull/60559#discussion_r4661012610
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -174,6 +147,87 @@ object RewriteMergeIntoTable extends
RewriteRowLevelCommand with PredicateHelper
case _ => false
}
+ /**
+ * Uses Project for values that fold safely and MergeRows for values needing
conditional
+ * evaluation. Conditions are checked separately so safe source filters can
still be pushed down.
+ * Later optimizer rules may introduce failing constants that this check
cannot see.
+ */
+ private def buildInsertOnlyMergeQuery(
+ relation: DataSourceV2Relation,
+ joinPlan: Join,
+ insertAction: InsertAction,
+ mergeRows: MergeRows): LogicalPlan = {
+ val condition = insertAction.condition.getOrElse(TrueLiteral)
+ val output = insertAction.assignments.map(_.value)
+ // Subqueries and window values need Project's analysis rules. Preserve
their existing plan.
+ val supportsMergeRows = !output.exists { expr =>
+ SubqueryExpression.hasSubquery(expr) ||
expr.containsPattern(WINDOW_EXPRESSION)
+ }
+ val foldedCondition = if (supportsMergeRows) {
+ tryFoldMergeExpression(condition, isCondition = true)
+ } else {
+ Some(condition)
+ }
+ val foldedOutput = if (supportsMergeRows) {
+ output.map(tryFoldMergeExpression(_, isCondition = false))
+ } else {
+ output.map(Some(_))
+ }
+
+ val filteredSource = foldedCondition match {
+ // Filter requires BOOLEAN; MergeRows also accepts an untyped NULL
condition.
+ case Some(cond) if insertAction.condition.isDefined && cond.dataType ==
NullType =>
+ Filter(Cast(cond, BooleanType), joinPlan.left)
+ case Some(cond) if insertAction.condition.isDefined => Filter(cond,
joinPlan.left)
+ case _ => joinPlan.left
+ }
+ val filteredJoin = joinPlan.copy(left = filteredSource)
+ val values = foldedOutput.zip(output).map { case (folded, original) =>
+ folded.getOrElse(original)
+ }
+
+ if (foldedCondition.isDefined && foldedOutput.forall(_.isDefined)) {
+ val projectList = values.zip(relation.output).map { case (expr, attr) =>
+ Alias(expr, attr.name)()
+ }
+ Project(projectList, filteredJoin)
+ } else {
+ // A condition with a deferred failure must be evaluated only for
unmatched source rows.
+ val instructionCondition = if (foldedCondition.isDefined) TrueLiteral
else condition
+ mergeRows.copy(
+ notMatchedInstructions = Seq(Keep(Insert, instructionCondition,
values)),
+ child = filteredJoin)
+ }
+ }
+
+ private def tryFoldMergeExpression(
+ expr: Expression,
+ isCondition: Boolean): Option[Expression] = {
+ try {
+ val replaced = ReplaceExpressions.replace(expr.clone())
+ val withCurrentTime = ComputeCurrentTime.applyForExpression(replaced)
+ // Catalog/user functions need ReplaceCurrentLike, which requires the
session catalog.
+ if (withCurrentTime.containsPattern(CURRENT_LIKE)) return None
+ val rewritten = SpecialDatetimeValues.applyForExpression(withCurrentTime)
+ val failed = Collections.newSetFromMap(new IdentityHashMap[Expression,
java.lang.Boolean]())
+ val folded = ConstantFolding.constantFolding(rewritten, failed = failed)
+ if (isCondition && (!failed.isEmpty ||
+ folded.exists(_.containsTag(ConstantFolding.FAILED_TO_EVALUATE)))) {
+ None
+ } else if (rewritten.fastEquals(replaced)) {
+ // Reuse successful folds, but leave query-time values for the
optimizer's shared snapshot.
+ Some(folded)
Review Comment:
**[24] Reusing the folded copy puts `ReplaceExpressions` output into the
analyzed plan.**
This comes from my suggestion in [19], which missed that the folded copy has
also gone through `ReplaceExpressions`. Every `RuntimeReplaceable` in the value
or the condition is replaced in `folded`, including the parts that do not fold,
so the analyzed plan now holds what only the optimizer used to produce.
`checkRestrictedMode` relies on the opposite (`CheckAnalysis.scala:382`: "A
try_reflect call stays a RuntimeReplaceable wrapper until optimization"), so
with restricted mode on,
```sql
MERGE INTO t USING s ON t.pk = s.pk
WHEN NOT MATCHED THEN
INSERT (pk, id, dep) VALUES (s.pk, try_reflect('java.util.UUID',
'randomUUID'), s.dep)
```
is reported as using the `reflect` function rather than `try_reflect`.
`EXPLAIN EXTENDED` also shows `nullif` and `between` as `With` expressions and
`nvl` as `coalesce` in the analyzed plan. Reusing `folded` only when it is a
`Literal`, and `expr` otherwise, would keep the gain of [19] for a value that
is a constant, as in its `size(sequence(1, 50000000))` example and the
`CountingConstant` test. The expected conditions in the test at
`RewriteMergeIntoTableSuite.scala:61` would then be the original ones, which
the optimizer folds as on master.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -174,6 +147,87 @@ object RewriteMergeIntoTable extends
RewriteRowLevelCommand with PredicateHelper
case _ => false
}
+ /**
+ * Uses Project for values that fold safely and MergeRows for values needing
conditional
+ * evaluation. Conditions are checked separately so safe source filters can
still be pushed down.
+ * Later optimizer rules may introduce failing constants that this check
cannot see.
+ */
+ private def buildInsertOnlyMergeQuery(
+ relation: DataSourceV2Relation,
+ joinPlan: Join,
+ insertAction: InsertAction,
+ mergeRows: MergeRows): LogicalPlan = {
+ val condition = insertAction.condition.getOrElse(TrueLiteral)
+ val output = insertAction.assignments.map(_.value)
+ // Subqueries and window values need Project's analysis rules. Preserve
their existing plan.
+ val supportsMergeRows = !output.exists { expr =>
+ SubqueryExpression.hasSubquery(expr) ||
expr.containsPattern(WINDOW_EXPRESSION)
+ }
+ val foldedCondition = if (supportsMergeRows) {
+ tryFoldMergeExpression(condition, isCondition = true)
+ } else {
+ Some(condition)
+ }
+ val foldedOutput = if (supportsMergeRows) {
+ output.map(tryFoldMergeExpression(_, isCondition = false))
+ } else {
+ output.map(Some(_))
+ }
+
+ val filteredSource = foldedCondition match {
+ // Filter requires BOOLEAN; MergeRows also accepts an untyped NULL
condition.
+ case Some(cond) if insertAction.condition.isDefined && cond.dataType ==
NullType =>
+ Filter(Cast(cond, BooleanType), joinPlan.left)
+ case Some(cond) if insertAction.condition.isDefined => Filter(cond,
joinPlan.left)
+ case _ => joinPlan.left
+ }
+ val filteredJoin = joinPlan.copy(left = filteredSource)
+ val values = foldedOutput.zip(output).map { case (folded, original) =>
+ folded.getOrElse(original)
+ }
+
+ if (foldedCondition.isDefined && foldedOutput.forall(_.isDefined)) {
+ val projectList = values.zip(relation.output).map { case (expr, attr) =>
+ Alias(expr, attr.name)()
+ }
+ Project(projectList, filteredJoin)
+ } else {
+ // A condition with a deferred failure must be evaluated only for
unmatched source rows.
+ val instructionCondition = if (foldedCondition.isDefined) TrueLiteral
else condition
+ mergeRows.copy(
+ notMatchedInstructions = Seq(Keep(Insert, instructionCondition,
values)),
+ child = filteredJoin)
+ }
+ }
+
+ private def tryFoldMergeExpression(
+ expr: Expression,
+ isCondition: Boolean): Option[Expression] = {
+ try {
+ val replaced = ReplaceExpressions.replace(expr.clone())
+ val withCurrentTime = ComputeCurrentTime.applyForExpression(replaced)
+ // Catalog/user functions need ReplaceCurrentLike, which requires the
session catalog.
+ if (withCurrentTime.containsPattern(CURRENT_LIKE)) return None
Review Comment:
**[23] A condition with a catalog or user function is no longer pushed
down.**
The fallback that I offered in [17], keeping `MergeRows` for an action that
still has the `CURRENT_LIKE` pattern, also applies to the condition, where it
costs more than it saves. Any condition with `current_user()`,
`current_database()`, `current_catalog()` or `current_path()` returns `None`
here, also when nothing around the function can fold. So this single-clause
MERGE, which holds no failing constant, changes its plan:
```sql
MERGE INTO t USING s ON t.pk = s.pk
WHEN NOT MATCHED AND s.owner = current_user() THEN
INSERT (pk, v) VALUES (s.pk, py_udf(s.x))
```
master filters the source below the anti join, so the filter can reach the
source scan and its partition pruning, and `py_udf` runs only for the unmatched
rows of the current user. With this PR the condition stays in the `Keep`
instruction (L196) and runs in `MergeRowsExec` after the full anti join.
`ExtractPythonUDFs` evaluates the Python and external UDFs of `MergeRows` below
it, for every row of its child (see the comment at `Optimizer.scala:1175`), so
`py_udf` now also runs for the rows of other owners, and a UDF that raises on
those rows fails a MERGE that master completes.
What can fail once `ReplaceCurrentLike` has run is an expression whose other
inputs are all constants, such as `CAST(current_database() AS BIGINT)` in [17]
and in the new tests. Could the check keep `MergeRows` only when a
`CURRENT_LIKE` node is under such an expression, and handle `s.owner =
current_user()`, which cannot fold, as on master? The tests for [17] would
still take `MergeRows`, and a value that is only `current_user()`, such as an
audit column, would keep the `Project` too.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -174,6 +147,87 @@ object RewriteMergeIntoTable extends
RewriteRowLevelCommand with PredicateHelper
case _ => false
}
+ /**
+ * Uses Project for values that fold safely and MergeRows for values needing
conditional
+ * evaluation. Conditions are checked separately so safe source filters can
still be pushed down.
+ * Later optimizer rules may introduce failing constants that this check
cannot see.
+ */
+ private def buildInsertOnlyMergeQuery(
+ relation: DataSourceV2Relation,
+ joinPlan: Join,
+ insertAction: InsertAction,
+ mergeRows: MergeRows): LogicalPlan = {
+ val condition = insertAction.condition.getOrElse(TrueLiteral)
+ val output = insertAction.assignments.map(_.value)
+ // Subqueries and window values need Project's analysis rules. Preserve
their existing plan.
+ val supportsMergeRows = !output.exists { expr =>
+ SubqueryExpression.hasSubquery(expr) ||
expr.containsPattern(WINDOW_EXPRESSION)
+ }
+ val foldedCondition = if (supportsMergeRows) {
+ tryFoldMergeExpression(condition, isCondition = true)
+ } else {
+ Some(condition)
+ }
+ val foldedOutput = if (supportsMergeRows) {
+ output.map(tryFoldMergeExpression(_, isCondition = false))
+ } else {
+ output.map(Some(_))
+ }
+
+ val filteredSource = foldedCondition match {
+ // Filter requires BOOLEAN; MergeRows also accepts an untyped NULL
condition.
+ case Some(cond) if insertAction.condition.isDefined && cond.dataType ==
NullType =>
+ Filter(Cast(cond, BooleanType), joinPlan.left)
+ case Some(cond) if insertAction.condition.isDefined => Filter(cond,
joinPlan.left)
+ case _ => joinPlan.left
+ }
+ val filteredJoin = joinPlan.copy(left = filteredSource)
+ val values = foldedOutput.zip(output).map { case (folded, original) =>
+ folded.getOrElse(original)
+ }
+
+ if (foldedCondition.isDefined && foldedOutput.forall(_.isDefined)) {
+ val projectList = values.zip(relation.output).map { case (expr, attr) =>
+ Alias(expr, attr.name)()
+ }
+ Project(projectList, filteredJoin)
+ } else {
+ // A condition with a deferred failure must be evaluated only for
unmatched source rows.
+ val instructionCondition = if (foldedCondition.isDefined) TrueLiteral
else condition
+ mergeRows.copy(
+ notMatchedInstructions = Seq(Keep(Insert, instructionCondition,
values)),
+ child = filteredJoin)
+ }
+ }
+
+ private def tryFoldMergeExpression(
+ expr: Expression,
+ isCondition: Boolean): Option[Expression] = {
+ try {
+ val replaced = ReplaceExpressions.replace(expr.clone())
+ val withCurrentTime = ComputeCurrentTime.applyForExpression(replaced)
+ // Catalog/user functions need ReplaceCurrentLike, which requires the
session catalog.
+ if (withCurrentTime.containsPattern(CURRENT_LIKE)) return None
+ val rewritten = SpecialDatetimeValues.applyForExpression(withCurrentTime)
+ val failed = Collections.newSetFromMap(new IdentityHashMap[Expression,
java.lang.Boolean]())
+ val folded = ConstantFolding.constantFolding(rewritten, failed = failed)
Review Comment:
**[25] The reused folds ignore `spark.sql.optimizer.excludedRules`.**
Also from [19]: with `ConstantFolding` in
`spark.sql.optimizer.excludedRules`, the optimizer leaves constants unfolded,
but this check still folds them and the plan now gets the results; for example,
`VALUES (s.pk, 1 + 1, s.dep)` plans `2`. Tests and debugging use that setting
to run an expression unfolded. `ConstantPropagation.simplify` checks it and
does not fold when `ConstantFolding` is excluded (`expressions.scala:542`).
Skipping the check in that case, and keeping the `Project` with the original
expressions, would follow the setting.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala:
##########
@@ -1913,6 +1914,342 @@ 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 {
Review Comment:
**[26] This test does not set ANSI mode.**
It is the only new test with `1 DIV 0` that does not use
`withSQLConf(SQLConf.ANSI_ENABLED.key -> "true")`. In the non-ANSI job
(`build_non_ansi.yml` sets `SPARK_ANSI_SQL_MODE` to `false`), `1 DIV 0` is
NULL, so the `conditional` and `failingCondition` cases, which the reply to
[16] added, have no failure to defer and pass either way.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -594,5 +648,9 @@ object RewriteMergeIntoTable extends RewriteRowLevelCommand
with PredicateHelper
if (cond.exists(_.isInstanceOf[AggregateExpression])) {
throw
QueryCompilationErrors.aggregationNotAllowedInMergeCondition(condName, cond)
}
+
+ if (condName != "SEARCH" && cond.dataType != BooleanType && cond.dataType
!= NullType) {
Review Comment:
**[28] The check matches the "SEARCH" label to skip the ON condition.**
My suggestion in [7] put this check into `checkMergeIntoCondition`, but that
also checks the ON condition (L629), so it needs `condName != "SEARCH"` to keep
master's `JOIN_CONDITION_IS_NOT_BOOLEAN_TYPE` for ON, as the reply to [7]
explains. Otherwise `condName` is only a label for error messages. Checking the
action conditions in `validateMergeIntoConditions` instead, e.g. over
`actions.flatMap(_.condition)` next to L631-635, would not depend on the label.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTableSuite.scala:
##########
@@ -0,0 +1,162 @@
+/*
+ * 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 java.util.concurrent.atomic.AtomicInteger
+
+import org.apache.spark.sql.catalyst.InternalRow
+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.expressions.codegen.CodegenFallback
+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, DataType, DateType,
DoubleType, LongType, StructType}
+
+class RewriteMergeIntoTableSuite extends PlanTest {
+ import RewriteMergeIntoTableSuite.CountingConstant
+
+ 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)))
+ }
+
+ private val currentDateCondition =
+ CurrentDate(Some("UTC")) === Cast(Literal("today"), DateType, Some("UTC"))
+ private val currentTimezoneCondition = key > Cast(Length(CurrentTimeZone()),
LongType)
+
+ gridTest("preserve the projection when prepared constants fold")(Seq(
+ (key > Cast(Literal("5"), LongType), key > Literal(5L)),
+ (Cast(key, DoubleType) > new TryDivide(Literal(10.0), Literal(2.0)),
+ Cast(key, DoubleType) > Literal(5.0)),
+ (currentDateCondition, currentDateCondition),
+ (currentTimezoneCondition, currentTimezoneCondition)
+ )) { case (condition, expected) =>
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ val result = rewrite(Seq(insert(condition)))
+ val project = result.query.asInstanceOf[Project]
+ val join = project.child.asInstanceOf[Join]
+ assert(join.joinType == LeftAnti)
+ comparePlans(join.left, Filter(expected, source))
+ assert(project.projectList.head.asInstanceOf[Alias].child == key)
+ }
+ }
+
+ gridTest("keep failed folds in MergeRows")(Seq("condition", "value", "if
input", "if branch")) {
+ position =>
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ val bad = IntegralDivide(Literal(1L), Literal(0L))
+ val action = position match {
+ case "condition" => insert(bad === 1L)
+ case "value" => insert(TrueLiteral, bad)
+ case "if input" => insert(If(bad === 1L, key > 0L, key < 0L))
+ case "if branch" => insert(If(key > 0L, bad === 1L, FalseLiteral))
+ }
+ val result = rewrite(Seq(action))
+ assert(result.query.isInstanceOf[MergeRows])
+ assert(!action.exists(_.containsTag(ConstantFolding.FAILED_TO_EVALUATE)))
+ }
+ }
+
+ test("multiple insert actions keep MergeRows") {
+ val result = rewrite(Seq(insert(key < 0L, Literal(0L)),
insert(TrueLiteral)))
+ assert(result.query.isInstanceOf[MergeRows])
+ }
+
+ test("a conditional insert value keeps its own failed folds protected") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ val value = If(key > 0L, key, IntegralDivide(Literal(1L), Literal(0L)))
+ val result = rewrite(Seq(insert(TrueLiteral, value)))
+ val project = result.query.asInstanceOf[Project]
+ assert(project.projectList.head.asInstanceOf[Alias].child == value)
+ }
+ }
+
+ gridTest("preserve false and null insert conditions")(
+ Seq(FalseLiteral, Literal.create(null, BooleanType), Literal(null))
+ .map(c => (c, c.dataType))) { case (condition, _) =>
Review Comment:
**[27] The test names depend on expression IDs and an unused parameter.**
`gridTest` names each test after the parameter's `toString`. Here the data
type is in the tuple only to tell apart the two `null` literals, whose names
would otherwise be the same, and the grid at L61 puts `sourceId#<id>L` into its
names, with an ID from a JVM-wide counter, so those names change with the
suites that ran before in the same JVM. `namedGridTest`
(`SparkFunSuite.scala:97`) with short names, e.g. `"false"`, `"boolean null"`
and `"void null"`, would avoid both.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -174,6 +147,87 @@ object RewriteMergeIntoTable extends
RewriteRowLevelCommand with PredicateHelper
case _ => false
}
+ /**
+ * Uses Project for values that fold safely and MergeRows for values needing
conditional
+ * evaluation. Conditions are checked separately so safe source filters can
still be pushed down.
+ * Later optimizer rules may introduce failing constants that this check
cannot see.
+ */
+ private def buildInsertOnlyMergeQuery(
+ relation: DataSourceV2Relation,
+ joinPlan: Join,
+ insertAction: InsertAction,
+ mergeRows: MergeRows): LogicalPlan = {
+ val condition = insertAction.condition.getOrElse(TrueLiteral)
+ val output = insertAction.assignments.map(_.value)
+ // Subqueries and window values need Project's analysis rules. Preserve
their existing plan.
+ val supportsMergeRows = !output.exists { expr =>
+ SubqueryExpression.hasSubquery(expr) ||
expr.containsPattern(WINDOW_EXPRESSION)
+ }
+ val foldedCondition = if (supportsMergeRows) {
Review Comment:
**[29] `MergeRows` is built for every single clause, then dropped or
rebuilt.**
`mergeRows`, including its `generateExpandOutput`, is built before this
method is called, and here it is either dropped on the `Project` path or
rebuilt with new instructions and a new child through `copy` (L197-199).
L166-175 also test `supportsMergeRows` twice. Returning the `Project` and
`Filter` right away when `supportsMergeRows` is false, and building `MergeRows`
only in the fallback, would avoid both.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteMergeIntoTable.scala:
##########
@@ -174,6 +147,87 @@ object RewriteMergeIntoTable extends
RewriteRowLevelCommand with PredicateHelper
case _ => false
}
+ /**
+ * Uses Project for values that fold safely and MergeRows for values needing
conditional
+ * evaluation. Conditions are checked separately so safe source filters can
still be pushed down.
+ * Later optimizer rules may introduce failing constants that this check
cannot see.
+ */
+ private def buildInsertOnlyMergeQuery(
+ relation: DataSourceV2Relation,
+ joinPlan: Join,
+ insertAction: InsertAction,
+ mergeRows: MergeRows): LogicalPlan = {
+ val condition = insertAction.condition.getOrElse(TrueLiteral)
+ val output = insertAction.assignments.map(_.value)
+ // Subqueries and window values need Project's analysis rules. Preserve
their existing plan.
+ val supportsMergeRows = !output.exists { expr =>
+ SubqueryExpression.hasSubquery(expr) ||
expr.containsPattern(WINDOW_EXPRESSION)
+ }
+ val foldedCondition = if (supportsMergeRows) {
+ tryFoldMergeExpression(condition, isCondition = true)
+ } else {
+ Some(condition)
+ }
+ val foldedOutput = if (supportsMergeRows) {
+ output.map(tryFoldMergeExpression(_, isCondition = false))
+ } else {
+ output.map(Some(_))
+ }
+
+ val filteredSource = foldedCondition match {
+ // Filter requires BOOLEAN; MergeRows also accepts an untyped NULL
condition.
+ case Some(cond) if insertAction.condition.isDefined && cond.dataType ==
NullType =>
+ Filter(Cast(cond, BooleanType), joinPlan.left)
+ case Some(cond) if insertAction.condition.isDefined => Filter(cond,
joinPlan.left)
+ case _ => joinPlan.left
+ }
+ val filteredJoin = joinPlan.copy(left = filteredSource)
+ val values = foldedOutput.zip(output).map { case (folded, original) =>
+ folded.getOrElse(original)
+ }
+
+ if (foldedCondition.isDefined && foldedOutput.forall(_.isDefined)) {
+ val projectList = values.zip(relation.output).map { case (expr, attr) =>
+ Alias(expr, attr.name)()
+ }
+ Project(projectList, filteredJoin)
+ } else {
+ // A condition with a deferred failure must be evaluated only for
unmatched source rows.
+ val instructionCondition = if (foldedCondition.isDefined) TrueLiteral
else condition
+ mergeRows.copy(
+ notMatchedInstructions = Seq(Keep(Insert, instructionCondition,
values)),
+ child = filteredJoin)
+ }
+ }
+
+ private def tryFoldMergeExpression(
+ expr: Expression,
+ isCondition: Boolean): Option[Expression] = {
+ try {
+ val replaced = ReplaceExpressions.replace(expr.clone())
Review Comment:
**[30] Nit: the `clone()` seems unneeded.**
With the `failed` set, `tryFold` records a failure in the set instead of
tagging the tree (`expressions.scala:85`). `ReplaceExpressions`,
`ComputeCurrentTime` and `SpecialDatetimeValues` return new nodes for what they
change, and `tryFold` already evaluates a fresh copy of a stateful expression.
So, reading the code, nothing here changes `expr`, and the clone copies every
value and the condition of the action once more.
--
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]