voonhous commented on code in PR #20895:
URL: https://github.com/apache/hudi/pull/20895#discussion_r4696525863
##########
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:
**blocker:** On a partitioned COW table with the default SIMPLE index,
source rows `(3,'p1')` and `(3,'p2')` with `ON false` fail with "Duplicate key
found ... key is: 3", while `ON t.id = s.id` and an INSERT INTO with the fail
policy both write the two rows, since a non-global index keys a record by
partition too. Could the grouping include the partition path when the index is
not global, with a partitioned table added to the test?
##########
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:
**blocker:** Beyond the NULL case reported above, grouping raw key columns
differs from the writer's record keys in other ways: with
`primaryKey='id,part'`, source rows `('a','')` and `('a','__empty__')` are both
written with key `id:a,part:__empty__`, and a double key with `-0.0` and `0.0`
is rejected while a plain INSERT with the fail policy writes both. Could the
check run on the keys the key generator produces, ideally inside the write?
##########
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:
**blocker:** This passes for `hoodie.index.type=RECORD_INDEX` even when the
record index partition was never initialized; the lookup then falls back to a
simple index over base files, which is the MOR case refused below. On a MOR
table with id 2 only in a log file, `ON false ... insert *` with id 2 succeeded
and left two rows for id 2. Could the record-index arm also require
`tableConfig.isMetadataPartitionAvailable(RECORD_INDEX)`?
--
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]