diff --git a/core/src/main/java/org/apache/iceberg/BaseUpdatePartitionSpec.java b/core/src/main/java/org/apache/iceberg/BaseUpdatePartitionSpec.java index 0818fb332dca..697ecc43bbef 100644 --- a/core/src/main/java/org/apache/iceberg/BaseUpdatePartitionSpec.java +++ b/core/src/main/java/org/apache/iceberg/BaseUpdatePartitionSpec.java @@ -69,7 +69,8 @@ class BaseUpdatePartitionSpec implements UpdatePartitionSpec { this.schema = spec.schema(); this.nameToField = indexSpecByName(spec); this.transformToField = indexSpecByTransform(spec); - this.lastAssignedPartitionId = spec.fields().stream().mapToInt(PartitionField::fieldId).max().orElse(999); + this.lastAssignedPartitionId = + base.specs().stream().mapToInt(PartitionSpec::lastAssignedFieldId).max().orElse(999); spec.fields().stream() .filter(field -> field.transform() instanceof UnknownTransform) diff --git a/core/src/test/java/org/apache/iceberg/TestTableUpdatePartitionSpec.java b/core/src/test/java/org/apache/iceberg/TestTableUpdatePartitionSpec.java index 0ad547c8ba25..76f9fa0b28fc 100644 --- a/core/src/test/java/org/apache/iceberg/TestTableUpdatePartitionSpec.java +++ b/core/src/test/java/org/apache/iceberg/TestTableUpdatePartitionSpec.java @@ -196,4 +196,26 @@ public void testAddAndRemoveField() { .build(), table.spec()); Assert.assertEquals(1001, table.spec().lastAssignedFieldId()); } + + @Test + public void testAddAfterLastFieldRemoved() { + table.updateSpec() + .removeField("data_bucket") + .commit(); + + table.updateSpec() + .addField(bucket("id", 8)) + .commit(); + + V1Assert.assertEquals("Should add a new id bucket", PartitionSpec.builderFor(table.schema()) + .withSpecId(2) + .alwaysNull("data", "data_bucket") + .bucket("id", 8, "id_bucket_8") + .build(), table.spec()); + V2Assert.assertEquals("Should add a new id bucket", PartitionSpec.builderFor(table.schema()) + .withSpecId(2) + .add(1, 1001, "id_bucket_8", "bucket[8]") + .build(), table.spec()); + Assert.assertEquals(1001, table.spec().lastAssignedFieldId()); + } }