You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "lzshlzsh (via GitHub)" <gi...@apache.org> on 2026/06/22 07:30:53 UTC

[PR] [#11753] feat(catalog-iceberg): support primary key via identifier fields [gravitino]

lzshlzsh opened a new pull request, #11754:
URL: https://github.com/apache/gravitino/pull/11754

   ### What changes were proposed in this pull request?
   
   Wire the Gravitino `PRIMARY_KEY` index through to / from Iceberg's
   schema-level `identifier-field-ids`, forming a create/load round-trip closure
   for primary keys on Iceberg V2 tables.
   
   - `ConvertUtil`
     - `applyIdentifierFields` + `primaryKeyColumnNames` (forward): after
       building the Iceberg `Schema`, set `identifier-field-ids` from the field
       ids of the columns referenced by the single `PRIMARY_KEY` index. This
       mirrors `FlinkSchemaUtil.freshIdentifierFieldIds` in apache/iceberg.
       Iceberg requires identifier fields to be `required` (NOT NULL); we rely
       on Iceberg's own `Schema` constructor to enforce that constraint and
       intentionally do not silently promote nullability.
     - `constructIndexesFromIdentifierFields` (reverse): reconstruct a
       `PRIMARY_KEY` index from `Schema#identifierFieldIds()`, ordered by the
       column position in the schema for deterministic results (Iceberg
       identifier fields are an unordered set).
   - `IcebergTable`
     - Add `ICEBERG_PRIMARY_KEY_INDEX_NAME = "ICEBERG_PRIMARY_KEY_INDEX"`
       (analogous to Paimon's `PAIMON_PRIMARY_KEY_INDEX`).
     - `internalBuild` now stores `indexes` on the built table; `fromIcebergTable`
       back-fills the `PRIMARY_KEY` index from the loaded Iceberg schema.
   - `IcebergCatalogOperations`
     - Replace the blanket "Iceberg does not support indexes" rejection with
       `validateIcebergIndexes`: allow at most one `PRIMARY_KEY` index over one
       or more non-nested columns; reject multiple indexes, non-`PRIMARY_KEY`
       types, empty column lists, and nested column references with clear
       messages.
     - Pass the validated indexes through to the Iceberg table builder.
   
   Out of scope: primary-key evolution via `TableChange` (Iceberg's
   `UpdateSchema#setIdentifierFields` exists, but PK evolution interacts with
   NOT NULL promotion and equality deletes and warrants a separate discussion);
   no changes to the `iceberg-rest-server` module.
   
   ### Why are the changes needed?
   
   Iceberg V2 natively supports a primary key concept via `identifier-field-ids`,
   which Flink CDC and the Iceberg Flink connector use for upsert /
   equality-delete writes. Gravitino's Iceberg catalog currently rejects every
   `Index` at create time, so users cannot:
   
   1. Express a primary key on an Iceberg table through the Gravitino API or any
      engine routed via Gravitino.
   2. Round-trip a primary key created by another engine — even when the
      underlying Iceberg table already carries `identifier-field-ids`,
      `IcebergTable#fromIcebergTable` previously dropped them and `Table#index()`
      always returned empty.
   
   The Paimon catalog already handles the analogous mapping in both directions
   (`PaimonTable#constructIndexesFromPrimaryKeys`,
   `GravitinoToPaimonTableConverter`); this PR aligns the Iceberg catalog with
   that behavior.
   
   Fix: #11753
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes, in the `catalog-lakehouse-iceberg` module only:
   
   - Creating an Iceberg table with a single `PRIMARY_KEY` index is now
     accepted and produces an Iceberg V2 table with `identifier-field-ids`
     set on its schema (previously rejected with
     *"Iceberg does not support indexes"*).
   - Loading an Iceberg table whose schema has `identifier-field-ids` now
     surfaces a `PRIMARY_KEY` index named `ICEBERG_PRIMARY_KEY_INDEX` via
     `Table#index()` (previously always empty for Iceberg).
   - Invalid index shapes (more than one index, non-`PRIMARY_KEY` type,
     empty column list, nested column reference) are still rejected, now
     with focused error messages.
   
   No new property keys, no public API signature changes.
   
   ### How was this patch tested?
   
   New unit tests cover both directions of the mapping and the validation
   rules (run via `./gradlew :catalogs:catalog-lakehouse-iceberg:test`):
   
   - `TestConvertUtil`
     - forward: `PRIMARY_KEY` index → Iceberg `identifier-field-ids` (single &
       composite columns).
     - reverse: `identifier-field-ids` → `PRIMARY_KEY` index, asserting the
       reconstructed columns are ordered by schema position.
     - empty cases: no index ⇒ no identifier fields; no identifier fields ⇒
       `Indexes.EMPTY_INDEXES`.
     - round-trip: forward then reverse yields the original PK column set.
     - Iceberg's NOT NULL constraint on identifier fields is exercised by
       relying on the `Schema` constructor's own validation.
   - `TestIcebergCatalogOperations` (validation):
     - more than one index ⇒ `IllegalArgumentException`.
     - non-`PRIMARY_KEY` index type ⇒ `IllegalArgumentException`.
     - empty PK column list ⇒ `IllegalArgumentException`.
     - nested PK column reference (`a.b`) ⇒ `IllegalArgumentException`.
   
   No existing tests required changes; the previous "indexes not supported"
   behavior had no positive coverage to remove.
   


-- 
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: commits-unsubscribe@gravitino.apache.org

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


Re: [PR] [#11753] feat(catalog-iceberg): support primary key via identifier fields [gravitino]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11754:
URL: https://github.com/apache/gravitino/pull/11754#discussion_r3456566667


##########
catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java:
##########
@@ -603,6 +604,36 @@ public Table createTable(
     }
   }
 
+  /**
+   * Validates the indexes supplied when creating an Iceberg table. Iceberg only supports expressing
+   * a primary key, which Gravitino models as a single {@code PRIMARY_KEY} index over one or more
+   * non-nested columns. The primary key columns are mapped to Iceberg {@code identifier-field-ids};
+   * Iceberg requires identifier fields to be required (NOT NULL), which is enforced by the Iceberg
+   * schema constructor.
+   *
+   * @param indexes The indexes to validate. An empty array is allowed (no primary key).
+   */
+  private static void validateIcebergIndexes(Index[] indexes) {
+    if (indexes == null || indexes.length == 0) {
+      return;
+    }
+    Preconditions.checkArgument(
+        indexes.length == 1, "Iceberg only supports no more than one PRIMARY_KEY Index.");
+    Index index = indexes[0];
+    Preconditions.checkArgument(
+        index.type() == Index.IndexType.PRIMARY_KEY, "Iceberg only supports primary key Index.");

Review Comment:
   `validateIcebergIndexes` dereferences `indexes[0]` without checking for a null element. `TableCreateRequest#validate()` doesn't validate each index entry is non-null, so this can currently throw an NPE instead of a clear `IllegalArgumentException`.



##########
catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergTable.java:
##########
@@ -72,6 +72,10 @@ public class IcebergTable extends BaseTable {
 
   public static final String ICEBERG_COMMENT_FIELD_NAME = "comment";
 
+  /** The name of the synthetic primary key index reconstructed from Iceberg identifier fields. */
+  @VisibleForTesting
+  public static final String ICEBERG_PRIMARY_KEY_INDEX_NAME = "ICEBERG_PRIMARY_KEY_INDEX";

Review Comment:
   `ICEBERG_PRIMARY_KEY_INDEX_NAME` is part of production behavior (it becomes the name surfaced via `Table#index()`), but it's annotated `@VisibleForTesting`, which is misleading. Consider removing the annotation so it doesn't imply test-only usage.



##########
catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java:
##########
@@ -603,6 +604,36 @@ public Table createTable(
     }
   }
 
+  /**
+   * Validates the indexes supplied when creating an Iceberg table. Iceberg only supports expressing
+   * a primary key, which Gravitino models as a single {@code PRIMARY_KEY} index over one or more
+   * non-nested columns. The primary key columns are mapped to Iceberg {@code identifier-field-ids};
+   * Iceberg requires identifier fields to be required (NOT NULL), which is enforced by the Iceberg
+   * schema constructor.
+   *
+   * @param indexes The indexes to validate. An empty array is allowed (no primary key).
+   */
+  private static void validateIcebergIndexes(Index[] indexes) {
+    if (indexes == null || indexes.length == 0) {
+      return;
+    }
+    Preconditions.checkArgument(
+        indexes.length == 1, "Iceberg only supports no more than one PRIMARY_KEY Index.");
+    Index index = indexes[0];
+    Preconditions.checkArgument(
+        index.type() == Index.IndexType.PRIMARY_KEY, "Iceberg only supports primary key Index.");
+    String[][] fieldNames = index.fieldNames();
+    Preconditions.checkArgument(
+        fieldNames != null && fieldNames.length > 0,
+        "The primary key Index must contain at least one column.");
+    Arrays.stream(fieldNames)
+        .forEach(
+            fieldName ->
+                Preconditions.checkArgument(
+                    fieldName != null && fieldName.length == 1,
+                    "The primary key columns should not be nested."));

Review Comment:
   Nested columns can be represented as a single dotted name (see `Index#fieldNames()` Javadoc: e.g. `"a.b.c"`). The current validation only checks `fieldName.length == 1`, so `{"a.b"}` would incorrectly pass and then fail later (or silently map to the wrong Iceberg field). Also, `fieldName[0]` can be null/empty, which can lead to NPEs downstream.



##########
catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java:
##########
@@ -40,7 +47,72 @@ public static Schema toIcebergSchema(IcebergTable gravitinoTable) {
         toGravitinoStructType(gravitinoTable);
     Type converted =
         ToIcebergTypeVisitor.visit(gravitinoStructType, new ToIcebergType(gravitinoStructType));
-    return new Schema(converted.asNestedType().asStructType().fields());
+    Schema schema = new Schema(converted.asNestedType().asStructType().fields());
+    return applyIdentifierFields(schema, primaryKeyColumnNames(gravitinoTable));
+  }
+
+  /**
+   * Sets the Iceberg {@code identifier-field-ids} for the primary key columns, mirroring the native
+   * Flink Iceberg connector's {@code FlinkSchemaUtil.freshIdentifierFieldIds}. Iceberg requires
+   * identifier fields to be required (NOT NULL) columns; this constraint is enforced by the Iceberg
+   * {@link Schema} constructor itself, so no nullability promotion is performed here.
+   *
+   * @param schema The Iceberg schema before identifier fields are applied.
+   * @param primaryKeyColumns The primary key column names (empty when there is no primary key).
+   * @return The Iceberg schema carrying the identifier field ids.
+   */
+  private static Schema applyIdentifierFields(Schema schema, List<String> primaryKeyColumns) {
+    if (primaryKeyColumns.isEmpty()) {
+      return schema;
+    }
+    Set<Integer> identifierFieldIds = new LinkedHashSet<>();
+    for (String columnName : primaryKeyColumns) {
+      Types.NestedField field = schema.findField(columnName);
+      Preconditions.checkArgument(
+          field != null, "Cannot find primary key column in table schema: %s", columnName);
+      identifierFieldIds.add(field.fieldId());
+    }
+    return new Schema(schema.schemaId(), schema.asStruct().fields(), identifierFieldIds);
+  }
+
+  /**
+   * Extracts the primary key column names from the table's {@code PRIMARY_KEY} index. Returns an
+   * empty list when no index is present.
+   *
+   * @param gravitinoTable Gravitino table of Iceberg.
+   * @return The ordered primary key column names.
+   */
+  private static List<String> primaryKeyColumnNames(IcebergTable gravitinoTable) {
+    Index[] indexes = gravitinoTable.index();
+    if (indexes == null || indexes.length == 0) {
+      return Collections.emptyList();
+    }
+    return Arrays.stream(indexes[0].fieldNames())
+        .map(fieldName -> fieldName[0])
+        .collect(Collectors.toList());
+  }
+
+  /**
+   * Reconstructs the Gravitino {@code PRIMARY_KEY} index from the Iceberg {@code
+   * identifier-field-ids}, mirroring Paimon's {@code constructIndexesFromPrimaryKeys}. The primary
+   * key columns are ordered by their position in the schema for deterministic results, since
+   * Iceberg identifier fields are an unordered set.
+   *
+   * @param schema The Iceberg schema loaded from the catalog.
+   * @return A single-element {@code PRIMARY_KEY} index array, or an empty array when the schema has
+   *     no identifier fields.
+   */
+  public static Index[] constructIndexesFromIdentifierFields(Schema schema) {
+    Set<Integer> identifierFieldIds = schema.identifierFieldIds();
+    if (identifierFieldIds == null || identifierFieldIds.isEmpty()) {
+      return Indexes.EMPTY_INDEXES;
+    }
+    String[][] fieldNames =
+        schema.columns().stream()
+            .filter(field -> identifierFieldIds.contains(field.fieldId()))
+            .map(field -> new String[] {field.name()})
+            .toArray(String[][]::new);
+    return new Index[] {Indexes.primary(IcebergTable.ICEBERG_PRIMARY_KEY_INDEX_NAME, fieldNames)};

Review Comment:
   If `schema.identifierFieldIds()` is non-empty but none of the ids match `schema.columns()` (e.g., unexpected nested identifier fields or stale ids), this method currently returns a PRIMARY_KEY index with an empty column list. That violates the catalog's own validation rules and can confuse downstream consumers. Better to return `Indexes.EMPTY_INDEXES` when no column names are resolved.



##########
catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogOperations.java:
##########
@@ -95,4 +101,49 @@ public void testListSchemasFlatOnlyReturnsUnchangedNames() {
     Assertions.assertTrue(Arrays.stream(result).anyMatch(id -> "db1".equals(id.name())));
     Assertions.assertTrue(Arrays.stream(result).anyMatch(id -> "db2".equals(id.name())));
   }
+
+  @Test
+  public void testCreateTableRejectsMultiplePrimaryKeyIndexes() {
+    Index[] indexes =
+        new Index[] {
+          Indexes.primary("pk1", new String[][] {{"id"}}),
+          Indexes.primary("pk2", new String[][] {{"name"}})
+        };
+    IllegalArgumentException exception =
+        Assertions.assertThrows(
+            IllegalArgumentException.class, () -> createTableWithIndexes(indexes));
+    Assertions.assertTrue(exception.getMessage().contains("no more than one PRIMARY_KEY Index"));
+  }
+
+  @Test
+  public void testCreateTableRejectsNonPrimaryKeyIndex() {
+    Index[] indexes = new Index[] {Indexes.unique("uk", new String[][] {{"id"}})};
+    IllegalArgumentException exception =
+        Assertions.assertThrows(
+            IllegalArgumentException.class, () -> createTableWithIndexes(indexes));
+    Assertions.assertTrue(exception.getMessage().contains("only supports primary key Index"));
+  }
+
+  @Test
+  public void testCreateTableRejectsNestedPrimaryKeyColumn() {
+    Index[] indexes = new Index[] {Indexes.primary("pk", new String[][] {{"struct", "field"}})};
+    IllegalArgumentException exception =
+        Assertions.assertThrows(
+            IllegalArgumentException.class, () -> createTableWithIndexes(indexes));
+    Assertions.assertTrue(exception.getMessage().contains("should not be nested"));
+  }
+

Review Comment:
   `validateIcebergIndexes` adds a new rejection path for an empty primary-key column list, but there is no test covering that case in this class (the PR description mentions it). Adding a focused unit test helps lock in the behavior and aligns with the repo rule that all new logic must be tested.



##########
catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java:
##########
@@ -108,6 +111,108 @@ public void testToIcebergSchemaWithNullColumns() {
     Assertions.assertEquals("columns must not be null", exception.getMessage());
   }
 
+  @Test
+  public void testToIcebergSchemaWithSinglePrimaryKey() {
+    IcebergTable table =
+        primaryKeyTable(
+            new String[][] {{"id"}},
+            requiredColumn("id", org.apache.gravitino.rel.types.Types.LongType.get()),
+            nullableColumn("name", org.apache.gravitino.rel.types.Types.StringType.get()));
+    Schema schema = ConvertUtil.toIcebergSchema(table);
+    Assertions.assertEquals(
+        Collections.singleton(schema.findField("id").fieldId()), schema.identifierFieldIds());
+  }
+
+  @Test
+  public void testToIcebergSchemaWithCompositePrimaryKey() {
+    IcebergTable table =
+        primaryKeyTable(
+            new String[][] {{"id"}, {"region"}},
+            requiredColumn("id", org.apache.gravitino.rel.types.Types.LongType.get()),
+            requiredColumn("region", org.apache.gravitino.rel.types.Types.StringType.get()),
+            nullableColumn("name", org.apache.gravitino.rel.types.Types.StringType.get()));
+    Schema schema = ConvertUtil.toIcebergSchema(table);
+    Assertions.assertEquals(
+        com.google.common.collect.ImmutableSet.of(
+            schema.findField("id").fieldId(), schema.findField("region").fieldId()),
+        schema.identifierFieldIds());

Review Comment:
   The test uses a fully qualified class name (`com.google.common.collect.ImmutableSet`) inside method code. Repo guidelines prefer normal imports instead of FQNs (AGENTS.md:26-30). You can avoid the FQN here without adding new imports by building the expected set via existing `Arrays`/`Collectors` imports.



-- 
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: commits-unsubscribe@gravitino.apache.org

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