This is an automated email from the ASF dual-hosted git repository.

huaxingao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/main by this push:
     new d5d7bf885f Core: Keep all per-column properties in sync on schema 
changes (#18885)
d5d7bf885f is described below

commit d5d7bf885fb9da5dafb747d7aec74a246ed68aa1
Author: drexler-sky <[email protected]>
AuthorDate: Wed Nov 18 09:50:13 2026 -0800

    Core: Keep all per-column properties in sync on schema changes (#18885)
    
    * Core: Keep all per-column properties in sync on schema changes
    
    * address review comments
    
    * address comments
    
    * address comments
    
    * simplify java doc
---
 .../main/java/org/apache/iceberg/SchemaUpdate.java | 26 ++-------
 .../java/org/apache/iceberg/TableProperties.java   | 17 ++++++
 .../java/org/apache/iceberg/util/PropertyUtil.java | 51 ++++++++++++++++++
 .../apache/iceberg/TestSchemaAndMappingUpdate.java | 62 +++++++++++-----------
 .../org/apache/iceberg/util/TestPropertyUtil.java  | 48 +++++++++++++++++
 .../org/apache/iceberg/spark/SparkCatalog.java     | 37 ++-----------
 6 files changed, 155 insertions(+), 86 deletions(-)

diff --git a/core/src/main/java/org/apache/iceberg/SchemaUpdate.java 
b/core/src/main/java/org/apache/iceberg/SchemaUpdate.java
index 0aed742f70..8d4c1ede64 100644
--- a/core/src/main/java/org/apache/iceberg/SchemaUpdate.java
+++ b/core/src/main/java/org/apache/iceberg/SchemaUpdate.java
@@ -32,7 +32,6 @@ import org.apache.iceberg.mapping.NameMapping;
 import org.apache.iceberg.mapping.NameMappingParser;
 import 
org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
 import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
-import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
 import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
 import org.apache.iceberg.relocated.com.google.common.collect.Lists;
 import org.apache.iceberg.relocated.com.google.common.collect.Maps;
@@ -504,27 +503,12 @@ class SchemaUpdate implements UpdateSchema {
       }
     }
 
-    // Transform the metrics if they exist
+    // Keep name-keyed per-column properties in sync
     if (base != null && base.properties() != null) {
-      Schema newSchema = newMetadata.schema();
-      List<String> deletedColumns =
-          
deletes.stream().map(schema::findColumnName).collect(Collectors.toList());
-      Map<String, String> renamedColumns =
-          updates.keySet().stream()
-              .filter(id -> !addedNameToId.containsValue(id)) // remove added 
columns
-              .filter(id -> 
!schema.findColumnName(id).equals(newSchema.findColumnName(id)))
-              .collect(Collectors.toMap(schema::findColumnName, 
newSchema::findColumnName));
-      if (!deletedColumns.isEmpty() || !renamedColumns.isEmpty()) {
-        Set<String> columnProperties =
-            ImmutableSet.of(
-                TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX,
-                TableProperties.PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX,
-                TableProperties.PARQUET_COLUMN_STATS_ENABLED_PREFIX,
-                TableProperties.PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX,
-                TableProperties.PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX);
-        Map<String, String> updatedProperties =
-            PropertyUtil.applySchemaChanges(
-                newMetadata.properties(), deletedColumns, renamedColumns, 
columnProperties);
+      Map<String, String> properties = newMetadata.properties();
+      Map<String, String> updatedProperties =
+          PropertyUtil.applySchemaChanges(properties, schema, 
newMetadata.schema());
+      if (updatedProperties != properties) {
         newMetadata = newMetadata.replaceProperties(updatedProperties);
       }
     }
diff --git a/core/src/main/java/org/apache/iceberg/TableProperties.java 
b/core/src/main/java/org/apache/iceberg/TableProperties.java
index da542dacca..ae02b199f3 100644
--- a/core/src/main/java/org/apache/iceberg/TableProperties.java
+++ b/core/src/main/java/org/apache/iceberg/TableProperties.java
@@ -346,6 +346,23 @@ public class TableProperties {
   public static final String DEFAULT_WRITE_METRICS_MODE = 
"write.metadata.metrics.default";
   public static final String DEFAULT_WRITE_METRICS_MODE_DEFAULT = 
"truncate(16)";
 
+  /**
+   * Prefixes of table properties that are keyed by column name.
+   *
+   * <p>Properties with these prefixes are renamed or removed when the column 
is renamed or dropped.
+   * New per-column properties must be added to this set.
+   */
+  public static final Set<String> COLUMN_PROPERTY_PREFIXES =
+      ImmutableSet.of(
+          METRICS_MODE_COLUMN_CONF_PREFIX,
+          PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX,
+          PARQUET_BLOOM_FILTER_COLUMN_FPP_PREFIX,
+          PARQUET_BLOOM_FILTER_COLUMN_NDV_PREFIX,
+          PARQUET_COLUMN_STATS_ENABLED_PREFIX,
+          PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX,
+          PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX,
+          PARQUET_DICT_ENCODING_ENABLED_COLUMN_PREFIX);
+
   public static final String DEFAULT_NAME_MAPPING = 
"schema.name-mapping.default";
 
   public static final String WRITE_AUDIT_PUBLISH_ENABLED = "write.wap.enabled";
diff --git a/core/src/main/java/org/apache/iceberg/util/PropertyUtil.java 
b/core/src/main/java/org/apache/iceberg/util/PropertyUtil.java
index b82e5ed275..fa5f13768a 100644
--- a/core/src/main/java/org/apache/iceberg/util/PropertyUtil.java
+++ b/core/src/main/java/org/apache/iceberg/util/PropertyUtil.java
@@ -24,11 +24,13 @@ import java.util.Map;
 import java.util.Set;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
+import org.apache.iceberg.Schema;
 import org.apache.iceberg.TableProperties;
 import org.apache.iceberg.exceptions.ValidationException;
 import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
 import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
 import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.types.Types;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -206,6 +208,11 @@ public class PropertyUtil {
     return merged;
   }
 
+  /**
+   * @deprecated since 1.13.0, will be removed in 1.14.0; use {@link 
#applySchemaChanges(Map,
+   *     Schema, Schema)} instead.
+   */
+  @Deprecated
   public static Map<String, String> applySchemaChanges(
       Map<String, String> properties,
       List<String> deletedColumns,
@@ -242,4 +249,48 @@ public class PropertyUtil {
       return updatedProperties;
     }
   }
+
+  /**
+   * Returns the properties with per-column keys renamed or removed to follow 
their columns from
+   * {@code oldSchema} to {@code newSchema}.
+   */
+  public static Map<String, String> applySchemaChanges(
+      Map<String, String> properties, Schema oldSchema, Schema newSchema) {
+    Map<String, String> updated = Maps.newHashMap(properties);
+    Map<String, String> renamed = Maps.newHashMap();
+    for (Map.Entry<String, String> entry : properties.entrySet()) {
+      String prefix = columnPropertyPrefix(entry.getKey());
+      if (prefix == null) {
+        continue;
+      }
+
+      Types.NestedField field = 
oldSchema.findField(entry.getKey().substring(prefix.length()));
+      if (field == null) {
+        continue;
+      }
+
+      String oldName = oldSchema.findColumnName(field.fieldId());
+      String newName = newSchema.findColumnName(field.fieldId());
+      if (!oldName.equals(newName)) {
+        updated.remove(entry.getKey());
+        if (newName != null) {
+          renamed.put(prefix + newName, entry.getValue());
+        }
+      }
+    }
+
+    // a renamed property takes precedence over an unresolved property with 
the same key
+    updated.putAll(renamed);
+    return updated.equals(properties) ? properties : updated;
+  }
+
+  private static String columnPropertyPrefix(String key) {
+    for (String prefix : TableProperties.COLUMN_PROPERTY_PREFIXES) {
+      if (key.startsWith(prefix)) {
+        return prefix;
+      }
+    }
+
+    return null;
+  }
 }
diff --git 
a/core/src/test/java/org/apache/iceberg/TestSchemaAndMappingUpdate.java 
b/core/src/test/java/org/apache/iceberg/TestSchemaAndMappingUpdate.java
index 5b10da372c..c6c092ecec 100644
--- a/core/src/test/java/org/apache/iceberg/TestSchemaAndMappingUpdate.java
+++ b/core/src/test/java/org/apache/iceberg/TestSchemaAndMappingUpdate.java
@@ -18,10 +18,6 @@
  */
 package org.apache.iceberg;
 
-import static 
org.apache.iceberg.TableProperties.PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX;
-import static 
org.apache.iceberg.TableProperties.PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX;
-import static 
org.apache.iceberg.TableProperties.PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX;
-import static 
org.apache.iceberg.TableProperties.PARQUET_COLUMN_STATS_ENABLED_PREFIX;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
@@ -42,6 +38,10 @@ import org.junit.jupiter.api.extension.ExtendWith;
 
 @ExtendWith(ParameterizedTestExtension.class)
 public class TestSchemaAndMappingUpdate extends TestBase {
+  private static final Types.StructType LOCATION_TYPE =
+      Types.StructType.of(
+          Types.NestedField.optional(1, "lat", Types.DoubleType.get()),
+          Types.NestedField.optional(2, "long", Types.DoubleType.get()));
 
   @TestTemplate
   public void testAddPrimitiveColumn() {
@@ -177,56 +177,56 @@ public class TestSchemaAndMappingUpdate extends TestBase {
   }
 
   @TestTemplate
-  public void testModificationWithParquetBloomConfig() {
+  public void testRenameStructWithNestedColumnProperties() {
+    table.updateSchema().addColumn("location", LOCATION_TYPE).commit();
     table
         .updateProperties()
-        .set(PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX + "id", "true")
+        .set(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "location.lat", 
"full")
         .commit();
 
-    table.updateSchema().renameColumn("id", "ID").commit();
-    assertThat(table.properties())
-        .containsEntry(PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX + "ID", 
"true")
-        .doesNotContainKey(PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX + "id");
+    table.updateSchema().renameColumn("location", "loc").commit();
 
-    table.updateSchema().deleteColumn("ID").commit();
     assertThat(table.properties())
-        .doesNotContainKey(
-            table.properties().get(PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX 
+ "ID"));
+        .containsEntry(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"loc.lat", "full")
+        .doesNotContainKey(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"location.lat");
   }
 
   @TestTemplate
-  public void testModificationWithParquetColumnStats() {
-    table.updateProperties().set(PARQUET_COLUMN_STATS_ENABLED_PREFIX + "id", 
"true").commit();
+  public void testDeleteStructWithNestedColumnProperties() {
+    table.updateSchema().addColumn("location", LOCATION_TYPE).commit();
+    table
+        .updateProperties()
+        .set(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + "location.lat", 
"full")
+        .commit();
 
-    table.updateSchema().renameColumn("id", "ID").commit();
+    table.updateSchema().deleteColumn("location").commit();
     assertThat(table.properties())
-        .containsEntry(PARQUET_COLUMN_STATS_ENABLED_PREFIX + "ID", "true")
-        .doesNotContainKey(PARQUET_COLUMN_STATS_ENABLED_PREFIX + "id");
+        .doesNotContainKey(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"location.lat");
 
-    table.updateSchema().deleteColumn("ID").commit();
+    table.updateSchema().addColumn("location", LOCATION_TYPE).commit();
     assertThat(table.properties())
-        
.doesNotContainKey(table.properties().get(PARQUET_COLUMN_STATS_ENABLED_PREFIX + 
"ID"));
+        .doesNotContainKey(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"location.lat");
   }
 
   @TestTemplate
-  public void testModificationWithParquetColumnCompression() {
+  void renameAndDeleteListWithElementColumnProperties() {
+    table
+        .updateSchema()
+        .addColumn("points", Types.ListType.ofOptional(1000, LOCATION_TYPE))
+        .commit();
     table
         .updateProperties()
-        .set(PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX + "id", "zstd")
-        .set(PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX + "id", "9")
+        .set(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"points.element.lat", "full")
         .commit();
 
-    table.updateSchema().renameColumn("id", "ID").commit();
+    table.updateSchema().renameColumn("points", "pts").commit();
     assertThat(table.properties())
-        .containsEntry(PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX + "ID", "zstd")
-        .containsEntry(PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX + "ID", "9")
-        .doesNotContainKey(PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX + "id")
-        .doesNotContainKey(PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX + "id");
+        .containsEntry(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"pts.element.lat", "full")
+        .doesNotContainKey(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"points.element.lat");
 
-    table.updateSchema().deleteColumn("ID").commit();
+    table.updateSchema().deleteColumn("pts").commit();
     assertThat(table.properties())
-        .doesNotContainKey(PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX + "ID")
-        .doesNotContainKey(PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX + "ID");
+        .doesNotContainKey(TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX + 
"pts.element.lat");
   }
 
   @TestTemplate
diff --git a/core/src/test/java/org/apache/iceberg/util/TestPropertyUtil.java 
b/core/src/test/java/org/apache/iceberg/util/TestPropertyUtil.java
index 3925b38a59..b65955aa34 100644
--- a/core/src/test/java/org/apache/iceberg/util/TestPropertyUtil.java
+++ b/core/src/test/java/org/apache/iceberg/util/TestPropertyUtil.java
@@ -18,12 +18,23 @@
  */
 package org.apache.iceberg.util;
 
+import static org.apache.iceberg.types.Types.NestedField.optional;
+import static org.apache.iceberg.types.Types.NestedField.required;
 import static org.assertj.core.api.Assertions.assertThat;
 
 import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.types.Types;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.FieldSource;
 
 public class TestPropertyUtil {
+  private static final Schema SCHEMA =
+      new Schema(
+          required(1, "id", Types.IntegerType.get()), optional(2, "data", 
Types.StringType.get()));
 
   @Test
   void propertiesWithPrefixHandlesRegexSpecialChars() {
@@ -62,4 +73,41 @@ public class TestPropertyUtil {
     assertThat(PropertyUtil.mergeProperties(properties, overrides))
         .containsExactlyInAnyOrderEntriesOf(Map.of("k1", "v11", "k2", "v2", 
"k3", "v3"));
   }
+
+  @ParameterizedTest
+  @FieldSource("org.apache.iceberg.TableProperties#COLUMN_PROPERTY_PREFIXES")
+  void applySchemaChangesRenamesColumnProperty(String prefix) {
+    Schema renamed =
+        new Schema(required(1, "ID", Types.IntegerType.get()), 
SCHEMA.findField("data"));
+
+    Map<String, String> result =
+        PropertyUtil.applySchemaChanges(Map.of(prefix + "id", "v"), SCHEMA, 
renamed);
+
+    assertThat(result).isEqualTo(Map.of(prefix + "ID", "v"));
+  }
+
+  @ParameterizedTest
+  @FieldSource("org.apache.iceberg.TableProperties#COLUMN_PROPERTY_PREFIXES")
+  void applySchemaChangesRemovesDroppedColumnProperty(String prefix) {
+    Schema dropped = new Schema(SCHEMA.findField("data"));
+
+    Map<String, String> result =
+        PropertyUtil.applySchemaChanges(Map.of(prefix + "id", "v"), SCHEMA, 
dropped);
+
+    assertThat(result).isEmpty();
+  }
+
+  @Test
+  void applySchemaChangesRenamedPropertyReplacesUnresolvedProperty() {
+    String prefix = TableProperties.PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX;
+    Schema renamed =
+        new Schema(required(1, "ID", Types.IntegerType.get()), 
SCHEMA.findField("data"));
+    Map<String, String> properties = Maps.newLinkedHashMap();
+    properties.put(prefix + "id", "true");
+    properties.put(prefix + "ID", "false");
+
+    Map<String, String> result = PropertyUtil.applySchemaChanges(properties, 
SCHEMA, renamed);
+
+    assertThat(result).isEqualTo(Map.of(prefix + "ID", "true"));
+  }
 }
diff --git 
a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/SparkCatalog.java 
b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/SparkCatalog.java
index 45f44fa8e9..36acc7f317 100644
--- a/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/SparkCatalog.java
+++ b/spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/SparkCatalog.java
@@ -68,7 +68,6 @@ import org.apache.iceberg.spark.source.SparkChangelogTable;
 import org.apache.iceberg.spark.source.SparkTable;
 import org.apache.iceberg.spark.source.SparkView;
 import org.apache.iceberg.spark.source.StagedSparkTable;
-import org.apache.iceberg.types.TypeUtil;
 import org.apache.iceberg.util.Pair;
 import org.apache.iceberg.util.PropertyUtil;
 import org.apache.iceberg.view.UpdateViewProperties;
@@ -142,14 +141,6 @@ public class SparkCatalog extends BaseCatalog implements 
SparkSupportsLoadContex
           ViewProperties.METADATA_COMPRESSION,
           ViewProperties.WRITE_METADATA_LOCATION,
           ViewProperties.REPLACE_DROP_DIALECT_ALLOWED);
-  private static final Set<String> COLUMN_PROPERTY_PREFIXES =
-      ImmutableSet.of(
-          TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX,
-          TableProperties.PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX,
-          TableProperties.PARQUET_BLOOM_FILTER_COLUMN_FPP_PREFIX,
-          TableProperties.PARQUET_BLOOM_FILTER_COLUMN_NDV_PREFIX,
-          TableProperties.PARQUET_COLUMN_STATS_ENABLED_PREFIX,
-          TableProperties.PARQUET_DICT_ENCODING_ENABLED_COLUMN_PREFIX);
 
   private enum ViewCommit {
     CREATE,
@@ -262,8 +253,10 @@ public class SparkCatalog extends BaseCatalog implements 
SparkSupportsLoadContex
       org.apache.iceberg.Table sourceIcebergTable = sparkTable.table();
       icebergSchema = sparkTable.icebergSchema();
       spec = copyPartitionSpec(icebergSchema, sourceIcebergTable.spec());
+      // column properties name columns of the current schema, which can 
differ from the schema of
+      // a pinned snapshot
       properties.putAll(
-          copyColumnProperties(
+          PropertyUtil.applySchemaChanges(
               sourceIcebergTable.properties(), sourceIcebergTable.schema(), 
icebergSchema));
       properties.remove(TableProperties.WRITE_METADATA_LOCATION);
       properties.remove(TableProperties.WRITE_DATA_LOCATION);
@@ -313,30 +306,6 @@ public class SparkCatalog extends BaseCatalog implements 
SparkSupportsLoadContex
     }
   }
 
-  /**
-   * Returns the source properties with column-specific properties renamed or 
dropped to match the
-   * given schema, since those properties name columns of the current schema, 
which can differ from
-   * the schema of a pinned snapshot.
-   */
-  private static Map<String, String> copyColumnProperties(
-      Map<String, String> properties, Schema currentSchema, Schema schema) {
-    List<String> deletedColumns = Lists.newArrayList();
-    Map<String, String> renamedColumns = Maps.newHashMap();
-    TypeUtil.indexByName(currentSchema.asStruct())
-        .forEach(
-            (name, id) -> {
-              String nameInSchema = schema.findColumnName(id);
-              if (nameInSchema == null) {
-                deletedColumns.add(name);
-              } else if (!nameInSchema.equals(name)) {
-                renamedColumns.put(name, nameInSchema);
-              }
-            });
-
-    return PropertyUtil.applySchemaChanges(
-        properties, deletedColumns, renamedColumns, COLUMN_PROPERTY_PREFIXES);
-  }
-
   private static PartitionSpec copyPartitionSpec(Schema schema, PartitionSpec 
sourceSpec) {
     UnboundPartitionSpec spec = sourceSpec.toUnbound();
     for (int index = sourceSpec.fields().size() - 1; index >= 0; index -= 1) {

Reply via email to