danny0405 commented on code in PR #20784:
URL: https://github.com/apache/hudi/pull/20784#discussion_r4694846827


##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/catalog/TestHoodieCatalogDDL.scala:
##########
@@ -492,6 +677,49 @@ class TestHoodieCatalogDDL extends HoodieSparkSqlTestBase {
     }
   }
 
+  test("alterTable accepts the full CREATE property set after upgrading a 
legacy precombine table") {
+    withTempDir { tmp =>
+      val fixture = "hudi-v6-table-complex-keygen"
+      
HoodieTestUtils.extractZipToDirectory(s"$COMPLEX_KEYGEN_FIXTURES_PATH$fixture.zip",
 tmp.toPath, getClass)
+      val path = tmp.toPath.resolve(fixture)
+      val name = generateTableName
+      val ident = Identifier.of(Array("default"), name)
+      val tableIdent = TableIdentifier(name, Some("default"))
+      val props = Map(
+        "provider" -> "hudi", "location" -> path.toString, "type" -> "mor", 
"primaryKey" -> "id",
+        "preCombineField" -> "ts", HoodieTableConfig.PRECOMBINE_FIELD.key -> 
"ts",
+        "hoodie.datasource.write.partitionpath.field" -> "partition,category",
+        "hoodie.datasource.write.keygenerator.class" -> 
KeyGeneratorType.COMPLEX.getClassName,
+        "payloadClass" -> classOf[OverwriteWithLatestAvroPayload].getName,
+        "recordMergeMode" -> "EVENT_TIME_ORDERING")
+      hoodieCatalog.createTable(ident, new StructType(), 
Array.empty[Transform], props.asJava)
+      try {
+        val legacy = HoodieCatalogTable(spark, tableIdent).tableConfig
+        assertEquals(HoodieTableVersion.SIX, legacy.getTableVersion)
+        assertEquals("ts", 
legacy.getProps.getProperty(HoodieTableConfig.PRECOMBINE_FIELD.key))
+        
assertFalse(legacy.getProps.containsKey(HoodieTableConfig.ORDERING_FIELDS.key))
+
+        val target = HoodieTableVersion.current()
+        checkAnswer(s"CALL upgrade_table(table => '$name', to_version => 
'${target.name()}')")(Seq(true))

Review Comment:
   The regression uses a Hudi 0.14.0 MOR fixture and runs the actual v6-to-v10 
upgrade. It re-sends every property used to register the table, including both 
precombine spellings and the original payload class. This caught a second 
representation change: the upgrade stores the payload under the legacy key. The 
catalog now uses the writer’s lookup. The test checks both the catalog entry 
and the bytes of `hoodie.properties` and rejects a different payload class.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/catalog/HoodieCatalog.scala:
##########
@@ -360,6 +368,26 @@ class HoodieCatalog extends DelegatingCatalogExtension
     }
   }
 
+  private def partitionPropertyMatches(table: HoodieCatalogTable, key: String, 
value: String): Boolean = {
+    val config = table.tableConfig
+    val persisted = 
HoodieTableConfig.getPartitionFieldPropForKeyGenerator(config).orElse("")
+    val writeKey = DataSourceWriteOptions.PARTITIONPATH_FIELD.key
+    val legacyCustomWriteOption = key == writeKey && persisted.nonEmpty &&

Review Comment:
   On v6, the writer stores `part` and omits the partition type. The catalog 
now accepts a replay of `part:simple` only when the typed option matches the 
registered CREATE value and the parsed field names match disk in order. When 
disk contains the types, as on v8, it supplies the complete comparison. The COW 
and MOR tests on both versions check replay, a different field, a changed or 
removed type, and stale catalog values.



##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/catalog/TestHoodieCatalogDDL.scala:
##########
@@ -295,6 +348,138 @@ class TestHoodieCatalogDDL extends HoodieSparkSqlTestBase 
{
     }
   }
 
+  for (tableType <- Seq("cow", "mor"); version <- Seq("6", "8")) {
+    test(s"alterTable protects partition and key-generator aliases: $tableType 
version $version") {
+      withTempDir { tmp =>
+        val catalog = hoodieCatalog
+        val name = generateTableName
+        val ident = Identifier.of(Array("default"), name)
+        val tableIdent = TableIdentifier(name, Some("default"))
+        val path = s"${tmp.getCanonicalPath}/$name"
+        val classKey = "hoodie.datasource.write.keygenerator.class"
+        val typeKey = "hoodie.datasource.write.keygenerator.type"
+        val partitionKey = "hoodie.datasource.write.partitionpath.field"
+        val aliases = Map(classKey -> KeyGeneratorType.SIMPLE.getClassName, 
typeKey -> "SIMPLE", partitionKey -> "part")
+        catalog.createTable(ident,
+          StructType(Seq(StructField("id", IntegerType), StructField("ts", 
LongType), StructField("part", StringType))),
+          Array[Transform](Expressions.identity("part")),
+          (aliases ++ Map("provider" -> "hudi", "primaryKey" -> "id", 
"preCombineField" -> "ts",
+            "type" -> tableType, "hoodie.write.table.version" -> version, 
"location" -> path)).asJava)
+        try {
+          spark.sql(s"INSERT INTO $name VALUES (1, 1L, 'a')")
+          val session = spark.sessionState.catalog
+          val before = session.getTableMetadata(tableIdent)
+          val schemaBefore = catalog.loadTable(ident).schema()
+          val propertiesFile = new 
File(s"$path/.hoodie/hoodie.properties").toPath
+          val persistedBefore = Files.readAllBytes(propertiesFile).toSeq
+          val config = HoodieCatalogTable(spark, before).tableConfig
+          assertEquals(version.toInt, config.getTableVersion.versionCode())
+          assertEquals(KeyGeneratorType.SIMPLE.getClassName, 
config.getKeyGeneratorClassName)
+          (1 to 3).foreach { _ =>
+            catalog.alterTable(ident, (aliases ++ Map(
+              typeKey -> "simple",
+              HoodieTableConfig.PARTITION_FIELDS.key -> "part",
+              HoodieTableConfig.KEY_GENERATOR_CLASS_NAME.key -> 
KeyGeneratorType.SIMPLE.getClassName,
+              HoodieTableConfig.KEY_GENERATOR_TYPE.key -> "SIMPLE")).toSeq.map 
{
+              case (key, value) => TableChange.setProperty(key, value)
+            }: _*)
+          }
+          assertEquals(before, session.getTableMetadata(tableIdent))
+
+          val changes = Seq(
+            TableChange.setProperty(classKey, 
KeyGeneratorType.COMPLEX.getClassName),
+            TableChange.setProperty(classKey, 
KeyGeneratorType.SIMPLE.getClassName.toUpperCase(Locale.ROOT)),
+            TableChange.setProperty(typeKey, "COMPLEX"),
+            TableChange.setProperty(partitionKey, "id")) ++ 
aliases.keys.toSeq.map(TableChange.removeProperty)
+          changes.foreach { change =>
+            val error = intercept[HoodieAnalysisException] {
+              catalog.alterTable(ident, TableChange.setProperty("some.key", 
"changed"),
+                TableChange.addColumn(Array("added"), StringType), change)
+            }
+            assertTrue(error.getMessage.contains("hoodie.properties"), 
error.getMessage)
+            assertEquals(before, session.getTableMetadata(tableIdent))
+            assertEquals(schemaBefore, catalog.loadTable(ident).schema())
+            assertEquals(persistedBefore, 
Files.readAllBytes(propertiesFile).toSeq)
+          }
+
+          // An old catalog entry may already disagree with the persisted 
table. Re-sending it is not a safe no-op.
+          session.alterTable(before.copy(properties = before.properties + 
(partitionKey -> "id")))
+          try {
+            intercept[HoodieAnalysisException] {
+              catalog.alterTable(ident, TableChange.setProperty(partitionKey, 
"id"))
+            }
+          } finally {
+            session.alterTable(before)
+          }
+          assertEquals(persistedBefore, 
Files.readAllBytes(propertiesFile).toSeq)
+          spark.sql(s"INSERT INTO $name VALUES (2, 2L, 'b')")
+          checkAnswer(s"SELECT id, ts, part FROM $name ORDER BY id")(Seq(1, 
1L, "a"), Seq(2, 2L, "b"))
+        } finally {
+          catalog.dropTable(ident)
+        }
+      }
+    }
+  }
+
+  test("alterTable accepts equivalent Spark and Avro key generators") {

Review Comment:
   This exercises both Simple and Complex Avro generators through CREATE and 
ALTER. It verifies the Avro type on disk, replays the original properties, 
accepts the corresponding Spark aliases, and rejects an unrelated generator. 
The comparison uses the same Avro-to-Spark mapping as `HoodieCatalogTable`. 
User-provided class names still compare exactly.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/HoodieOptionConfig.scala:
##########
@@ -206,26 +218,49 @@ object HoodieOptionConfig {
   }
 
   /**
-   * Map a SQL option, data source write config or table config, given by key 
and value, to the table config
-   * it is persisted as in hoodie.properties. Returns None if it is not 
persisted as a table config.
+   * Map a SQL option, data source write config or table config to its 
persisted key and a value normalized
+   * for comparison with hoodie.properties. Returns None for properties 
outside the table config.
    */
   def mapToTableConfig(key: String, value: String): Option[(String, String)] = 
{
     val sqlKey = writeConfigKeyToSqlOptionKey.getOrElse(key, 
canonicalizeSqlOptionKey(key))
-    
sqlOptionKeyToTableConfigKey.get(sqlKey).orElse(tableConfigKeys.get(key)).map { 
tableKey =>
+    
sqlOptionKeyToTableConfigKey.get(sqlKey).orElse(identityWriteConfigKeys.get(key)).orElse(tableConfigKeys.get(key)).map
 { tableKey =>
       val tableValue = if (tableKey == HoodieTableConfig.TYPE.key) {
         
sqlOptionValueToHoodieConfigValue.getOrElse(value.toLowerCase(Locale.ROOT), 
value.toUpperCase(Locale.ROOT))
+      } else if (tableKey == HoodieTableConfig.KEY_GENERATOR_CLASS_NAME.key) {
+        convertToSparkKeyGenerator(value)
+      } else if (tableKey == HoodieTableConfig.KEY_GENERATOR_TYPE.key) {
+        val typeName = value.toUpperCase(Locale.ROOT)
+        sparkKeyGeneratorTypes.getOrElse(typeName, typeName)
       } else {
         value
       }
       tableKey -> tableValue
     }
   }
 
-  /** Read a persisted value using its declared alternative keys and the same 
conversion as incoming options. */
+  /** Resolve both representations from the persisted generator, using the 
same Avro conversions as the catalog. */
+  private def keyGeneratorConfig(tableConfig: HoodieTableConfig): Map[String, 
String] =

Review Comment:
   Extracted `keyGeneratorConfig` to resolve the Spark class and type together 
from the persisted generator. Both lookups now use that helper, including when 
the table stores just one representation.



-- 
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