Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions pyiceberg/table/update/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,17 @@ def add_field(
if added:
raise ValueError(f"Already added partition: {added.name}")

if (
existing_partition_field
and existing_partition_field.field_id in self._deletes
and partition_field_name not in self._name_to_added_field
):
# Undo the removal instead of adding a new field, as Java's rewriteDeleteAndAddField does
self._deletes.remove(existing_partition_field.field_id)
if partition_field_name is None or partition_field_name == existing_partition_field.name:
return self
return self.rename_field(existing_partition_field.name, partition_field_name)

new_field = self._partition_field((bound_ref.field.field_id, transform), partition_field_name)
if new_field.name in self._name_to_added_field:
raise ValueError(f"Already added partition field with name: {new_field.name}")
Expand Down Expand Up @@ -136,7 +147,7 @@ def remove_field(self, name: str) -> UpdateSpec:
if added:
raise ValueError(f"Cannot delete newly added field {name}")
renamed = self._renames.get(name)
if renamed:
if renamed is not None:
raise ValueError(f"Cannot rename and delete field {name}")
field = self._name_to_field.get(name)
if not field:
Expand Down Expand Up @@ -204,7 +215,7 @@ def _add_new_field(
for field in self._transaction.table_metadata.spec().fields:
if field.field_id not in self._deletes:
renamed = self._renames.get(field.name)
if renamed:
if renamed is not None:
new_field = _add_new_field(
self._transaction.table_metadata.schema(),
field.source_id,
Expand All @@ -225,7 +236,7 @@ def _add_new_field(
partition_fields.append(new_field)
elif self._transaction.table_metadata.format_version == 1:
renamed = self._renames.get(field.name)
if renamed:
if renamed is not None:
new_field = _add_new_field(
self._transaction.table_metadata.schema(),
field.source_id,
Expand Down
123 changes: 121 additions & 2 deletions tests/table/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@
from pyiceberg.table.update.schema import UpdateSchema
from pyiceberg.transforms import (
BucketTransform,
DayTransform,
HourTransform,
IdentityTransform,
VoidTransform,
)
Expand Down Expand Up @@ -1805,10 +1807,19 @@ def test_update_spec_rejects_duplicate_partition_name(table_v2: Table) -> None:
txn.update_spec().rename_field("y_bucket", "z_bucket").add_field("z", BucketTransform(16), "z_bucket").commit()


def test_update_spec_rejects_empty_partition_name(table_v2: Table) -> None:
def test_update_spec_rejects_empty_partition_name(table_v1: Table, table_v2: Table) -> None:
with pytest.raises(ValueError, match="Undefined name"):
table_v2.transaction().update_spec().add_field("z", BucketTransform(16), "").commit()

for table in (table_v1, table_v2):
# renaming to an empty name, also by adding a removed field back, is rejected as well
with pytest.raises(ValueError, match="Undefined name"):
table.transaction().update_spec().rename_field("x", "").commit()
with pytest.raises(ValueError, match="Undefined name"):
table.transaction().update_spec().remove_field("x").add_field("x", IdentityTransform(), "").commit()
with pytest.raises(ValueError, match="^Cannot rename and delete field x$"):
table.transaction().update_spec().remove_field("x").add_field("x", IdentityTransform(), "").remove_field("x")


@pytest.mark.parametrize("table", [lf("table_v2"), lf("table_v3")])
def test_update_spec_reuses_removed_partition_field_id(table: Table) -> None:
Expand All @@ -1823,7 +1834,7 @@ def test_update_spec_reuses_removed_partition_field_id(table: Table) -> None:
assert txn.table_metadata.last_partition_id == 1001


@pytest.mark.parametrize("table", [lf("table_v2"), lf("table_v3")])
@pytest.mark.parametrize("table", [lf("table_v1"), lf("table_v2"), lf("table_v3")])
def test_update_spec_remove_and_add_same_field_reuses_id(table: Table) -> None:
txn = table.transaction()
txn.update_spec().remove_field("x").add_identity("x").commit()
Expand All @@ -1834,6 +1845,114 @@ def test_update_spec_remove_and_add_same_field_reuses_id(table: Table) -> None:
assert txn.table_metadata.last_partition_id == 1000


def test_update_spec_remove_or_rename_field_added_back_in_same_update(table_v1: Table, table_v2: Table) -> None:
for table in (table_v1, table_v2):
# the field is an original field again, so removing it voids it on v1 tables and drops it on v2
txn = table.transaction()
txn.update_spec().remove_field("x").add_identity("x").remove_field("x").commit()
voided = PartitionField(source_id=1, field_id=1000, transform=VoidTransform(), name="x")
assert txn.table_metadata.spec().fields == ((voided,) if table.format_version == 1 else ())

txn = table.transaction()
txn.update_spec().remove_field("x").add_identity("x").rename_field("x", "x_renamed").commit()
assert txn.table_metadata.spec().fields == (
PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="x_renamed"),
)


def test_update_spec_remove_and_add_same_field_in_one_update(catalog: Catalog) -> None:
catalog.create_namespace("default")
schema = Schema(
NestedField(1, "x", IntegerType(), required=False),
NestedField(2, "y", IntegerType(), required=False),
)
spec = PartitionSpec(
PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="x"),
PartitionField(source_id=2, field_id=1001, transform=BucketTransform(16), name="y_shard"),
)
# The removed field is the first (x) or the last (y_shard) one. Added back under the same name in the same
# update, it keeps its id and position, so the spec is unchanged.
for format_version in (1, 2):
for removed, source, transform in (("x", "x", IdentityTransform()), ("y_shard", "y", BucketTransform(16))):
identifier = f"default.readd_v{format_version}_{removed}"
catalog.create_table(
identifier, schema=schema, partition_spec=spec, properties={"format-version": str(format_version)}
).update_spec().remove_field(removed).add_field(source, transform, removed).commit()

table = catalog.load_table(identifier)
assert table.spec().fields == spec.fields
assert table.metadata.last_partition_id == 1001
assert sorted(table.metadata.specs().keys()) == [0]

# added back under another name, the first field is renamed in place
identifier = f"default.readd_v{format_version}_renamed"
catalog.create_table(
identifier, schema=schema, partition_spec=spec, properties={"format-version": str(format_version)}
).update_spec().remove_field("x").add_field("x", IdentityTransform(), "x_renamed").commit()
assert catalog.load_table(identifier).spec().fields == (
PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="x_renamed"),
spec.fields[1],
)


def test_update_spec_restore_time_transform_with_added_time_transform(catalog: Catalog) -> None:
catalog.create_namespace("default")
schema = Schema(NestedField(1, "ts", TimestampType(), required=False))
day = PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="ts_day")
hour = PartitionField(source_id=1, field_id=1001, transform=HourTransform(), name="ts_hour")
for format_version in (1, 2):
for first, second in ((HourTransform(), DayTransform()), (DayTransform(), HourTransform())):
identifier = f"default.time_{first}_v{format_version}"
catalog.create_table(
identifier, schema=schema, partition_spec=PartitionSpec(day), properties={"format-version": str(format_version)}
).update_spec().remove_field("ts_day").add_field("ts", first).add_field("ts", second).commit()

# the restored day keeps its id and position, and the new hour field is appended
assert catalog.load_table(identifier).spec().fields == (day, hour)


def test_update_spec_remove_and_add_renamed_field_in_one_update(catalog: Catalog) -> None:
catalog.create_namespace("default")
schema = Schema(
NestedField(1, "x", IntegerType(), required=False),
NestedField(2, "y", IntegerType(), required=False),
)
expected = (PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="r"),)
for format_version in (1, 2):
identifier = f"default.renamed_v{format_version}"
catalog.create_table(
identifier,
schema=schema,
partition_spec=PartitionSpec(
PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="p"),
),
properties={"format-version": str(format_version)},
).update_spec().rename_field("p", "r").commit()

# the renamed field is removed and added back without a name in one update: the spec does not change
renamed = catalog.load_table(identifier)
renamed.update_spec().remove_field("r").add_identity("x").commit()
restored = catalog.load_table(identifier)
assert restored.spec().fields == expected
assert restored.metadata.default_spec_id == renamed.metadata.default_spec_id == 1
assert restored.metadata.last_partition_id == renamed.metadata.last_partition_id == 1000

# a later add in the same update cannot take the restored name
with pytest.raises(ValueError, match="^Cannot add duplicate partition field name: r$"):
restored.update_spec().remove_field("r").add_identity("x").add_field("y", BucketTransform(8), "r").commit()

# once a new field takes the removed name, the removed field cannot be added back under it, and without a name
# it is restored as r_1000, as in Java
update = restored.update_spec().remove_field("r").add_field("y", BucketTransform(8), "r")
with pytest.raises(ValueError, match="^Already added partition field with name: r$"):
update.add_field("x", IdentityTransform(), "r")
restored.update_spec().remove_field("r").add_field("y", BucketTransform(8), "r").add_identity("x").commit()
assert catalog.load_table(identifier).spec().fields == (
PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="r_1000"),
PartitionField(source_id=2, field_id=1001, transform=BucketTransform(8), name="r"),
)


def test_update_spec_remove_and_add_field_with_same_name(table_v1: Table, table_v2: Table) -> None:
for table in [table_v1, table_v2]:
txn = table.transaction()
Expand Down