From 051e4dc9781f8a79525cb3c3c4e13a3e8f3578db Mon Sep 17 00:00:00 2001 From: eye-gu Date: Mon, 23 Nov 2026 21:41:28 +0800 Subject: [PATCH] [spark] Prune join columns for primary key MERGE INTO --- .../spark/commands/MergeIntoPaimonTable.scala | 70 +++++- .../spark/commands/MergeIntoPaimonTable.scala | 70 +++++- ...MergeIntoPaimonTablePruneColumnsTest.scala | 140 ++++++++++++ .../spark/sql/MergeIntoTableTestBase.scala | 200 +++++++++++++++++- 4 files changed, 468 insertions(+), 12 deletions(-) create mode 100644 paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTablePruneColumnsTest.scala diff --git a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala index d51504059df9..12835d4f3e90 100644 --- a/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala +++ b/paimon-spark/paimon-spark-4.0/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala @@ -102,7 +102,8 @@ case class MergeIntoPaimonTable( constructChangedRows( sparkSession, createDataset(sparkSession, filteredTargetPlan), - remainDeletedRow = true)) + remainDeletedRow = true, + pruneJoinColumns = true)) } private def performMergeForNonPkTable(sparkSession: SparkSession): Seq[CommitMessage] = { @@ -239,12 +240,26 @@ case class MergeIntoPaimonTable( remainDeletedRow: Boolean = false, deletionVectorEnabled: Boolean = false, extraMetadataCols: Seq[PaimonMetadataColumn] = Seq.empty, - writeRowTracking: Boolean = false): Dataset[Row] = { + writeRowTracking: Boolean = false, + pruneJoinColumns: Boolean = false): Dataset[Row] = { val targetPlan = targetDataset.queryExecution.analyzed + val (targetJoinOutput, sourceJoinOutput) = + if (pruneJoinColumns) { + pruneJoinColumnsForMerge( + mergeCondition, + matchedActions, + notMatchedActions, + notMatchedBySourceActions, + targetPlan.output, + sourceTable.output, + remainDeletedRow || deletionVectorEnabled) + } else { + (targetPlan.output, sourceTable.output) + } val targetProject = - Project(targetPlan.output :+ Alias(Literal(true), TARGET_ROW_COL)(), targetPlan) + Project(targetJoinOutput :+ Alias(Literal(true), TARGET_ROW_COL)(), targetPlan) val sourceProject = - Project(sourceTable.output :+ Alias(Literal(true), SOURCE_ROW_COL)(), sourceTable) + Project(sourceJoinOutput :+ Alias(Literal(true), SOURCE_ROW_COL)(), sourceTable) val joinNode = Join(sourceProject, targetProject, FullOuter, Some(mergeCondition), JoinHint.NONE) val joinedDS = createDataset(sparkSession, joinNode) @@ -270,8 +285,15 @@ case class MergeIntoPaimonTable( (null, null) } - val targetOutput = if (writeRowTracking) { + val targetOutput: Seq[Expression] = if (writeRowTracking) { filteredTargetPlan.output ++ Seq(rowIdAttr, sequenceNumberAttr) + } else if (pruneJoinColumns) { + // Templates span the full output schema; NULL-filled slots belong only to rows the processor + // drops, or to DELETE rows, which force unpruned columns. + val keptExprIds = targetJoinOutput.map(_.exprId).toSet + targetPlan.output.map { + attr => if (keptExprIds.contains(attr.exprId)) attr else Literal(null, attr.dataType) + } } else { filteredTargetPlan.output } @@ -368,6 +390,44 @@ object MergeIntoPaimonTable { private val ROW_KIND_COL: String = SparkSystemColumns.ROW_KIND_COL private val NOOP_ROW_KIND_VALUE: Byte = "-1".toByte + /** + * Computes the target/source columns that must survive the merge join: the references of the + * merge condition plus every action's condition and assignment values, in the original output + * order. A DELETE clause materializes `-D` records carrying the full target row (its value is + * consumed by the merge engines), so with deleted rows the target side is not pruned. + */ + private[commands] def pruneJoinColumnsForMerge( + mergeCondition: Expression, + matchedActions: Seq[MergeAction], + notMatchedActions: Seq[MergeAction], + notMatchedBySourceActions: Seq[MergeAction], + targetOutput: Seq[Attribute], + sourceOutput: Seq[Attribute], + remainDeletedRow: Boolean): (Seq[Attribute], Seq[Attribute]) = { + val actionExpressions = + (matchedActions ++ notMatchedActions ++ notMatchedBySourceActions).flatMap { + case PaimonUpdateAction(condition, assignments) => + condition.toSeq ++ assignments.map(_.value) + case InsertAction(condition, assignments) => + condition.toSeq ++ assignments.map(_.value) + case DeleteAction(condition) => condition.toSeq + case _ => Seq.empty[Expression] + } + val referencedExprIds = + (mergeCondition +: actionExpressions).flatMap(_.references).map(_.exprId).toSet + val keepFullTargetRows = + remainDeletedRow && + (matchedActions ++ notMatchedBySourceActions).exists(_.isInstanceOf[DeleteAction]) + val neededTarget = + if (keepFullTargetRows) { + targetOutput + } else { + targetOutput.filter(attr => referencedExprIds.contains(attr.exprId)) + } + val neededSource = sourceOutput.filter(attr => referencedExprIds.contains(attr.exprId)) + (neededTarget, neededSource) + } + private case class MergeIntoProcessor( joinedAttributes: Seq[Attribute], targetRowHasNoMatch: Expression, diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala index d51504059df9..12835d4f3e90 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTable.scala @@ -102,7 +102,8 @@ case class MergeIntoPaimonTable( constructChangedRows( sparkSession, createDataset(sparkSession, filteredTargetPlan), - remainDeletedRow = true)) + remainDeletedRow = true, + pruneJoinColumns = true)) } private def performMergeForNonPkTable(sparkSession: SparkSession): Seq[CommitMessage] = { @@ -239,12 +240,26 @@ case class MergeIntoPaimonTable( remainDeletedRow: Boolean = false, deletionVectorEnabled: Boolean = false, extraMetadataCols: Seq[PaimonMetadataColumn] = Seq.empty, - writeRowTracking: Boolean = false): Dataset[Row] = { + writeRowTracking: Boolean = false, + pruneJoinColumns: Boolean = false): Dataset[Row] = { val targetPlan = targetDataset.queryExecution.analyzed + val (targetJoinOutput, sourceJoinOutput) = + if (pruneJoinColumns) { + pruneJoinColumnsForMerge( + mergeCondition, + matchedActions, + notMatchedActions, + notMatchedBySourceActions, + targetPlan.output, + sourceTable.output, + remainDeletedRow || deletionVectorEnabled) + } else { + (targetPlan.output, sourceTable.output) + } val targetProject = - Project(targetPlan.output :+ Alias(Literal(true), TARGET_ROW_COL)(), targetPlan) + Project(targetJoinOutput :+ Alias(Literal(true), TARGET_ROW_COL)(), targetPlan) val sourceProject = - Project(sourceTable.output :+ Alias(Literal(true), SOURCE_ROW_COL)(), sourceTable) + Project(sourceJoinOutput :+ Alias(Literal(true), SOURCE_ROW_COL)(), sourceTable) val joinNode = Join(sourceProject, targetProject, FullOuter, Some(mergeCondition), JoinHint.NONE) val joinedDS = createDataset(sparkSession, joinNode) @@ -270,8 +285,15 @@ case class MergeIntoPaimonTable( (null, null) } - val targetOutput = if (writeRowTracking) { + val targetOutput: Seq[Expression] = if (writeRowTracking) { filteredTargetPlan.output ++ Seq(rowIdAttr, sequenceNumberAttr) + } else if (pruneJoinColumns) { + // Templates span the full output schema; NULL-filled slots belong only to rows the processor + // drops, or to DELETE rows, which force unpruned columns. + val keptExprIds = targetJoinOutput.map(_.exprId).toSet + targetPlan.output.map { + attr => if (keptExprIds.contains(attr.exprId)) attr else Literal(null, attr.dataType) + } } else { filteredTargetPlan.output } @@ -368,6 +390,44 @@ object MergeIntoPaimonTable { private val ROW_KIND_COL: String = SparkSystemColumns.ROW_KIND_COL private val NOOP_ROW_KIND_VALUE: Byte = "-1".toByte + /** + * Computes the target/source columns that must survive the merge join: the references of the + * merge condition plus every action's condition and assignment values, in the original output + * order. A DELETE clause materializes `-D` records carrying the full target row (its value is + * consumed by the merge engines), so with deleted rows the target side is not pruned. + */ + private[commands] def pruneJoinColumnsForMerge( + mergeCondition: Expression, + matchedActions: Seq[MergeAction], + notMatchedActions: Seq[MergeAction], + notMatchedBySourceActions: Seq[MergeAction], + targetOutput: Seq[Attribute], + sourceOutput: Seq[Attribute], + remainDeletedRow: Boolean): (Seq[Attribute], Seq[Attribute]) = { + val actionExpressions = + (matchedActions ++ notMatchedActions ++ notMatchedBySourceActions).flatMap { + case PaimonUpdateAction(condition, assignments) => + condition.toSeq ++ assignments.map(_.value) + case InsertAction(condition, assignments) => + condition.toSeq ++ assignments.map(_.value) + case DeleteAction(condition) => condition.toSeq + case _ => Seq.empty[Expression] + } + val referencedExprIds = + (mergeCondition +: actionExpressions).flatMap(_.references).map(_.exprId).toSet + val keepFullTargetRows = + remainDeletedRow && + (matchedActions ++ notMatchedBySourceActions).exists(_.isInstanceOf[DeleteAction]) + val neededTarget = + if (keepFullTargetRows) { + targetOutput + } else { + targetOutput.filter(attr => referencedExprIds.contains(attr.exprId)) + } + val neededSource = sourceOutput.filter(attr => referencedExprIds.contains(attr.exprId)) + (neededTarget, neededSource) + } + private case class MergeIntoProcessor( joinedAttributes: Seq[Attribute], targetRowHasNoMatch: Expression, diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTablePruneColumnsTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTablePruneColumnsTest.scala new file mode 100644 index 000000000000..509c38bac4f3 --- /dev/null +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/commands/MergeIntoPaimonTablePruneColumnsTest.scala @@ -0,0 +1,140 @@ +/* + * 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.paimon.spark.commands + +import org.apache.spark.sql.catalyst.expressions.{Add, AttributeReference, EqualTo, GreaterThan, Literal} +import org.apache.spark.sql.catalyst.plans.logical.{Assignment, DeleteAction, InsertAction, UpdateAction} +import org.apache.spark.sql.types.IntegerType +import org.scalatest.funsuite.AnyFunSuite + +/** Unit tests for the pure column-collection logic behind MERGE INTO join pruning. */ +class MergeIntoPaimonTablePruneColumnsTest extends AnyFunSuite { + + private def attr(name: String): AttributeReference = + AttributeReference(name, IntegerType, nullable = true)() + + test("collect referenced columns from conditions and assignment values on both sides") { + val tId = attr("id") + val tV1 = attr("v1") + val tV2 = attr("v2") + val tV3 = attr("v3") + val sId = attr("s_id") + val sV1 = attr("s_v1") + + val (neededTarget, neededSource) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + EqualTo(tId, sId), + // SET v1 = target.v1 + source.s_v1 + Seq(UpdateAction(None, Seq(Assignment(tV1, Add(tV1, sV1))))), + // INSERT (id, v2) VALUES (s_id, literal) + Seq(InsertAction(None, Seq(Assignment(tId, sId), Assignment(tV2, Literal(1))))), + Seq.empty, + Seq(tId, tV1, tV2, tV3), + Seq(sId, sV1), + remainDeletedRow = true + ) + + // v3 is never referenced; assignment keys are not collected, so `v2` (a literal value) drops. + assert(neededTarget == Seq(tId, tV1)) + assert(neededSource == Seq(sId, sV1)) + } + + test("delete clause keeps the full target side") { + val tId = attr("id") + val tV1 = attr("v1") + val sId = attr("s_id") + val fullTarget = Seq(tId, tV1) + + // A matched DELETE materializes a -D record carrying the full target row. + val (matchedDelete, _) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + EqualTo(tId, sId), + Seq(DeleteAction(None)), + Seq.empty, + Seq.empty, + fullTarget, + Seq(sId), + remainDeletedRow = true + ) + assert(matchedDelete == fullTarget) + + // Same for a NOT MATCHED BY SOURCE DELETE; once un-gated, its condition reference (`v1`) + // is collected alongside the merge condition's (`id`). + val nmsDelete = Seq(DeleteAction(Some(GreaterThan(tV1, Literal(5))))) + val (nmsGated, _) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + EqualTo(tId, sId), + Seq.empty, + Seq.empty, + nmsDelete, + fullTarget, + Seq(sId), + remainDeletedRow = true + ) + assert(nmsGated == fullTarget) + val (nmsUngated, _) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + EqualTo(tId, sId), + Seq.empty, + Seq.empty, + nmsDelete, + fullTarget, + Seq(sId), + remainDeletedRow = false + ) + assert(nmsUngated == Seq(tId, tV1)) + + // remainDeletedRow = false does not gate. + val (ungated, _) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + EqualTo(tId, sId), + Seq(DeleteAction(None)), + Seq.empty, + Seq.empty, + fullTarget, + Seq(sId), + remainDeletedRow = false + ) + assert(ungated == Seq(tId)) + + // A DELETE under WHEN NOT MATCHED never materializes -D records, so it does not gate. + val (notMatchedDelete, _) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + EqualTo(tId, sId), + Seq.empty, + Seq(DeleteAction(None)), + Seq.empty, + fullTarget, + Seq(sId), + remainDeletedRow = true + ) + assert(notMatchedDelete == Seq(tId)) + } + + test("no referenced columns yields empty sets") { + val tV1 = attr("v1") + + val (neededTarget, neededSource) = MergeIntoPaimonTable.pruneJoinColumnsForMerge( + Literal.TrueLiteral, + Seq.empty, + Seq(InsertAction(None, Seq(Assignment(tV1, Literal(1))))), + Seq.empty, + Seq(tV1), + Seq.empty, + remainDeletedRow = true + ) + + assert(neededTarget.isEmpty) + assert(neededSource.isEmpty) + } +} diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MergeIntoTableTestBase.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MergeIntoTableTestBase.scala index 014c953b41b6..c87b7913e11f 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MergeIntoTableTestBase.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/MergeIntoTableTestBase.scala @@ -21,12 +21,17 @@ package org.apache.paimon.spark.sql import org.apache.paimon.{CoreOptions, Snapshot} import org.apache.paimon.spark.{PaimonAppendTable, PaimonPrimaryKeyTable, PaimonSparkTestBase, PaimonTableTest} import org.apache.paimon.spark.catalyst.analysis.MergeInto - +import org.apache.spark.sql.catalyst.plans.FullOuter +import org.apache.spark.sql.catalyst.plans.logical.Join +import org.apache.spark.sql.execution.QueryExecution +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2ScanRelation +import org.apache.spark.sql.paimon.Utils +import org.apache.spark.sql.util.QueryExecutionListener import org.apache.spark.sql.{AnalysisException, Row} import org.assertj.core.api.Assertions.{assertThat, assertThatThrownBy} import java.util.UUID -import java.util.concurrent.Executors +import java.util.concurrent.{ConcurrentLinkedQueue, Executors} import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global @@ -1530,6 +1535,197 @@ abstract class MergeIntoTableTestBase extends PaimonSparkTestBase with PaimonTab trait MergeIntoPrimaryKeyTableTest extends PaimonSparkTestBase with PaimonPrimaryKeyTable { import testImplicits._ + test("Paimon MergeInto: wide pk table with update set star + insert star keeps pruned columns") { + withTable("source", "target") { + // Only `id` is referenced by the merge, so the target scan is pruned down to it; the output + // templates NULL-fill the pruned columns. If a NULL slot ever leaked into a written row, + // the matched rows below would lose their v1..v5 values. + createTable("target", "id INT, v1 INT, v2 INT, v3 STRING, v4 STRING, v5 DOUBLE", Seq("id")) + spark.sql( + "INSERT INTO target VALUES (1, 10, 100, 'a1', 'x1', 1.5), (2, 20, 200, 'a2', 'x2', 2.5), " + + "(3, 30, 300, 'a3', 'x3', 3.5)") + + Seq( + (1, 11, 111, "b1", "y1", 11.1), + (3, 33, 333, "b3", "y3", 33.3), + (4, 44, 444, "b4", "y4", 44.4)) + .toDF("id", "v1", "v2", "v3", "v4", "v5") + .createOrReplaceTempView("source") + + spark.sql(""" + |MERGE INTO target + |USING source + |ON target.id = source.id + |WHEN MATCHED THEN UPDATE SET * + |WHEN NOT MATCHED THEN INSERT * + |""".stripMargin) + + checkAnswer( + spark.sql("SELECT * FROM target ORDER BY id"), + Row(1, 11, 111, "b1", "y1", 11.1) :: Row(2, 20, 200, "a2", "x2", 2.5) :: + Row(3, 33, 333, "b3", "y3", 33.3) :: Row(4, 44, 444, "b4", "y4", 44.4) :: Nil + ) + } + } + + test("Paimon MergeInto: update assignments referencing target columns on pk table") { + withTable("source", "target") { + createTable("target", "id INT, v1 INT, v2 INT, v3 STRING", Seq("id")) + spark.sql("INSERT INTO target VALUES (1, 10, 100, 'a1'), (2, 20, 200, 'a2')") + + Seq((1, 5, 55, "b1"), (3, 7, 77, "b3")) + .toDF("id", "v1", "v2", "v3") + .createOrReplaceTempView("source") + + spark.sql(""" + |MERGE INTO target + |USING source + |ON target.id = source.id + |WHEN MATCHED THEN + |UPDATE SET v1 = target.v1 + source.v1, v2 = source.v2 + |WHEN NOT MATCHED THEN + |INSERT (id, v1, v2, v3) VALUES (source.id, source.v1, source.v2, source.v3) + |""".stripMargin) + + checkAnswer( + spark.sql("SELECT * FROM target ORDER BY id"), + Row(1, 15, 55, "a1") :: Row(2, 20, 200, "a2") :: Row(3, 7, 77, "b3") :: Nil) + } + } + + test("Paimon MergeInto: merge condition referencing target non-key column") { + withTable("source", "target") { + // `region` is only referenced by the merge condition; if pruning dropped it the join could + // not bind the condition. Ids are aligned so no insert collides with an existing primary + // key (a pk table cannot hold two rows with the same id). + createTable("target", "id INT, region STRING, v1 INT, v2 INT", Seq("id")) + spark.sql("INSERT INTO target VALUES (1, 'us', 10, 100), (2, 'eu', 20, 200)") + + Seq((1, "us", 11, 111), (2, "eu", 22, 222), (3, "ap", 30, 300)) + .toDF("id", "region", "v1", "v2") + .createOrReplaceTempView("source") + + spark.sql(""" + |MERGE INTO target + |USING source + |ON target.id = source.id AND target.region = source.region + |WHEN MATCHED THEN UPDATE SET * + |WHEN NOT MATCHED THEN INSERT * + |""".stripMargin) + + checkAnswer( + spark.sql("SELECT * FROM target ORDER BY id"), + Row(1, "us", 11, 111) :: Row(2, "eu", 22, 222) :: Row(3, "ap", 30, 300) :: Nil) + } + } + + test("Paimon MergeInto: delete clause on wide pk table materializes full target rows") { + withTable("source", "target") { + // The DELETE clause emits -D records that carry the full target row, so the target side + // must fall back to unpruned columns. + createTable("target", "id INT, v1 INT, v2 INT, v3 STRING, v4 STRING, v5 DOUBLE", Seq("id")) + spark.sql( + "INSERT INTO target VALUES (1, 10, 100, 'a1', 'x1', 1.5), (2, 20, 200, 'a2', 'x2', 2.5), " + + "(3, 30, 300, 'a3', 'x3', 3.5)") + + Seq( + (1, 11, 111, "b1", "y1", 11.1), + (3, 33, 333, "b3", "y3", 33.3), + (4, 44, 444, "b4", "y4", 44.4)) + .toDF("id", "v1", "v2", "v3", "v4", "v5") + .createOrReplaceTempView("source") + + spark.sql(""" + |MERGE INTO target + |USING source + |ON target.id = source.id + |WHEN MATCHED THEN DELETE + |WHEN NOT MATCHED THEN INSERT * + |""".stripMargin) + + checkAnswer( + spark.sql("SELECT * FROM target ORDER BY id"), + Row(2, 20, 200, "a2", "x2", 2.5) :: Row(4, 44, 444, "b4", "y4", 44.4) :: Nil) + } + } + + test("Paimon MergeInto: source side needs no columns") { + withTable("source", "target") { + createTable("target", "id INT, v INT", Seq("id")) + createTable( + "source", + "id INT, seq INT", + Seq("id"), + extraProps = Map("sequence.field" -> "seq")) + spark.sql("INSERT INTO target VALUES (1, 10), (2, 20)") + spark.sql("INSERT INTO source VALUES (1, 1)") + + // The source scan has rows but no projected columns; its sequence field is read internally. + spark.sql(""" + |MERGE INTO target + |USING source + |ON target.id > 0 + |WHEN MATCHED THEN UPDATE SET v = target.v + 1 + |""".stripMargin) + + checkAnswer( + spark.sql("SELECT * FROM target ORDER BY id"), + Row(1, 11) :: Row(2, 21) :: Nil) + } + } + + /** + * Guards the join-side column pruning. Correctness tests alone stay green when pruning silently + * degrades to a full-row scan, so assert the optimizer's target scan output instead: + * `UPDATE SET *` / `INSERT *` reference no target column except the merge key. + */ + test("Paimon MergeInto: scan only the merge key from the target table") { + // Dynamic-bucket writes replace the SQL plan with LogicalRDD before the write action. + assume(bucket > 0) + withTable("source", "target") { + createTable("target", "id INT, v1 INT, v2 INT, v3 STRING", Seq("id")) + spark.sql("INSERT INTO target VALUES (1, 10, 100, 'a1'), (2, 20, 200, 'a2')") + Seq((1, 11, 111, "b1"), (3, 33, 333, "b3")) + .toDF("id", "v1", "v2", "v3") + .createOrReplaceTempView("source") + + val targetScans = new ConcurrentLinkedQueue[Set[String]]() + val listener = new QueryExecutionListener { + override def onFailure(funcName: String, qe: QueryExecution, exception: Exception): Unit = + () + override def onSuccess(funcName: String, qe: QueryExecution, durationNs: Long): Unit = { + val isMergeWrite = qe.optimizedPlan.exists { + case join: Join => join.joinType == FullOuter + case _ => false + } + if (isMergeWrite) { + qe.optimizedPlan.collect { + case scan: DataSourceV2ScanRelation => + targetScans.add(scan.output.map(_.name).toSet) + } + } + } + } + + spark.listenerManager.register(listener) + try { + spark.sql( + """MERGE INTO target + |USING source + |ON target.id = source.id + |WHEN MATCHED THEN UPDATE SET * + |WHEN NOT MATCHED THEN INSERT * + |""".stripMargin) + Utils.waitUntilEventEmpty(spark) + } finally { + spark.listenerManager.unregister(listener) + } + + assert(targetScans.size() == 1, targetScans) + assert(targetScans.peek() == Set("id"), targetScans) + } + } + test("Paimon MergeInto: fail in case that maybe update primary key column") { withTable("source", "target") {