You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "leaves12138 (via GitHub)" <gi...@apache.org> on 2025/08/19 00:46:57 UTC

[PR] [WIP][core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

leaves12138 opened a new pull request, #6091:
URL: https://github.com/apache/paimon/pull/6091

   …
   
   <!-- Please specify the module before the PR name: [core] ... or [flink] ... -->
   
   ### Purpose
   
   <!-- Linking this pull request to the issue -->
   As for 'data-evolution' table, we can partially update column by spark MERGE INTO clause.
   
   
   <!-- What is the purpose of the change -->
   
   ### Tests
   
   <!-- List UT and IT cases to verify this change -->
   
   ### API and Format
   
   <!-- Does this change affect API or storage format -->
   
   ### Documentation
   
   <!-- Does this change introduce a new feature -->
   


-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284716141


##########
paimon-core/src/main/java/org/apache/paimon/table/sink/TableWrite.java:
##########
@@ -57,6 +57,9 @@ public interface TableWrite extends AutoCloseable {
     /** Write a row with bucket. */
     void write(InternalRow row, int bucket) throws Exception;
 
+    /** Write a row with partition and bucket. */
+    void write(InternalRow row, BinaryRow partition, int bucket) throws Exception;

Review Comment:
   OK



##########
paimon-core/src/main/java/org/apache/paimon/table/sink/TableWriteImpl.java:
##########
@@ -161,6 +161,11 @@ public void write(InternalRow row, int bucket) throws Exception {
         writeAndReturn(row, bucket);
     }
 
+    @Override
+    public void write(InternalRow row, BinaryRow partition, int bucket) throws Exception {

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287142829


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")
+        sql("INSERT INTO s VALUES (1, 11), (2, 22)")
+
+        sql(
+          "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')")
+        sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(2, 4)")
+
+        sql("""
+              |MERGE INTO t
+              |USING s
+              |ON t.id = s.id
+              |WHEN MATCHED THEN UPDATE SET t.b = s.b
+              |WHEN NOT MATCHED THEN INSERT (id, b, c) VALUES (id, b, 11)
+              |""".stripMargin)
+        checkAnswer(
+          sql("SELECT *, _ROW_ID, _SEQUENCE_NUMBER FROM t ORDER BY id"),
+          Seq(Row(1, 11, 11, 2, 2), Row(2, 22, 2, 0, 2), Row(3, 3, 3, 1, 2))
+        )
+      }
+    }
+  }
+
+  test("Row Lineage: merge into table with with data-evolution complex") {

Review Comment:
   Also add case for UPDATE and DELETE. If not support, just throw a readable exception.



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284646897


##########
paimon-core/src/main/java/org/apache/paimon/operation/BaseAppendFileStoreWrite.java:
##########
@@ -139,7 +139,7 @@ protected RecordWriter<InternalRow> createWriter(
     }
 
     @Override
-    public void withWriteType(RowType writeType) {
+    public BaseAppendFileStoreWrite withWriteType(RowType writeType) {

Review Comment:
   revert



##########
paimon-core/src/main/java/org/apache/paimon/operation/FileStoreWrite.java:
##########
@@ -54,7 +54,7 @@ public interface FileStoreWrite<T> extends Restorable<List<FileStoreWrite.State<
     FileStoreWrite<T> withIOManager(IOManager ioManager);
 
     /** Specified the write rowType. */
-    default void withWriteType(RowType writeType) {
+    default FileStoreWrite<T> withWriteType(RowType writeType) {

Review Comment:
   revert



##########
paimon-core/src/main/java/org/apache/paimon/table/sink/TableWrite.java:
##########
@@ -57,6 +57,9 @@ public interface TableWrite extends AutoCloseable {
     /** Write a row with bucket. */
     void write(InternalRow row, int bucket) throws Exception;
 
+    /** Write a row with partition and bucket. */
+    void write(InternalRow row, BinaryRow partition, int bucket) throws Exception;

Review Comment:
   revert



##########
paimon-core/src/main/java/org/apache/paimon/table/sink/BatchWriteBuilderImpl.java:
##########
@@ -80,4 +80,9 @@ public BatchTableCommit newCommit() {
                         .orElse(true));
         return commit;
     }
+
+    @Override
+    public String commitUser() {

Review Comment:
   revert



##########
paimon-core/src/main/java/org/apache/paimon/table/sink/TableWriteImpl.java:
##########
@@ -161,6 +161,11 @@ public void write(InternalRow row, int bucket) throws Exception {
         writeAndReturn(row, bucket);
     }
 
+    @Override
+    public void write(InternalRow row, BinaryRow partition, int bucket) throws Exception {

Review Comment:
   revert this file



##########
paimon-core/src/main/java/org/apache/paimon/table/sink/BatchWriteBuilder.java:
##########
@@ -71,4 +71,6 @@ default BatchWriteBuilder withOverwrite() {
     /** Create a {@link TableCommit} to commit {@link CommitMessage}s. */
     @Override
     BatchTableCommit newCommit();
+
+    String commitUser();

Review Comment:
   revert



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2289829015


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.paimon.CoreOptions
+import org.apache.paimon.data.BinaryRow
+import org.apache.paimon.spark.DataEvolutionSparkTableWrite
+import org.apache.paimon.spark.commands.DataEvolutionPaimonWriter.{deserializeCommitMessage, dynamicOp}
+import org.apache.paimon.spark.write.WriteHelper
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink._
+
+import org.apache.spark.sql._
+
+import java.io.IOException
+import java.util.Collections
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+case class DataEvolutionPaimonWriter(paimonTable: FileStoreTable) extends WriteHelper {
+
+  private lazy val firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]] =
+    initPartitionMap()
+  private lazy val normalWrite = PaimonSparkWriter(paimonTable)
+  override val table: FileStoreTable = paimonTable.copy(dynamicOp)

Review Comment:
   Well



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2286865945


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(

Review Comment:
   Sorry, not yet. Maybe we can fix this issue in future



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2286930373


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(
+    notMatchedBySourceActions.isEmpty,
+    "notMatchedBySourceActions is not supported in MergeIntoPaimonDataEvolutionTable.")
+  assert(
+    matchedActions.forall(x => x.isInstanceOf[UpdateAction]),
+    "Only SET clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN MATCHED.")
+  assert(
+    notMatchedActions.forall(x => x.isInstanceOf[InsertAction]),
+    "Only INSERT clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN NOT MATCHED."
+  )
+
+  import MergeIntoPaimonDataEvolutionTable._
+
+  override val table: FileStoreTable = v2Table.getTable.asInstanceOf[FileStoreTable]
+  private val firstRowIds: Seq[Long] = table
+    .newSnapshotReader()
+    .withManifestEntryFilter(entry => entry.file().firstRowId() != null)
+    .read()
+    .splits()
+    .asScala
+    .map(_.asInstanceOf[DataSplit])
+    .flatMap(split => split.dataFiles().asScala.map(s => s.firstRowId().asInstanceOf[Long]))
+    .distinct
+    .sorted
+    .toSeq
+
+  lazy val targetRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(targetTable)
+  lazy val sourceRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(sourceTable)
+
+  lazy val tableSchema: StructType = v2Table.schema
+
+  override def run(sparkSession: SparkSession): Seq[Row] = {
+    // Avoid that more than one source rows match the same target row.
+    val commitMessages = invokeMergeInto(sparkSession)
+    writer.commit(commitMessages.toSeq)
+    Seq.empty[Row]
+  }
+
+  private def invokeMergeInto(sparkSession: SparkSession): Seq[CommitMessage] = {
+    // step 1: find the related data split, make it target file plan
+    val dataSplits: Seq[DataSplit] = targetRelatedSplits(sparkSession)
+    val touchedFileTargetRelation =
+      createNewPlan(dataSplits.toSeq, targetRelation)
+
+    // step 2: invoke update action
+    val updateCommit =
+      if (matchedActions.nonEmpty)
+        updateActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    // step 3: invoke insert action
+    val insertCommit =
+      if (notMatchedActions.nonEmpty)
+        insertActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    updateCommit ++ insertCommit
+  }
+
+  private def targetRelatedSplits(sparkSession: SparkSession): Seq[DataSplit] = {
+    val mergeFields = extractFields(matchedCondition)
+    val mergeFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+    val mergeFieldsOnSource =
+      mergeFields.filter(field => sourceTable.output.exists(attr => attr.equals(field)))
+
+    val targetDss = createDataset(
+      sparkSession,
+      targetRelation.copy(
+        targetRelation.table,
+        mergeFieldsOnTarget.toSeq
+      ))
+
+    val sourceDss = createDataset(
+      sparkSession,
+      sourceRelation.copy(
+        sourceRelation.table,
+        mergeFieldsOnSource.toSeq
+      ))
+
+    val firstRowIdsTouched = mutable.Set.empty[Long]
+
+    firstRowIdsTouched ++= findRelatedFirstRowIds(
+      targetDss.alias("_left").join(sourceDss, toColumn(matchedCondition), "inner"),
+      sparkSession,
+      "_left." + ROW_ID_NAME)
+
+    table
+      .newSnapshotReader()
+      .withManifestEntryFilter(
+        entry =>
+          entry.file().firstRowId() != null && firstRowIdsTouched.contains(
+            entry.file().firstRowId()))
+      .read()
+      .splits()
+      .asScala
+      .map(_.asInstanceOf[DataSplit])
+      .toSeq
+  }
+
+  private def updateActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allFields = mutable.SortedSet.empty[AttributeReference](
+      (o1, o2) => {
+        o1.toString().compareTo(o2.toString())
+      }) ++ mergeFields
+    val updateColumns = mutable.Set[AttributeReference]()
+    for (action <- matchedActions) {
+      action match {
+        case updateAction: UpdateAction =>
+          for (assignment <- updateAction.assignments) {
+            if (!assignment.key.equals(assignment.value)) {
+              val key = assignment.key.asInstanceOf[AttributeReference]
+              updateColumns ++= Seq(key)
+            }
+          }
+      }
+    }
+
+    val updateColumnsSorted = updateColumns.toSeq.sortBy(
+      s => targetTable.output.map(x => x.toString()).indexOf(s.toString()))
+
+    val assignments = redundantColumns.map(column => Assignment(column, column))
+    val output = updateColumnsSorted ++ redundantColumns
+    val realUpdateActions = matchedActions
+      .map(s => s.asInstanceOf[UpdateAction])
+      .map(
+        update =>
+          UpdateAction.apply(
+            update.condition,
+            update.assignments.filter(
+              a =>
+                updateColumnsSorted.contains(
+                  a.key.asInstanceOf[AttributeReference])) ++ assignments))
+
+    for (action <- realUpdateActions) {
+      allFields ++= action.references.flatMap(r => extractFields(r)).seq
+    }
+
+    val allReadFieldsOnTarget = allFields.filter(
+      field =>
+        targetTable.output.exists(
+          attr => attr.toString().equals(field.toString()))) ++ redundantColumns
+    val allReadFieldsOnSource = allFields.filter(
+      field => sourceTable.output.exists(attr => attr.toString().equals(field.toString())))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+    val targetTableProjExprs = targetReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_TARGET)()
+    val targetTableProj = Project(targetTableProjExprs, targetReadPlan)
+
+    val sourceReadPlan = sourceRelation.copy(sourceRelation.table, allReadFieldsOnSource.toSeq)
+    val sourceTableProjExprs = sourceReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_SOURCE)()
+    val sourceTableProj = Project(sourceTableProjExprs, sourceReadPlan)
+
+    val joinPlan =
+      Join(targetTableProj, sourceTableProj, LeftOuter, Some(matchedCondition), JoinHint.NONE)
+
+    val rowFromSourceAttr = attribute(ROW_FROM_SOURCE, joinPlan)
+    val rowFromTargetAttr = attribute(ROW_FROM_TARGET, joinPlan)
+
+    val mergeRows = MergeRows(
+      isSourceRowPresent = rowFromSourceAttr,
+      isTargetRowPresent = rowFromTargetAttr,
+      matchedInstructions = realUpdateActions
+        .map(
+          action => {
+            Keep(action.condition.getOrElse(TrueLiteral), action.assignments.map(a => a.value))
+          }) ++ Seq(Keep(TrueLiteral, output)),
+      notMatchedInstructions = Nil,
+      notMatchedBySourceInstructions = Seq(Keep(TrueLiteral, output)).toSeq,
+      checkCardinality = false,
+      output = output,
+      child = joinPlan
+    )
+
+    val firstRowIdsFinal = firstRowIds
+    val firstRowIdUdf = udf((rowId: Long) => floorBinarySearch(firstRowIdsFinal, rowId))
+    val firstRowIdColumn = firstRowIdUdf(col(ROW_ID_NAME))
+    val toWrite =
+      createDataset(sparkSession, mergeRows).withColumn(FIRST_ROW_ID_NAME, firstRowIdColumn)
+    assert(toWrite.schema.fields.length == updateColumnsSorted.size + 2)
+    val sortedDs = toWrite
+      .repartitionByRange(firstRowIdColumn)
+      .sortWithinPartitions(FIRST_ROW_ID_NAME, ROW_ID_NAME)
+    val writer0 = writer.withDataEvolutionMergeWrite(updateColumnsSorted.map(_.name))
+    writer0.write(sortedDs)
+  }
+
+  private def insertActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allReadFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+
+    val joinPlan =
+      Join(sourceRelation, targetReadPlan, LeftAnti, Some(matchedCondition), JoinHint.NONE)
+
+    // merge rows as there are multiple not matched actions
+    val mergeRows = MergeRows(
+      isSourceRowPresent = TrueLiteral,
+      isTargetRowPresent = FalseLiteral,
+      matchedInstructions = Nil,
+      notMatchedInstructions = notMatchedActions.map {
+        case insertAction: InsertAction =>
+          Keep(
+            insertAction.condition.getOrElse(TrueLiteral),
+            insertAction.assignments.map(a => a.value))
+      }.toSeq,
+      notMatchedBySourceInstructions = Nil,
+      checkCardinality = false,
+      output = targetTable.output,
+      child = joinPlan
+    )
+
+    val toWrite = createDataset(sparkSession, mergeRows)
+    val writer0 = writer.disableDataEvolutionMergeWrite()
+    writer0.write(toWrite)
+  }
+
+  private def findRelatedFirstRowIds(
+      dataset: Dataset[Row],
+      sparkSession: SparkSession,
+      identifier: String = FILE_PATH_COLUMN): Array[Long] = {
+    import sparkSession.implicits._
+    val firstRowIdsFinal = firstRowIds
+    dataset
+      .select(identifier)
+      .as[Long]
+      .map(x => floorBinarySearch(firstRowIdsFinal, x))

Review Comment:
   ok



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(
+    notMatchedBySourceActions.isEmpty,
+    "notMatchedBySourceActions is not supported in MergeIntoPaimonDataEvolutionTable.")
+  assert(
+    matchedActions.forall(x => x.isInstanceOf[UpdateAction]),
+    "Only SET clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN MATCHED.")
+  assert(
+    notMatchedActions.forall(x => x.isInstanceOf[InsertAction]),
+    "Only INSERT clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN NOT MATCHED."
+  )
+
+  import MergeIntoPaimonDataEvolutionTable._
+
+  override val table: FileStoreTable = v2Table.getTable.asInstanceOf[FileStoreTable]
+  private val firstRowIds: Seq[Long] = table
+    .newSnapshotReader()
+    .withManifestEntryFilter(entry => entry.file().firstRowId() != null)
+    .read()
+    .splits()
+    .asScala
+    .map(_.asInstanceOf[DataSplit])
+    .flatMap(split => split.dataFiles().asScala.map(s => s.firstRowId().asInstanceOf[Long]))
+    .distinct
+    .sorted
+    .toSeq
+
+  lazy val targetRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(targetTable)
+  lazy val sourceRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(sourceTable)
+
+  lazy val tableSchema: StructType = v2Table.schema
+
+  override def run(sparkSession: SparkSession): Seq[Row] = {
+    // Avoid that more than one source rows match the same target row.
+    val commitMessages = invokeMergeInto(sparkSession)
+    writer.commit(commitMessages.toSeq)
+    Seq.empty[Row]
+  }
+
+  private def invokeMergeInto(sparkSession: SparkSession): Seq[CommitMessage] = {
+    // step 1: find the related data split, make it target file plan
+    val dataSplits: Seq[DataSplit] = targetRelatedSplits(sparkSession)
+    val touchedFileTargetRelation =
+      createNewPlan(dataSplits.toSeq, targetRelation)
+
+    // step 2: invoke update action
+    val updateCommit =
+      if (matchedActions.nonEmpty)
+        updateActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    // step 3: invoke insert action
+    val insertCommit =
+      if (notMatchedActions.nonEmpty)
+        insertActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    updateCommit ++ insertCommit
+  }
+
+  private def targetRelatedSplits(sparkSession: SparkSession): Seq[DataSplit] = {
+    val mergeFields = extractFields(matchedCondition)
+    val mergeFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+    val mergeFieldsOnSource =
+      mergeFields.filter(field => sourceTable.output.exists(attr => attr.equals(field)))
+
+    val targetDss = createDataset(
+      sparkSession,
+      targetRelation.copy(

Review Comment:
   Removed this



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284602371


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/DataEvolutionSparkTableWrite.scala:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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
+
+import org.apache.paimon.data.{BinaryRow, InternalRow}
+import org.apache.paimon.disk.IOManager
+import org.apache.paimon.io.{CompactIncrement, DataIncrement}
+import org.apache.paimon.operation.AppendFileStoreWrite
+import org.apache.paimon.spark.util.SparkRowUtils
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.{CommitMessageImpl, CommitMessageSerializer}
+import org.apache.paimon.types.RowType
+import org.apache.paimon.utils.RecordWriter
+
+import org.apache.spark.sql.Row
+
+import java.util.Collections
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+case class DataEvolutionSparkTableWrite(
+    table: FileStoreTable,

Review Comment:
   Copy `TARGET_FILE_SIZE` to Long.MAX.



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287141614


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")
+        sql("INSERT INTO s VALUES (1, 11), (2, 22)")
+
+        sql(
+          "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')")
+        sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(2, 4)")
+
+        sql("""
+              |MERGE INTO t
+              |USING s
+              |ON t.id = s.id
+              |WHEN MATCHED THEN UPDATE SET t.b = s.b
+              |WHEN NOT MATCHED THEN INSERT (id, b, c) VALUES (id, b, 11)

Review Comment:
   if insert (id, b)? What happen?



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on PR #6091:
URL: https://github.com/apache/paimon/pull/6091#issuecomment-3204365745

   > Please add documentation too. Maybe just in row tracking doc.
   
   OK


-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284737045


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala:
##########
@@ -50,23 +51,23 @@ import java.io.IOException
 import java.util.Collections.singletonMap
 
 import scala.collection.JavaConverters._
+import scala.collection.mutable
 
-case class PaimonSparkWriter(table: FileStoreTable, writeRowLineage: Boolean = false)
-  extends WriteHelper {
+case class PaimonSparkWriter(table: FileStoreTable) extends WriteHelper {
 
   private lazy val tableSchema = table.schema
 
   private lazy val bucketMode = table.bucketMode
 
+  private var firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]] = _

Review Comment:
   Why we need to make `firstRowIdToPartitionMap` as a class field?



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284741468


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala:
##########
@@ -50,23 +51,23 @@ import java.io.IOException
 import java.util.Collections.singletonMap
 
 import scala.collection.JavaConverters._
+import scala.collection.mutable
 
-case class PaimonSparkWriter(table: FileStoreTable, writeRowLineage: Boolean = false)
-  extends WriteHelper {
+case class PaimonSparkWriter(table: FileStoreTable) extends WriteHelper {

Review Comment:
   Why do you want to reuse this class? It seems many things cannot work with data evolution.



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287029764


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala:
##########
@@ -50,23 +51,23 @@ import java.io.IOException
 import java.util.Collections.singletonMap
 
 import scala.collection.JavaConverters._
+import scala.collection.mutable
 
-case class PaimonSparkWriter(table: FileStoreTable, writeRowLineage: Boolean = false)
-  extends WriteHelper {
+case class PaimonSparkWriter(table: FileStoreTable) extends WriteHelper {

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287186908


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")
+        sql("INSERT INTO s VALUES (1, 11), (2, 22)")
+
+        sql(
+          "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')")
+        sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(2, 4)")
+
+        sql("""
+              |MERGE INTO t
+              |USING s
+              |ON t.id = s.id
+              |WHEN MATCHED THEN UPDATE SET t.b = s.b
+              |WHEN NOT MATCHED THEN INSERT (id, b, c) VALUES (id, b, 11)

Review Comment:
   Throws exception "Can't align the table's columns in insert clause."



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287487007


##########
paimon-core/src/main/java/org/apache/paimon/table/sink/CommitMessageImpl.java:
##########
@@ -114,6 +117,23 @@ public boolean isEmpty() {
         return dataIncrement.isEmpty() && compactIncrement.isEmpty() && indexIncrement.isEmpty();
     }
 
+    public CommitMessageImpl assignFirstRowIdForIncrementNewFiles(long firstRowId) {

Review Comment:
   Any usesage?



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287500438


##########
paimon-core/src/main/java/org/apache/paimon/table/sink/CommitMessageImpl.java:
##########
@@ -114,6 +117,23 @@ public boolean isEmpty() {
         return dataIncrement.isEmpty() && compactIncrement.isEmpty() && indexIncrement.isEmpty();
     }
 
+    public CommitMessageImpl assignFirstRowIdForIncrementNewFiles(long firstRowId) {

Review Comment:
   Removed



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284715392


##########
paimon-core/src/main/java/org/apache/paimon/table/sink/BatchWriteBuilderImpl.java:
##########
@@ -80,4 +80,9 @@ public BatchTableCommit newCommit() {
                         .orElse(true));
         return commit;
     }
+
+    @Override
+    public String commitUser() {

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2286930201


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/util/ScanPlanHelper.scala:
##########
@@ -38,17 +38,22 @@ trait ScanPlanHelper extends SQLConfHelper {
       dataSplits: Seq[DataSplit],
       relation: DataSourceV2Relation,
       condition: Option[Expression] = None): LogicalPlan = {
-    val newRelation = relation.table match {
+    val newRelation = createNewPlan(dataSplits, relation)
+    condition match {
+      case Some(c) if c != TrueLiteral => Filter(c, newRelation)
+      case _ => newRelation
+    }
+  }
+
+  def createNewPlan(

Review Comment:
   To get DataXXXV2Table, this can copy fields some thing like that



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2289791233


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.paimon.CoreOptions
+import org.apache.paimon.data.BinaryRow
+import org.apache.paimon.spark.DataEvolutionSparkTableWrite
+import org.apache.paimon.spark.commands.DataEvolutionPaimonWriter.{deserializeCommitMessage, dynamicOp}
+import org.apache.paimon.spark.write.WriteHelper
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink._
+
+import org.apache.spark.sql._
+
+import java.io.IOException
+import java.util.Collections
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+case class DataEvolutionPaimonWriter(paimonTable: FileStoreTable) extends WriteHelper {
+
+  private lazy val firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]] =
+    initPartitionMap()
+  private lazy val normalWrite = PaimonSparkWriter(paimonTable)
+  override val table: FileStoreTable = paimonTable.copy(dynamicOp)

Review Comment:
   Copy dynamic options here, but use `paimonTable` to create `normalWrite`?



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi merged PR #6091:
URL: https://github.com/apache/paimon/pull/6091


-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP][core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284016374


##########
paimon-api/src/main/java/org/apache/paimon/table/SpecialFields.java:
##########
@@ -93,15 +94,22 @@ public class SpecialFields {
     public static final DataField ROW_ID =
             new DataField(Integer.MAX_VALUE - 5, "_ROW_ID", DataTypes.BIGINT());
 
+    public static final DataField FIRST_ROW_ID =

Review Comment:
   Do not add FIRST_ROW_ID in paimon-core, this work can be done by Spark.



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP][core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284016374


##########
paimon-api/src/main/java/org/apache/paimon/table/SpecialFields.java:
##########
@@ -93,15 +94,22 @@ public class SpecialFields {
     public static final DataField ROW_ID =
             new DataField(Integer.MAX_VALUE - 5, "_ROW_ID", DataTypes.BIGINT());
 
+    public static final DataField FIRST_ROW_ID =

Review Comment:
   Do not add FIRST_ROW_ID in paimon-core, this work can be did by Spark.



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287137302


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {

Review Comment:
   with with



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on PR #6091:
URL: https://github.com/apache/paimon/pull/6091#issuecomment-3209152982

   +1


-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287188728


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")

Review Comment:
   OK



##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")
+        sql("INSERT INTO s VALUES (1, 11), (2, 22)")
+
+        sql(
+          "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')")
+        sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(2, 4)")
+
+        sql("""
+              |MERGE INTO t
+              |USING s
+              |ON t.id = s.id
+              |WHEN MATCHED THEN UPDATE SET t.b = s.b
+              |WHEN NOT MATCHED THEN INSERT (id, b, c) VALUES (id, b, 11)
+              |""".stripMargin)
+        checkAnswer(
+          sql("SELECT *, _ROW_ID, _SEQUENCE_NUMBER FROM t ORDER BY id"),
+          Seq(Row(1, 11, 11, 2, 2), Row(2, 22, 2, 0, 2), Row(3, 3, 3, 1, 2))
+        )
+      }
+    }
+  }
+
+  test("Row Lineage: merge into table with with data-evolution complex") {
+    if (gteqSpark3_5) {
+      withTable("source", "target") {
+        sql(
+          "CREATE TABLE source (a INT, b INT, c STRING) TBLPROPERTIES ('row-tracking.enabled' = 'true')")

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284459231


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/DataEvolutionSparkTableWrite.scala:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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
+
+import org.apache.paimon.data.{BinaryRow, InternalRow}
+import org.apache.paimon.disk.IOManager
+import org.apache.paimon.io.{CompactIncrement, DataIncrement}
+import org.apache.paimon.operation.AppendFileStoreWrite
+import org.apache.paimon.spark.util.SparkRowUtils
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.{CommitMessageImpl, CommitMessageSerializer}
+import org.apache.paimon.types.RowType
+import org.apache.paimon.utils.RecordWriter
+
+import org.apache.spark.sql.Row
+
+import java.util.Collections
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+case class DataEvolutionSparkTableWrite(
+    table: FileStoreTable,
+    commitUser: String,
+    writeType: RowType,
+    firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]])
+  extends SparkTableWriteTrait {
+
+  private var currentWriter: PerFileWriter = _
+  private val ioManager: IOManager = SparkUtils.createIOManager
+  private val rowIdIndex = writeType.getFieldCount
+  private val firstRowIdIndex = rowIdIndex + 1
+  private val commitMessageImpls = ListBuffer[CommitMessageImpl]()
+
+  private val toPaimonRow = {
+    SparkRowUtils.toPaimonRow(writeType, -1)
+  }
+
+  def write(row: Row): Unit = {
+    val firstRowId = row.getLong(firstRowIdIndex)
+    val rowId = row.getLong(rowIdIndex)
+
+    if (currentWriter == null || !currentWriter.matchFirstRowId(firstRowId)) {
+      newCurrentWriter(firstRowId)
+    }
+
+    currentWriter.write(toPaimonRow(row), rowId)
+  }
+
+  def newCurrentWriter(firstRowId: Long): Unit = {
+    finishCurrentWriter()
+    val (partition, numRecords) = firstRowIdToPartitionMap.getOrElse(firstRowId, null)
+    if (partition == null) {
+      throw new IllegalArgumentException(
+        s"First row ID $firstRowId not found in partition map. " +
+          s"Available first row IDs: ${firstRowIdToPartitionMap.keys.mkString(", ")}")
+    }
+    val writer = table
+      .store()
+      .newWrite(commitUser)
+      .withWriteType(writeType)
+      .asInstanceOf[AppendFileStoreWrite]
+      .createWriterContainer(partition, 0, true)
+      .writer
+    currentWriter = PerFileWriter(partition, firstRowId, writer, numRecords)
+  }
+
+  def finishCurrentWriter(): Unit = {
+    if (currentWriter != null) {
+      commitMessageImpls.append(currentWriter.finish())
+    }
+    currentWriter = null
+  }
+
+  def write(row: Row, bucket: Int): Unit = {
+    throw new UnsupportedOperationException(
+      "DataEvolutionSparkTableWrite does not support writing with bucket.")
+  }
+
+  def finish(): Iterator[Array[Byte]] = {
+    finishCurrentWriter()
+    var bytesWritten = 0L
+    var recordsWritten = 0L
+    val commitMessages = new ListBuffer[Array[Byte]]()
+    val serializer = new CommitMessageSerializer()
+    commitMessageImpls.foreach {
+      message: CommitMessageImpl =>
+        message.newFilesIncrement().newFiles().asScala.foreach {
+          dataFileMeta =>
+            bytesWritten += dataFileMeta.fileSize()
+            recordsWritten += dataFileMeta.rowCount()
+        }
+        commitMessages += serializer.serialize(message)
+    }
+    reportOutputMetrics(bytesWritten, recordsWritten)
+    commitMessages.iterator
+  }
+
+  override def close(): Unit = {
+    ioManager.close()
+  }
+
+  private case class PerFileWriter(
+      partition: BinaryRow,
+      firstRowId: Long,
+      recordWriter: RecordWriter[InternalRow],

Review Comment:
   Can we just use `TableWrite` here?



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284714897


##########
paimon-core/src/main/java/org/apache/paimon/operation/BaseAppendFileStoreWrite.java:
##########
@@ -139,7 +139,7 @@ protected RecordWriter<InternalRow> createWriter(
     }
 
     @Override
-    public void withWriteType(RowType writeType) {
+    public BaseAppendFileStoreWrite withWriteType(RowType writeType) {

Review Comment:
   OK



##########
paimon-core/src/main/java/org/apache/paimon/operation/FileStoreWrite.java:
##########
@@ -54,7 +54,7 @@ public interface FileStoreWrite<T> extends Restorable<List<FileStoreWrite.State<
     FileStoreWrite<T> withIOManager(IOManager ioManager);
 
     /** Specified the write rowType. */
-    default void withWriteType(RowType writeType) {
+    default FileStoreWrite<T> withWriteType(RowType writeType) {

Review Comment:
   OK



##########
paimon-core/src/main/java/org/apache/paimon/table/sink/BatchWriteBuilder.java:
##########
@@ -71,4 +71,6 @@ default BatchWriteBuilder withOverwrite() {
     /** Create a {@link TableCommit} to commit {@link CommitMessage}s. */
     @Override
     BatchTableCommit newCommit();
+
+    String commitUser();

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2286864802


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/DataEvolutionSparkTableWrite.scala:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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
+
+import org.apache.paimon.data.{BinaryRow, InternalRow}
+import org.apache.paimon.disk.IOManager
+import org.apache.paimon.io.{CompactIncrement, DataIncrement}
+import org.apache.paimon.operation.AppendFileStoreWrite
+import org.apache.paimon.spark.util.SparkRowUtils
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.{CommitMessageImpl, CommitMessageSerializer}
+import org.apache.paimon.types.RowType
+import org.apache.paimon.utils.RecordWriter
+
+import org.apache.spark.sql.Row
+
+import java.util.Collections
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+case class DataEvolutionSparkTableWrite(
+    table: FileStoreTable,
+    commitUser: String,
+    writeType: RowType,
+    firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]])
+  extends SparkTableWriteTrait {
+
+  private var currentWriter: PerFileWriter = _
+  private val ioManager: IOManager = SparkUtils.createIOManager
+  private val rowIdIndex = writeType.getFieldCount
+  private val firstRowIdIndex = rowIdIndex + 1
+  private val commitMessageImpls = ListBuffer[CommitMessageImpl]()
+
+  private val toPaimonRow = {
+    SparkRowUtils.toPaimonRow(writeType, -1)
+  }
+
+  def write(row: Row): Unit = {
+    val firstRowId = row.getLong(firstRowIdIndex)
+    val rowId = row.getLong(rowIdIndex)
+
+    if (currentWriter == null || !currentWriter.matchFirstRowId(firstRowId)) {
+      newCurrentWriter(firstRowId)
+    }
+
+    currentWriter.write(toPaimonRow(row), rowId)
+  }
+
+  def newCurrentWriter(firstRowId: Long): Unit = {
+    finishCurrentWriter()
+    val (partition, numRecords) = firstRowIdToPartitionMap.getOrElse(firstRowId, null)
+    if (partition == null) {
+      throw new IllegalArgumentException(
+        s"First row ID $firstRowId not found in partition map. " +
+          s"Available first row IDs: ${firstRowIdToPartitionMap.keys.mkString(", ")}")
+    }
+    val writer = table
+      .store()
+      .newWrite(commitUser)
+      .withWriteType(writeType)
+      .asInstanceOf[AppendFileStoreWrite]
+      .createWriterContainer(partition, 0, true)
+      .writer
+    currentWriter = PerFileWriter(partition, firstRowId, writer, numRecords)
+  }
+
+  def finishCurrentWriter(): Unit = {
+    if (currentWriter != null) {
+      commitMessageImpls.append(currentWriter.finish())
+    }
+    currentWriter = null
+  }
+
+  def write(row: Row, bucket: Int): Unit = {
+    throw new UnsupportedOperationException(
+      "DataEvolutionSparkTableWrite does not support writing with bucket.")
+  }
+
+  def finish(): Iterator[Array[Byte]] = {
+    finishCurrentWriter()
+    var bytesWritten = 0L
+    var recordsWritten = 0L
+    val commitMessages = new ListBuffer[Array[Byte]]()
+    val serializer = new CommitMessageSerializer()
+    commitMessageImpls.foreach {
+      message: CommitMessageImpl =>
+        message.newFilesIncrement().newFiles().asScala.foreach {
+          dataFileMeta =>
+            bytesWritten += dataFileMeta.fileSize()
+            recordsWritten += dataFileMeta.rowCount()
+        }
+        commitMessages += serializer.serialize(message)
+    }
+    reportOutputMetrics(bytesWritten, recordsWritten)
+    commitMessages.iterator
+  }
+
+  override def close(): Unit = {
+    ioManager.close()
+  }
+
+  private case class PerFileWriter(
+      partition: BinaryRow,
+      firstRowId: Long,
+      recordWriter: RecordWriter[InternalRow],

Review Comment:
   Sorry, we can't. It seems not suitable here for file level record writing



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287030132


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/PaimonSparkWriter.scala:
##########
@@ -50,23 +51,23 @@ import java.io.IOException
 import java.util.Collections.singletonMap
 
 import scala.collection.JavaConverters._
+import scala.collection.mutable
 
-case class PaimonSparkWriter(table: FileStoreTable, writeRowLineage: Boolean = false)
-  extends WriteHelper {
+case class PaimonSparkWriter(table: FileStoreTable) extends WriteHelper {
 
   private lazy val tableSchema = table.schema
 
   private lazy val bucketMode = table.bucketMode
 
+  private var firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]] = _

Review Comment:
   Reverted this class



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287135934


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")

Review Comment:
   No need to be row tracking table.



##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")
+        sql("INSERT INTO s VALUES (1, 11), (2, 22)")
+
+        sql(
+          "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')")
+        sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(2, 4)")
+
+        sql("""
+              |MERGE INTO t
+              |USING s
+              |ON t.id = s.id
+              |WHEN MATCHED THEN UPDATE SET t.b = s.b
+              |WHEN NOT MATCHED THEN INSERT (id, b, c) VALUES (id, b, 11)
+              |""".stripMargin)
+        checkAnswer(
+          sql("SELECT *, _ROW_ID, _SEQUENCE_NUMBER FROM t ORDER BY id"),
+          Seq(Row(1, 11, 11, 2, 2), Row(2, 22, 2, 0, 2), Row(3, 3, 3, 1, 2))
+        )
+      }
+    }
+  }
+
+  test("Row Lineage: merge into table with with data-evolution complex") {
+    if (gteqSpark3_5) {
+      withTable("source", "target") {
+        sql(
+          "CREATE TABLE source (a INT, b INT, c STRING) TBLPROPERTIES ('row-tracking.enabled' = 'true')")

Review Comment:
   No need to be row tracking table.



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "Zouxxyy (via GitHub)" <gi...@apache.org>.
Zouxxyy commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2286703579


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(
+    notMatchedBySourceActions.isEmpty,
+    "notMatchedBySourceActions is not supported in MergeIntoPaimonDataEvolutionTable.")
+  assert(
+    matchedActions.forall(x => x.isInstanceOf[UpdateAction]),
+    "Only SET clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN MATCHED.")
+  assert(
+    notMatchedActions.forall(x => x.isInstanceOf[InsertAction]),
+    "Only INSERT clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN NOT MATCHED."
+  )
+
+  import MergeIntoPaimonDataEvolutionTable._
+
+  override val table: FileStoreTable = v2Table.getTable.asInstanceOf[FileStoreTable]
+  private val firstRowIds: Seq[Long] = table
+    .newSnapshotReader()
+    .withManifestEntryFilter(entry => entry.file().firstRowId() != null)
+    .read()
+    .splits()
+    .asScala
+    .map(_.asInstanceOf[DataSplit])
+    .flatMap(split => split.dataFiles().asScala.map(s => s.firstRowId().asInstanceOf[Long]))
+    .distinct
+    .sorted
+    .toSeq
+
+  lazy val targetRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(targetTable)
+  lazy val sourceRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(sourceTable)
+
+  lazy val tableSchema: StructType = v2Table.schema
+
+  override def run(sparkSession: SparkSession): Seq[Row] = {
+    // Avoid that more than one source rows match the same target row.
+    val commitMessages = invokeMergeInto(sparkSession)
+    writer.commit(commitMessages.toSeq)
+    Seq.empty[Row]
+  }
+
+  private def invokeMergeInto(sparkSession: SparkSession): Seq[CommitMessage] = {
+    // step 1: find the related data split, make it target file plan
+    val dataSplits: Seq[DataSplit] = targetRelatedSplits(sparkSession)
+    val touchedFileTargetRelation =
+      createNewPlan(dataSplits.toSeq, targetRelation)
+
+    // step 2: invoke update action
+    val updateCommit =
+      if (matchedActions.nonEmpty)
+        updateActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    // step 3: invoke insert action
+    val insertCommit =
+      if (notMatchedActions.nonEmpty)
+        insertActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    updateCommit ++ insertCommit
+  }
+
+  private def targetRelatedSplits(sparkSession: SparkSession): Seq[DataSplit] = {
+    val mergeFields = extractFields(matchedCondition)
+    val mergeFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+    val mergeFieldsOnSource =
+      mergeFields.filter(field => sourceTable.output.exists(attr => attr.equals(field)))
+
+    val targetDss = createDataset(
+      sparkSession,
+      targetRelation.copy(
+        targetRelation.table,
+        mergeFieldsOnTarget.toSeq
+      ))
+
+    val sourceDss = createDataset(
+      sparkSession,
+      sourceRelation.copy(
+        sourceRelation.table,
+        mergeFieldsOnSource.toSeq
+      ))
+
+    val firstRowIdsTouched = mutable.Set.empty[Long]
+
+    firstRowIdsTouched ++= findRelatedFirstRowIds(
+      targetDss.alias("_left").join(sourceDss, toColumn(matchedCondition), "inner"),
+      sparkSession,
+      "_left." + ROW_ID_NAME)
+
+    table
+      .newSnapshotReader()
+      .withManifestEntryFilter(
+        entry =>
+          entry.file().firstRowId() != null && firstRowIdsTouched.contains(
+            entry.file().firstRowId()))
+      .read()
+      .splits()
+      .asScala
+      .map(_.asInstanceOf[DataSplit])
+      .toSeq
+  }
+
+  private def updateActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allFields = mutable.SortedSet.empty[AttributeReference](
+      (o1, o2) => {
+        o1.toString().compareTo(o2.toString())
+      }) ++ mergeFields
+    val updateColumns = mutable.Set[AttributeReference]()
+    for (action <- matchedActions) {
+      action match {
+        case updateAction: UpdateAction =>
+          for (assignment <- updateAction.assignments) {
+            if (!assignment.key.equals(assignment.value)) {
+              val key = assignment.key.asInstanceOf[AttributeReference]
+              updateColumns ++= Seq(key)
+            }
+          }
+      }
+    }
+
+    val updateColumnsSorted = updateColumns.toSeq.sortBy(
+      s => targetTable.output.map(x => x.toString()).indexOf(s.toString()))
+
+    val assignments = redundantColumns.map(column => Assignment(column, column))
+    val output = updateColumnsSorted ++ redundantColumns
+    val realUpdateActions = matchedActions
+      .map(s => s.asInstanceOf[UpdateAction])
+      .map(
+        update =>
+          UpdateAction.apply(
+            update.condition,
+            update.assignments.filter(
+              a =>
+                updateColumnsSorted.contains(
+                  a.key.asInstanceOf[AttributeReference])) ++ assignments))
+
+    for (action <- realUpdateActions) {
+      allFields ++= action.references.flatMap(r => extractFields(r)).seq
+    }
+
+    val allReadFieldsOnTarget = allFields.filter(
+      field =>
+        targetTable.output.exists(
+          attr => attr.toString().equals(field.toString()))) ++ redundantColumns
+    val allReadFieldsOnSource = allFields.filter(
+      field => sourceTable.output.exists(attr => attr.toString().equals(field.toString())))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+    val targetTableProjExprs = targetReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_TARGET)()
+    val targetTableProj = Project(targetTableProjExprs, targetReadPlan)
+
+    val sourceReadPlan = sourceRelation.copy(sourceRelation.table, allReadFieldsOnSource.toSeq)
+    val sourceTableProjExprs = sourceReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_SOURCE)()
+    val sourceTableProj = Project(sourceTableProjExprs, sourceReadPlan)
+
+    val joinPlan =
+      Join(targetTableProj, sourceTableProj, LeftOuter, Some(matchedCondition), JoinHint.NONE)
+
+    val rowFromSourceAttr = attribute(ROW_FROM_SOURCE, joinPlan)
+    val rowFromTargetAttr = attribute(ROW_FROM_TARGET, joinPlan)
+
+    val mergeRows = MergeRows(
+      isSourceRowPresent = rowFromSourceAttr,
+      isTargetRowPresent = rowFromTargetAttr,
+      matchedInstructions = realUpdateActions
+        .map(
+          action => {
+            Keep(action.condition.getOrElse(TrueLiteral), action.assignments.map(a => a.value))
+          }) ++ Seq(Keep(TrueLiteral, output)),
+      notMatchedInstructions = Nil,
+      notMatchedBySourceInstructions = Seq(Keep(TrueLiteral, output)).toSeq,
+      checkCardinality = false,
+      output = output,
+      child = joinPlan
+    )
+
+    val firstRowIdsFinal = firstRowIds
+    val firstRowIdUdf = udf((rowId: Long) => floorBinarySearch(firstRowIdsFinal, rowId))
+    val firstRowIdColumn = firstRowIdUdf(col(ROW_ID_NAME))
+    val toWrite =
+      createDataset(sparkSession, mergeRows).withColumn(FIRST_ROW_ID_NAME, firstRowIdColumn)
+    assert(toWrite.schema.fields.length == updateColumnsSorted.size + 2)
+    val sortedDs = toWrite
+      .repartitionByRange(firstRowIdColumn)
+      .sortWithinPartitions(FIRST_ROW_ID_NAME, ROW_ID_NAME)
+    val writer0 = writer.withDataEvolutionMergeWrite(updateColumnsSorted.map(_.name))
+    writer0.write(sortedDs)
+  }
+
+  private def insertActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allReadFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+
+    val joinPlan =
+      Join(sourceRelation, targetReadPlan, LeftAnti, Some(matchedCondition), JoinHint.NONE)
+
+    // merge rows as there are multiple not matched actions
+    val mergeRows = MergeRows(
+      isSourceRowPresent = TrueLiteral,
+      isTargetRowPresent = FalseLiteral,
+      matchedInstructions = Nil,
+      notMatchedInstructions = notMatchedActions.map {
+        case insertAction: InsertAction =>
+          Keep(
+            insertAction.condition.getOrElse(TrueLiteral),
+            insertAction.assignments.map(a => a.value))
+      }.toSeq,
+      notMatchedBySourceInstructions = Nil,
+      checkCardinality = false,
+      output = targetTable.output,
+      child = joinPlan
+    )
+
+    val toWrite = createDataset(sparkSession, mergeRows)
+    val writer0 = writer.disableDataEvolutionMergeWrite()
+    writer0.write(toWrite)
+  }
+
+  private def findRelatedFirstRowIds(
+      dataset: Dataset[Row],
+      sparkSession: SparkSession,
+      identifier: String = FILE_PATH_COLUMN): Array[Long] = {

Review Comment:
   why FILE_PATH_COLUMN



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(

Review Comment:
   When these conditions are not met, can we write it in the old way?



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(
+    notMatchedBySourceActions.isEmpty,
+    "notMatchedBySourceActions is not supported in MergeIntoPaimonDataEvolutionTable.")
+  assert(
+    matchedActions.forall(x => x.isInstanceOf[UpdateAction]),
+    "Only SET clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN MATCHED.")
+  assert(
+    notMatchedActions.forall(x => x.isInstanceOf[InsertAction]),
+    "Only INSERT clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN NOT MATCHED."
+  )
+
+  import MergeIntoPaimonDataEvolutionTable._
+
+  override val table: FileStoreTable = v2Table.getTable.asInstanceOf[FileStoreTable]
+  private val firstRowIds: Seq[Long] = table
+    .newSnapshotReader()
+    .withManifestEntryFilter(entry => entry.file().firstRowId() != null)
+    .read()
+    .splits()
+    .asScala
+    .map(_.asInstanceOf[DataSplit])
+    .flatMap(split => split.dataFiles().asScala.map(s => s.firstRowId().asInstanceOf[Long]))
+    .distinct
+    .sorted
+    .toSeq
+
+  lazy val targetRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(targetTable)
+  lazy val sourceRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(sourceTable)
+
+  lazy val tableSchema: StructType = v2Table.schema
+
+  override def run(sparkSession: SparkSession): Seq[Row] = {
+    // Avoid that more than one source rows match the same target row.
+    val commitMessages = invokeMergeInto(sparkSession)
+    writer.commit(commitMessages.toSeq)
+    Seq.empty[Row]
+  }
+
+  private def invokeMergeInto(sparkSession: SparkSession): Seq[CommitMessage] = {
+    // step 1: find the related data split, make it target file plan
+    val dataSplits: Seq[DataSplit] = targetRelatedSplits(sparkSession)
+    val touchedFileTargetRelation =
+      createNewPlan(dataSplits.toSeq, targetRelation)
+
+    // step 2: invoke update action
+    val updateCommit =
+      if (matchedActions.nonEmpty)
+        updateActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    // step 3: invoke insert action
+    val insertCommit =
+      if (notMatchedActions.nonEmpty)
+        insertActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    updateCommit ++ insertCommit
+  }
+
+  private def targetRelatedSplits(sparkSession: SparkSession): Seq[DataSplit] = {
+    val mergeFields = extractFields(matchedCondition)
+    val mergeFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+    val mergeFieldsOnSource =
+      mergeFields.filter(field => sourceTable.output.exists(attr => attr.equals(field)))
+
+    val targetDss = createDataset(
+      sparkSession,
+      targetRelation.copy(
+        targetRelation.table,
+        mergeFieldsOnTarget.toSeq
+      ))
+
+    val sourceDss = createDataset(
+      sparkSession,
+      sourceRelation.copy(
+        sourceRelation.table,
+        mergeFieldsOnSource.toSeq
+      ))
+
+    val firstRowIdsTouched = mutable.Set.empty[Long]
+
+    firstRowIdsTouched ++= findRelatedFirstRowIds(
+      targetDss.alias("_left").join(sourceDss, toColumn(matchedCondition), "inner"),
+      sparkSession,
+      "_left." + ROW_ID_NAME)
+
+    table
+      .newSnapshotReader()
+      .withManifestEntryFilter(
+        entry =>
+          entry.file().firstRowId() != null && firstRowIdsTouched.contains(
+            entry.file().firstRowId()))
+      .read()
+      .splits()
+      .asScala
+      .map(_.asInstanceOf[DataSplit])
+      .toSeq
+  }
+
+  private def updateActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allFields = mutable.SortedSet.empty[AttributeReference](
+      (o1, o2) => {
+        o1.toString().compareTo(o2.toString())
+      }) ++ mergeFields
+    val updateColumns = mutable.Set[AttributeReference]()
+    for (action <- matchedActions) {
+      action match {
+        case updateAction: UpdateAction =>
+          for (assignment <- updateAction.assignments) {
+            if (!assignment.key.equals(assignment.value)) {
+              val key = assignment.key.asInstanceOf[AttributeReference]
+              updateColumns ++= Seq(key)
+            }
+          }
+      }
+    }
+
+    val updateColumnsSorted = updateColumns.toSeq.sortBy(
+      s => targetTable.output.map(x => x.toString()).indexOf(s.toString()))
+
+    val assignments = redundantColumns.map(column => Assignment(column, column))
+    val output = updateColumnsSorted ++ redundantColumns
+    val realUpdateActions = matchedActions
+      .map(s => s.asInstanceOf[UpdateAction])
+      .map(
+        update =>
+          UpdateAction.apply(
+            update.condition,
+            update.assignments.filter(
+              a =>
+                updateColumnsSorted.contains(
+                  a.key.asInstanceOf[AttributeReference])) ++ assignments))
+
+    for (action <- realUpdateActions) {
+      allFields ++= action.references.flatMap(r => extractFields(r)).seq
+    }
+
+    val allReadFieldsOnTarget = allFields.filter(
+      field =>
+        targetTable.output.exists(
+          attr => attr.toString().equals(field.toString()))) ++ redundantColumns
+    val allReadFieldsOnSource = allFields.filter(
+      field => sourceTable.output.exists(attr => attr.toString().equals(field.toString())))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+    val targetTableProjExprs = targetReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_TARGET)()
+    val targetTableProj = Project(targetTableProjExprs, targetReadPlan)
+
+    val sourceReadPlan = sourceRelation.copy(sourceRelation.table, allReadFieldsOnSource.toSeq)
+    val sourceTableProjExprs = sourceReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_SOURCE)()
+    val sourceTableProj = Project(sourceTableProjExprs, sourceReadPlan)
+
+    val joinPlan =
+      Join(targetTableProj, sourceTableProj, LeftOuter, Some(matchedCondition), JoinHint.NONE)
+
+    val rowFromSourceAttr = attribute(ROW_FROM_SOURCE, joinPlan)
+    val rowFromTargetAttr = attribute(ROW_FROM_TARGET, joinPlan)
+
+    val mergeRows = MergeRows(
+      isSourceRowPresent = rowFromSourceAttr,
+      isTargetRowPresent = rowFromTargetAttr,
+      matchedInstructions = realUpdateActions
+        .map(
+          action => {
+            Keep(action.condition.getOrElse(TrueLiteral), action.assignments.map(a => a.value))
+          }) ++ Seq(Keep(TrueLiteral, output)),
+      notMatchedInstructions = Nil,
+      notMatchedBySourceInstructions = Seq(Keep(TrueLiteral, output)).toSeq,
+      checkCardinality = false,
+      output = output,
+      child = joinPlan
+    )
+
+    val firstRowIdsFinal = firstRowIds
+    val firstRowIdUdf = udf((rowId: Long) => floorBinarySearch(firstRowIdsFinal, rowId))
+    val firstRowIdColumn = firstRowIdUdf(col(ROW_ID_NAME))
+    val toWrite =
+      createDataset(sparkSession, mergeRows).withColumn(FIRST_ROW_ID_NAME, firstRowIdColumn)
+    assert(toWrite.schema.fields.length == updateColumnsSorted.size + 2)
+    val sortedDs = toWrite
+      .repartitionByRange(firstRowIdColumn)
+      .sortWithinPartitions(FIRST_ROW_ID_NAME, ROW_ID_NAME)
+    val writer0 = writer.withDataEvolutionMergeWrite(updateColumnsSorted.map(_.name))
+    writer0.write(sortedDs)
+  }
+
+  private def insertActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allReadFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+
+    val joinPlan =
+      Join(sourceRelation, targetReadPlan, LeftAnti, Some(matchedCondition), JoinHint.NONE)
+
+    // merge rows as there are multiple not matched actions
+    val mergeRows = MergeRows(
+      isSourceRowPresent = TrueLiteral,
+      isTargetRowPresent = FalseLiteral,
+      matchedInstructions = Nil,
+      notMatchedInstructions = notMatchedActions.map {
+        case insertAction: InsertAction =>
+          Keep(
+            insertAction.condition.getOrElse(TrueLiteral),
+            insertAction.assignments.map(a => a.value))
+      }.toSeq,
+      notMatchedBySourceInstructions = Nil,
+      checkCardinality = false,
+      output = targetTable.output,
+      child = joinPlan
+    )
+
+    val toWrite = createDataset(sparkSession, mergeRows)
+    val writer0 = writer.disableDataEvolutionMergeWrite()
+    writer0.write(toWrite)
+  }
+
+  private def findRelatedFirstRowIds(
+      dataset: Dataset[Row],
+      sparkSession: SparkSession,
+      identifier: String = FILE_PATH_COLUMN): Array[Long] = {
+    import sparkSession.implicits._
+    val firstRowIdsFinal = firstRowIds
+    dataset
+      .select(identifier)
+      .as[Long]
+      .map(x => floorBinarySearch(firstRowIdsFinal, x))

Review Comment:
   reuse firstRowIdUdf?



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(
+    notMatchedBySourceActions.isEmpty,
+    "notMatchedBySourceActions is not supported in MergeIntoPaimonDataEvolutionTable.")
+  assert(
+    matchedActions.forall(x => x.isInstanceOf[UpdateAction]),
+    "Only SET clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN MATCHED.")
+  assert(
+    notMatchedActions.forall(x => x.isInstanceOf[InsertAction]),
+    "Only INSERT clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN NOT MATCHED."
+  )
+
+  import MergeIntoPaimonDataEvolutionTable._
+
+  override val table: FileStoreTable = v2Table.getTable.asInstanceOf[FileStoreTable]
+  private val firstRowIds: Seq[Long] = table
+    .newSnapshotReader()
+    .withManifestEntryFilter(entry => entry.file().firstRowId() != null)
+    .read()
+    .splits()
+    .asScala
+    .map(_.asInstanceOf[DataSplit])
+    .flatMap(split => split.dataFiles().asScala.map(s => s.firstRowId().asInstanceOf[Long]))
+    .distinct
+    .sorted
+    .toSeq
+
+  lazy val targetRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(targetTable)
+  lazy val sourceRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(sourceTable)
+
+  lazy val tableSchema: StructType = v2Table.schema
+
+  override def run(sparkSession: SparkSession): Seq[Row] = {
+    // Avoid that more than one source rows match the same target row.
+    val commitMessages = invokeMergeInto(sparkSession)
+    writer.commit(commitMessages.toSeq)
+    Seq.empty[Row]
+  }
+
+  private def invokeMergeInto(sparkSession: SparkSession): Seq[CommitMessage] = {
+    // step 1: find the related data split, make it target file plan
+    val dataSplits: Seq[DataSplit] = targetRelatedSplits(sparkSession)
+    val touchedFileTargetRelation =
+      createNewPlan(dataSplits.toSeq, targetRelation)
+
+    // step 2: invoke update action
+    val updateCommit =
+      if (matchedActions.nonEmpty)
+        updateActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    // step 3: invoke insert action
+    val insertCommit =
+      if (notMatchedActions.nonEmpty)
+        insertActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    updateCommit ++ insertCommit
+  }
+
+  private def targetRelatedSplits(sparkSession: SparkSession): Seq[DataSplit] = {
+    val mergeFields = extractFields(matchedCondition)
+    val mergeFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+    val mergeFieldsOnSource =
+      mergeFields.filter(field => sourceTable.output.exists(attr => attr.equals(field)))
+
+    val targetDss = createDataset(
+      sparkSession,
+      targetRelation.copy(

Review Comment:
   Why need this copy



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/util/ScanPlanHelper.scala:
##########
@@ -38,17 +38,22 @@ trait ScanPlanHelper extends SQLConfHelper {
       dataSplits: Seq[DataSplit],
       relation: DataSourceV2Relation,
       condition: Option[Expression] = None): LogicalPlan = {
-    val newRelation = relation.table match {
+    val newRelation = createNewPlan(dataSplits, relation)
+    condition match {
+      case Some(c) if c != TrueLiteral => Filter(c, newRelation)
+      case _ => newRelation
+    }
+  }
+
+  def createNewPlan(

Review Comment:
   Why split them, we already have default value in createNewScanPlan's condicttion



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2287189178


##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {

Review Comment:
   Fixec



##########
paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/RowLineageTestBase.scala:
##########
@@ -198,6 +198,68 @@ abstract class RowLineageTestBase extends PaimonSparkTestBase {
     }
   }
 
+  test("Row Lineage: merge into table with with data-evolution") {
+    if (gteqSpark3_5) {
+      withTable("s", "t") {
+        sql("CREATE TABLE s (id INT, b INT) TBLPROPERTIES ('row-tracking.enabled' = 'true')")
+        sql("INSERT INTO s VALUES (1, 11), (2, 22)")
+
+        sql(
+          "CREATE TABLE t (id INT, b INT, c INT) TBLPROPERTIES ('row-tracking.enabled' = 'true', 'data-evolution.enabled' = 'true')")
+        sql("INSERT INTO t SELECT /*+ REPARTITION(1) */ id, id AS b, id AS c FROM range(2, 4)")
+
+        sql("""
+              |MERGE INTO t
+              |USING s
+              |ON t.id = s.id
+              |WHEN MATCHED THEN UPDATE SET t.b = s.b
+              |WHEN NOT MATCHED THEN INSERT (id, b, c) VALUES (id, b, 11)
+              |""".stripMargin)
+        checkAnswer(
+          sql("SELECT *, _ROW_ID, _SEQUENCE_NUMBER FROM t ORDER BY id"),
+          Seq(Row(1, 11, 11, 2, 2), Row(2, 22, 2, 0, 2), Row(3, 3, 3, 1, 2))
+        )
+      }
+    }
+  }
+
+  test("Row Lineage: merge into table with with data-evolution complex") {

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP][core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2284292272


##########
paimon-api/src/main/java/org/apache/paimon/table/SpecialFields.java:
##########
@@ -93,15 +94,22 @@ public class SpecialFields {
     public static final DataField ROW_ID =
             new DataField(Integer.MAX_VALUE - 5, "_ROW_ID", DataTypes.BIGINT());
 
+    public static final DataField FIRST_ROW_ID =

Review Comment:
   OK



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "leaves12138 (via GitHub)" <gi...@apache.org>.
leaves12138 commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2286866688


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/MergeIntoPaimonDataEvolutionTable.scala:
##########
@@ -0,0 +1,347 @@
+/*
+ * 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.paimon.spark.SparkTable
+import org.apache.paimon.spark.catalyst.analysis.PaimonRelation
+import org.apache.paimon.spark.leafnode.PaimonLeafRunnableCommand
+import org.apache.paimon.spark.schema.PaimonMetadataColumn
+import org.apache.paimon.spark.schema.PaimonMetadataColumn.FILE_PATH_COLUMN
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink.CommitMessage
+import org.apache.paimon.table.source.DataSplit
+
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
+import org.apache.spark.sql.PaimonUtils._
+import org.apache.spark.sql.catalyst.analysis.SimpleAnalyzer.resolver
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, Expression}
+import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, TrueLiteral}
+import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.plans.logical.MergeRows.Keep
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.types.StructType
+
+import scala.collection.JavaConverters._
+import scala.collection.Searching.{search, Found, InsertionPoint}
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/** Command for Merge Into for Data Evolution paimom table. */
+case class MergeIntoPaimonDataEvolutionTable(
+    v2Table: SparkTable,
+    targetTable: LogicalPlan,
+    sourceTable: LogicalPlan,
+    matchedCondition: Expression,
+    matchedActions: Seq[MergeAction],
+    notMatchedActions: Seq[MergeAction],
+    notMatchedBySourceActions: Seq[MergeAction])
+  extends PaimonLeafRunnableCommand
+  with PaimonRowLevelCommand {
+
+  assert(
+    notMatchedBySourceActions.isEmpty,
+    "notMatchedBySourceActions is not supported in MergeIntoPaimonDataEvolutionTable.")
+  assert(
+    matchedActions.forall(x => x.isInstanceOf[UpdateAction]),
+    "Only SET clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN MATCHED.")
+  assert(
+    notMatchedActions.forall(x => x.isInstanceOf[InsertAction]),
+    "Only INSERT clause is supported in MergeIntoPaimonDataEvolutionTable for SQL: WHEN NOT MATCHED."
+  )
+
+  import MergeIntoPaimonDataEvolutionTable._
+
+  override val table: FileStoreTable = v2Table.getTable.asInstanceOf[FileStoreTable]
+  private val firstRowIds: Seq[Long] = table
+    .newSnapshotReader()
+    .withManifestEntryFilter(entry => entry.file().firstRowId() != null)
+    .read()
+    .splits()
+    .asScala
+    .map(_.asInstanceOf[DataSplit])
+    .flatMap(split => split.dataFiles().asScala.map(s => s.firstRowId().asInstanceOf[Long]))
+    .distinct
+    .sorted
+    .toSeq
+
+  lazy val targetRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(targetTable)
+  lazy val sourceRelation: DataSourceV2Relation = PaimonRelation.getPaimonRelation(sourceTable)
+
+  lazy val tableSchema: StructType = v2Table.schema
+
+  override def run(sparkSession: SparkSession): Seq[Row] = {
+    // Avoid that more than one source rows match the same target row.
+    val commitMessages = invokeMergeInto(sparkSession)
+    writer.commit(commitMessages.toSeq)
+    Seq.empty[Row]
+  }
+
+  private def invokeMergeInto(sparkSession: SparkSession): Seq[CommitMessage] = {
+    // step 1: find the related data split, make it target file plan
+    val dataSplits: Seq[DataSplit] = targetRelatedSplits(sparkSession)
+    val touchedFileTargetRelation =
+      createNewPlan(dataSplits.toSeq, targetRelation)
+
+    // step 2: invoke update action
+    val updateCommit =
+      if (matchedActions.nonEmpty)
+        updateActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    // step 3: invoke insert action
+    val insertCommit =
+      if (notMatchedActions.nonEmpty)
+        insertActionInvoke(sparkSession, touchedFileTargetRelation)
+      else Nil
+
+    updateCommit ++ insertCommit
+  }
+
+  private def targetRelatedSplits(sparkSession: SparkSession): Seq[DataSplit] = {
+    val mergeFields = extractFields(matchedCondition)
+    val mergeFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+    val mergeFieldsOnSource =
+      mergeFields.filter(field => sourceTable.output.exists(attr => attr.equals(field)))
+
+    val targetDss = createDataset(
+      sparkSession,
+      targetRelation.copy(
+        targetRelation.table,
+        mergeFieldsOnTarget.toSeq
+      ))
+
+    val sourceDss = createDataset(
+      sparkSession,
+      sourceRelation.copy(
+        sourceRelation.table,
+        mergeFieldsOnSource.toSeq
+      ))
+
+    val firstRowIdsTouched = mutable.Set.empty[Long]
+
+    firstRowIdsTouched ++= findRelatedFirstRowIds(
+      targetDss.alias("_left").join(sourceDss, toColumn(matchedCondition), "inner"),
+      sparkSession,
+      "_left." + ROW_ID_NAME)
+
+    table
+      .newSnapshotReader()
+      .withManifestEntryFilter(
+        entry =>
+          entry.file().firstRowId() != null && firstRowIdsTouched.contains(
+            entry.file().firstRowId()))
+      .read()
+      .splits()
+      .asScala
+      .map(_.asInstanceOf[DataSplit])
+      .toSeq
+  }
+
+  private def updateActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allFields = mutable.SortedSet.empty[AttributeReference](
+      (o1, o2) => {
+        o1.toString().compareTo(o2.toString())
+      }) ++ mergeFields
+    val updateColumns = mutable.Set[AttributeReference]()
+    for (action <- matchedActions) {
+      action match {
+        case updateAction: UpdateAction =>
+          for (assignment <- updateAction.assignments) {
+            if (!assignment.key.equals(assignment.value)) {
+              val key = assignment.key.asInstanceOf[AttributeReference]
+              updateColumns ++= Seq(key)
+            }
+          }
+      }
+    }
+
+    val updateColumnsSorted = updateColumns.toSeq.sortBy(
+      s => targetTable.output.map(x => x.toString()).indexOf(s.toString()))
+
+    val assignments = redundantColumns.map(column => Assignment(column, column))
+    val output = updateColumnsSorted ++ redundantColumns
+    val realUpdateActions = matchedActions
+      .map(s => s.asInstanceOf[UpdateAction])
+      .map(
+        update =>
+          UpdateAction.apply(
+            update.condition,
+            update.assignments.filter(
+              a =>
+                updateColumnsSorted.contains(
+                  a.key.asInstanceOf[AttributeReference])) ++ assignments))
+
+    for (action <- realUpdateActions) {
+      allFields ++= action.references.flatMap(r => extractFields(r)).seq
+    }
+
+    val allReadFieldsOnTarget = allFields.filter(
+      field =>
+        targetTable.output.exists(
+          attr => attr.toString().equals(field.toString()))) ++ redundantColumns
+    val allReadFieldsOnSource = allFields.filter(
+      field => sourceTable.output.exists(attr => attr.toString().equals(field.toString())))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+    val targetTableProjExprs = targetReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_TARGET)()
+    val targetTableProj = Project(targetTableProjExprs, targetReadPlan)
+
+    val sourceReadPlan = sourceRelation.copy(sourceRelation.table, allReadFieldsOnSource.toSeq)
+    val sourceTableProjExprs = sourceReadPlan.output :+ Alias(TrueLiteral, ROW_FROM_SOURCE)()
+    val sourceTableProj = Project(sourceTableProjExprs, sourceReadPlan)
+
+    val joinPlan =
+      Join(targetTableProj, sourceTableProj, LeftOuter, Some(matchedCondition), JoinHint.NONE)
+
+    val rowFromSourceAttr = attribute(ROW_FROM_SOURCE, joinPlan)
+    val rowFromTargetAttr = attribute(ROW_FROM_TARGET, joinPlan)
+
+    val mergeRows = MergeRows(
+      isSourceRowPresent = rowFromSourceAttr,
+      isTargetRowPresent = rowFromTargetAttr,
+      matchedInstructions = realUpdateActions
+        .map(
+          action => {
+            Keep(action.condition.getOrElse(TrueLiteral), action.assignments.map(a => a.value))
+          }) ++ Seq(Keep(TrueLiteral, output)),
+      notMatchedInstructions = Nil,
+      notMatchedBySourceInstructions = Seq(Keep(TrueLiteral, output)).toSeq,
+      checkCardinality = false,
+      output = output,
+      child = joinPlan
+    )
+
+    val firstRowIdsFinal = firstRowIds
+    val firstRowIdUdf = udf((rowId: Long) => floorBinarySearch(firstRowIdsFinal, rowId))
+    val firstRowIdColumn = firstRowIdUdf(col(ROW_ID_NAME))
+    val toWrite =
+      createDataset(sparkSession, mergeRows).withColumn(FIRST_ROW_ID_NAME, firstRowIdColumn)
+    assert(toWrite.schema.fields.length == updateColumnsSorted.size + 2)
+    val sortedDs = toWrite
+      .repartitionByRange(firstRowIdColumn)
+      .sortWithinPartitions(FIRST_ROW_ID_NAME, ROW_ID_NAME)
+    val writer0 = writer.withDataEvolutionMergeWrite(updateColumnsSorted.map(_.name))
+    writer0.write(sortedDs)
+  }
+
+  private def insertActionInvoke(
+      sparkSession: SparkSession,
+      touchedFileTargetRelation: DataSourceV2Relation): Seq[CommitMessage] = {
+    val mergeFields = extractFields(matchedCondition)
+    val allReadFieldsOnTarget =
+      mergeFields.filter(field => targetTable.output.exists(attr => attr.equals(field)))
+
+    val targetReadPlan =
+      touchedFileTargetRelation.copy(targetRelation.table, allReadFieldsOnTarget.toSeq)
+
+    val joinPlan =
+      Join(sourceRelation, targetReadPlan, LeftAnti, Some(matchedCondition), JoinHint.NONE)
+
+    // merge rows as there are multiple not matched actions
+    val mergeRows = MergeRows(
+      isSourceRowPresent = TrueLiteral,
+      isTargetRowPresent = FalseLiteral,
+      matchedInstructions = Nil,
+      notMatchedInstructions = notMatchedActions.map {
+        case insertAction: InsertAction =>
+          Keep(
+            insertAction.condition.getOrElse(TrueLiteral),
+            insertAction.assignments.map(a => a.value))
+      }.toSeq,
+      notMatchedBySourceInstructions = Nil,
+      checkCardinality = false,
+      output = targetTable.output,
+      child = joinPlan
+    )
+
+    val toWrite = createDataset(sparkSession, mergeRows)
+    val writer0 = writer.disableDataEvolutionMergeWrite()
+    writer0.write(toWrite)
+  }
+
+  private def findRelatedFirstRowIds(
+      dataset: Dataset[Row],
+      sparkSession: SparkSession,
+      identifier: String = FILE_PATH_COLUMN): Array[Long] = {

Review Comment:
   My bad



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on PR #6091:
URL: https://github.com/apache/paimon/pull/6091#issuecomment-3204259651

   Please add documentation too. Maybe just in row tracking doc.


-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [core][spark] Support add partial column by spark MERGE INTO clause for data-evolution table [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #6091:
URL: https://github.com/apache/paimon/pull/6091#discussion_r2289791233


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/commands/DataEvolutionPaimonWriter.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.paimon.CoreOptions
+import org.apache.paimon.data.BinaryRow
+import org.apache.paimon.spark.DataEvolutionSparkTableWrite
+import org.apache.paimon.spark.commands.DataEvolutionPaimonWriter.{deserializeCommitMessage, dynamicOp}
+import org.apache.paimon.spark.write.WriteHelper
+import org.apache.paimon.table.FileStoreTable
+import org.apache.paimon.table.sink._
+
+import org.apache.spark.sql._
+
+import java.io.IOException
+import java.util.Collections
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+case class DataEvolutionPaimonWriter(paimonTable: FileStoreTable) extends WriteHelper {
+
+  private lazy val firstRowIdToPartitionMap: mutable.HashMap[Long, Tuple2[BinaryRow, Long]] =
+    initPartitionMap()
+  private lazy val normalWrite = PaimonSparkWriter(paimonTable)
+  override val table: FileStoreTable = paimonTable.copy(dynamicOp)

Review Comment:
   Copy dynamic options here, but use `paimonTable` to create `normalWrite`? Can you add a test for not split file in writing?



-- 
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: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org