yihua commented on code in PR #20895:
URL: https://github.com/apache/hudi/pull/20895#discussion_r4702875641


##########
hudi-spark-datasource/hudi-spark3-common/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala:
##########
@@ -318,20 +318,99 @@ case class MergeIntoHoodieTableCommand(mergeInto: 
MergeIntoTable) extends Hoodie
 
   override def run(sparkSession: SparkSession): Seq[Row] = {
     this.sparkSession = sparkSession
-    // TODO move to analysis phase
-    // Create the write parameters
-    val props = buildMergeIntoConfig(hoodieCatalogTable)
-    validate(props)
-
-    val processedInputDf: DataFrame = getProcessedInputDf(props)
-    // Do the upsert
-    executeUpsert(processedInputDf, props)
-    // Refresh the table in the catalog
-    sparkSession.catalog.refreshTable(hoodieCatalogTable.table.qualifiedName)
+    if (hasPrimaryKey() && matchesNoRecord && indexFindsEveryKey) {
+      insertSourceRecords()
+    } else {
+      // TODO move to analysis phase
+      // Create the write parameters
+      val props = buildMergeIntoConfig(hoodieCatalogTable)
+      validate(props)
+
+      val processedInputDf: DataFrame = getProcessedInputDf(props)
+      // Do the upsert
+      executeUpsert(processedInputDf, props)
+      // Refresh the table in the catalog
+      sparkSession.catalog.refreshTable(hoodieCatalogTable.table.qualifiedName)
+    }
 
     Seq.empty[Row]
   }
 
+  /**
+   * Whether the merge condition is always false, so that no source record 
matches a record of the table.
+   */
+  private lazy val matchesNoRecord: Boolean = 
mergeInto.mergeCondition.foldable &&
+    
Try(mergeInto.mergeCondition.eval()).toOption.contains(java.lang.Boolean.FALSE)
+
+  /**
+   * Whether the index finds every record key the table holds, so that the 
insert of a statement whose merge
+   * condition matches no record can fail on a key the table already has: a 
record-level index, or a non-bucket
+   * index of a copy-on-write table, whose keys are all in base files.
+   */
+  private lazy val indexFindsEveryKey: Boolean = {
+    val indexType = combineOptions(hoodieCatalogTable, 
hoodieCatalogTable.tableConfig, sparkSession.sessionState.conf,
+      defaultOpts = Map.empty).getOrElse(HoodieIndexConfig.INDEX_TYPE.key, 
HoodieIndex.IndexType.SIMPLE.name)
+    def isOneOf(types: HoodieIndex.IndexType*): Boolean = 
types.exists(_.name.equalsIgnoreCase(indexType))
+    isOneOf(HoodieIndex.IndexType.RECORD_INDEX, 
HoodieIndex.IndexType.GLOBAL_RECORD_LEVEL_INDEX,
+      HoodieIndex.IndexType.RECORD_LEVEL_INDEX) ||
+      (targetTableType == COW_TABLE_TYPE_OPT_VAL && 
isOneOf(HoodieIndex.IndexType.SIMPLE, HoodieIndex.IndexType.BLOOM,
+        HoodieIndex.IndexType.GLOBAL_SIMPLE, 
HoodieIndex.IndexType.GLOBAL_BLOOM))
+  }
+
+  /**
+   * Runs a statement whose merge condition matches no record as the INSERT 
INTO it comes to: the first
+   * not-matched clause that accepts a source record inserts it, and the 
matched clauses apply to no record.
+   * This is how a table with a record key takes such a statement, as its 
merge condition is otherwise an
+   * equality on the record key. The insert fails on a key the table already 
holds, or that more than one
+   * inserted source record carries, as the upsert of a not-matched clause 
never writes a second record for
+   * one key.
+   */
+  private def insertSourceRecords(): Unit = {
+    if (insertingActions.nonEmpty) {
+      checkInsertingActions(insertingActions, 
buildMergeIntoConfig(hoodieCatalogTable))
+      val conditions = 
insertingActions.map(_.condition.getOrElse(Literal.TrueLiteral))
+      val values = insertingActions.map(action =>
+        alignAssignments(action.assignments, 
Some(PartialAssignmentMode.NULL_VALUE), keepUpdatedFieldsOnly = 
false).map(_.value))
+      val output = mergeInto.targetTable.output.filterNot(attr => 
isMetaField(attr.name)).zip(values.transpose).map {
+        case (attr, clauseValues) =>
+          Alias(CaseWhen(conditions.zip(clauseValues.map(castIfNeeded(_, 
attr.dataType)))), attr.name)()
+      }
+      val query = InsertIntoHoodieTableCommand.alignQueryOutput(
+        Project(output, Filter(conditions.reduce(Or), mergeInto.sourceTable)),
+        hoodieCatalogTable, Map.empty, sparkSession.sessionState.conf)
+      val insertedDf = 
sparkAdapter.getUnsafeUtils.createDataFrameFrom(sparkSession, query)
+      failOnRepeatedRecordKey(insertedDf)
+      InsertIntoHoodieTableCommand.run(sparkSession, hoodieCatalogTable.table,
+        insertedDf.queryExecution.executedPlan,
+        Map.empty, overwrite = false, extraOptions = Map(
+          OPERATION.key -> INSERT_OPERATION_OPT_VAL,
+          SPARK_SQL_INSERT_INTO_OPERATION.key -> INSERT_OPERATION_OPT_VAL,
+          INSERT_DUP_POLICY.key -> FAIL_INSERT_DUP_POLICY),
+        metrics = metrics)
+    }
+  }
+
+  /**
+   * Fails on a record key that more than one inserted source record carries. 
The insert checks the keys
+   * against the records the table holds only, so it would write each of these 
records.
+   */
+  private def failOnRepeatedRecordKey(insertedDf: DataFrame): Unit = {
+    val keyFields = hoodieCatalogTable.primaryKeys.toSeq
+    val countField = "__record_key_count"
+    val repeated = insertedDf
+      .where(keyFields.map(field => functions.col(field).isNotNull).reduce(_ 
&& _))
+      .groupBy(keyFields.map(functions.col): _*)

Review Comment:
   Done, the check now runs inside the insert on the keys the key generator 
produces, with composite null and empty keys and -0.0/0.0 covered.



##########
hudi-spark-datasource/hudi-spark3-common/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala:
##########
@@ -318,20 +318,99 @@ case class MergeIntoHoodieTableCommand(mergeInto: 
MergeIntoTable) extends Hoodie
 
   override def run(sparkSession: SparkSession): Seq[Row] = {
     this.sparkSession = sparkSession
-    // TODO move to analysis phase
-    // Create the write parameters
-    val props = buildMergeIntoConfig(hoodieCatalogTable)
-    validate(props)
-
-    val processedInputDf: DataFrame = getProcessedInputDf(props)
-    // Do the upsert
-    executeUpsert(processedInputDf, props)
-    // Refresh the table in the catalog
-    sparkSession.catalog.refreshTable(hoodieCatalogTable.table.qualifiedName)
+    if (hasPrimaryKey() && matchesNoRecord && indexFindsEveryKey) {
+      insertSourceRecords()
+    } else {
+      // TODO move to analysis phase
+      // Create the write parameters
+      val props = buildMergeIntoConfig(hoodieCatalogTable)
+      validate(props)
+
+      val processedInputDf: DataFrame = getProcessedInputDf(props)
+      // Do the upsert
+      executeUpsert(processedInputDf, props)
+      // Refresh the table in the catalog
+      sparkSession.catalog.refreshTable(hoodieCatalogTable.table.qualifiedName)
+    }
 
     Seq.empty[Row]
   }
 
+  /**
+   * Whether the merge condition is always false, so that no source record 
matches a record of the table.
+   */
+  private lazy val matchesNoRecord: Boolean = 
mergeInto.mergeCondition.foldable &&
+    
Try(mergeInto.mergeCondition.eval()).toOption.contains(java.lang.Boolean.FALSE)
+
+  /**
+   * Whether the index finds every record key the table holds, so that the 
insert of a statement whose merge
+   * condition matches no record can fail on a key the table already has: a 
record-level index, or a non-bucket
+   * index of a copy-on-write table, whose keys are all in base files.
+   */
+  private lazy val indexFindsEveryKey: Boolean = {
+    val indexType = combineOptions(hoodieCatalogTable, 
hoodieCatalogTable.tableConfig, sparkSession.sessionState.conf,
+      defaultOpts = Map.empty).getOrElse(HoodieIndexConfig.INDEX_TYPE.key, 
HoodieIndex.IndexType.SIMPLE.name)
+    def isOneOf(types: HoodieIndex.IndexType*): Boolean = 
types.exists(_.name.equalsIgnoreCase(indexType))
+    isOneOf(HoodieIndex.IndexType.RECORD_INDEX, 
HoodieIndex.IndexType.GLOBAL_RECORD_LEVEL_INDEX,
+      HoodieIndex.IndexType.RECORD_LEVEL_INDEX) ||
+      (targetTableType == COW_TABLE_TYPE_OPT_VAL && 
isOneOf(HoodieIndex.IndexType.SIMPLE, HoodieIndex.IndexType.BLOOM,
+        HoodieIndex.IndexType.GLOBAL_SIMPLE, 
HoodieIndex.IndexType.GLOBAL_BLOOM))
+  }
+
+  /**
+   * Runs a statement whose merge condition matches no record as the INSERT 
INTO it comes to: the first
+   * not-matched clause that accepts a source record inserts it, and the 
matched clauses apply to no record.
+   * This is how a table with a record key takes such a statement, as its 
merge condition is otherwise an
+   * equality on the record key. The insert fails on a key the table already 
holds, or that more than one
+   * inserted source record carries, as the upsert of a not-matched clause 
never writes a second record for
+   * one key.
+   */
+  private def insertSourceRecords(): Unit = {
+    if (insertingActions.nonEmpty) {
+      checkInsertingActions(insertingActions, 
buildMergeIntoConfig(hoodieCatalogTable))
+      val conditions = 
insertingActions.map(_.condition.getOrElse(Literal.TrueLiteral))
+      val values = insertingActions.map(action =>
+        alignAssignments(action.assignments, 
Some(PartialAssignmentMode.NULL_VALUE), keepUpdatedFieldsOnly = 
false).map(_.value))
+      val output = mergeInto.targetTable.output.filterNot(attr => 
isMetaField(attr.name)).zip(values.transpose).map {
+        case (attr, clauseValues) =>
+          Alias(CaseWhen(conditions.zip(clauseValues.map(castIfNeeded(_, 
attr.dataType)))), attr.name)()
+      }
+      val query = InsertIntoHoodieTableCommand.alignQueryOutput(
+        Project(output, Filter(conditions.reduce(Or), mergeInto.sourceTable)),
+        hoodieCatalogTable, Map.empty, sparkSession.sessionState.conf)
+      val insertedDf = 
sparkAdapter.getUnsafeUtils.createDataFrameFrom(sparkSession, query)
+      failOnRepeatedRecordKey(insertedDf)
+      InsertIntoHoodieTableCommand.run(sparkSession, hoodieCatalogTable.table,
+        insertedDf.queryExecution.executedPlan,
+        Map.empty, overwrite = false, extraOptions = Map(
+          OPERATION.key -> INSERT_OPERATION_OPT_VAL,
+          SPARK_SQL_INSERT_INTO_OPERATION.key -> INSERT_OPERATION_OPT_VAL,
+          INSERT_DUP_POLICY.key -> FAIL_INSERT_DUP_POLICY),
+        metrics = metrics)
+    }
+  }
+
+  /**
+   * Fails on a record key that more than one inserted source record carries. 
The insert checks the keys
+   * against the records the table holds only, so it would write each of these 
records.
+   */
+  private def failOnRepeatedRecordKey(insertedDf: DataFrame): Unit = {
+    val keyFields = hoodieCatalogTable.primaryKeys.toSeq
+    val countField = "__record_key_count"
+    val repeated = insertedDf
+      .where(keyFields.map(field => functions.col(field).isNotNull).reduce(_ 
&& _))

Review Comment:
   Done, keys are now scoped to the partition unless the index is global, with 
partitioned cases added.



##########
hudi-spark-datasource/hudi-spark3-common/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala:
##########
@@ -318,20 +318,99 @@ case class MergeIntoHoodieTableCommand(mergeInto: 
MergeIntoTable) extends Hoodie
 
   override def run(sparkSession: SparkSession): Seq[Row] = {
     this.sparkSession = sparkSession
-    // TODO move to analysis phase
-    // Create the write parameters
-    val props = buildMergeIntoConfig(hoodieCatalogTable)
-    validate(props)
-
-    val processedInputDf: DataFrame = getProcessedInputDf(props)
-    // Do the upsert
-    executeUpsert(processedInputDf, props)
-    // Refresh the table in the catalog
-    sparkSession.catalog.refreshTable(hoodieCatalogTable.table.qualifiedName)
+    if (hasPrimaryKey() && matchesNoRecord && indexFindsEveryKey) {
+      insertSourceRecords()
+    } else {
+      // TODO move to analysis phase
+      // Create the write parameters
+      val props = buildMergeIntoConfig(hoodieCatalogTable)
+      validate(props)
+
+      val processedInputDf: DataFrame = getProcessedInputDf(props)
+      // Do the upsert
+      executeUpsert(processedInputDf, props)
+      // Refresh the table in the catalog
+      sparkSession.catalog.refreshTable(hoodieCatalogTable.table.qualifiedName)
+    }
 
     Seq.empty[Row]
   }
 
+  /**
+   * Whether the merge condition is always false, so that no source record 
matches a record of the table.
+   */
+  private lazy val matchesNoRecord: Boolean = 
mergeInto.mergeCondition.foldable &&
+    
Try(mergeInto.mergeCondition.eval()).toOption.contains(java.lang.Boolean.FALSE)
+
+  /**
+   * Whether the index finds every record key the table holds, so that the 
insert of a statement whose merge
+   * condition matches no record can fail on a key the table already has: a 
record-level index, or a non-bucket
+   * index of a copy-on-write table, whose keys are all in base files.
+   */
+  private lazy val indexFindsEveryKey: Boolean = {
+    val indexType = combineOptions(hoodieCatalogTable, 
hoodieCatalogTable.tableConfig, sparkSession.sessionState.conf,
+      defaultOpts = Map.empty).getOrElse(HoodieIndexConfig.INDEX_TYPE.key, 
HoodieIndex.IndexType.SIMPLE.name)
+    def isOneOf(types: HoodieIndex.IndexType*): Boolean = 
types.exists(_.name.equalsIgnoreCase(indexType))
+    isOneOf(HoodieIndex.IndexType.RECORD_INDEX, 
HoodieIndex.IndexType.GLOBAL_RECORD_LEVEL_INDEX,

Review Comment:
   Done, on a merge-on-read table the record level index must be built, and the 
write fails if it is no longer available once the commit starts. An index class 
is refused too.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to