Skip to content

Commit 7e47009

Browse files
committed
Add validation for compatible schema evolution when partition fields or sort order fields reference schema fields
1 parent abae20f commit 7e47009

File tree

7 files changed

+181
-2
lines changed

7 files changed

+181
-2
lines changed

pyiceberg/partitioning.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
model_validator,
3333
)
3434

35-
from pyiceberg.schema import Schema
35+
from pyiceberg.exceptions import ValidationError
36+
from pyiceberg.schema import Schema, _index_parents
3637
from pyiceberg.transforms import (
3738
BucketTransform,
3839
DayTransform,
@@ -249,6 +250,36 @@ def partition_to_path(self, data: Record, schema: Schema) -> str:
249250
path = "/".join([field_str + "=" + value_str for field_str, value_str in zip(field_strs, value_strs, strict=True)])
250251
return path
251252

253+
def check_compatible(self, schema: Schema, allow_missing_fields: bool = False) -> None:
254+
# if the underlying field is dropped, we cannot check they are compatible -- continue
255+
schema_fields = schema._lazy_id_to_field
256+
parents = _index_parents(schema)
257+
258+
def validate_parents_are_structs(field_id: int) -> None:
259+
parent_id = parents.get(field_id)
260+
while parent_id:
261+
parent_type = schema.find_type(parent_id)
262+
if not parent_type.is_struct:
263+
raise ValidationError("Invalid partition field parent: %s", parent_type)
264+
parent_id = parents.get(parent_id)
265+
266+
for field in self.fields:
267+
source_field = schema_fields.get(field.source_id)
268+
if allow_missing_fields and source_field:
269+
continue
270+
271+
if not isinstance(field.transform, VoidTransform):
272+
if source_field:
273+
source_type = source_field.field_type
274+
if not source_type.is_primitive:
275+
raise ValidationError(f"Cannot partition by non-primitive source field: {source_type}")
276+
if not field.transform.can_transform(source_type):
277+
raise ValidationError(f"Invalid source type {source_type} for transform: {field.transform}")
278+
# The only valid parent types for a PartitionField are StructTypes. This must be checked recursively
279+
validate_parents_are_structs(field.source_id)
280+
else:
281+
raise ValidationError(f"Cannot find source column for partition field: {field}")
282+
252283

253284
UNPARTITIONED_PARTITION_SPEC = PartitionSpec(spec_id=0)
254285

pyiceberg/table/sorting.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
model_validator,
2828
)
2929

30+
from pyiceberg.exceptions import ValidationError
3031
from pyiceberg.schema import Schema
3132
from pyiceberg.transforms import IdentityTransform, Transform, parse_transform
3233
from pyiceberg.typedef import IcebergBaseModel
@@ -169,6 +170,17 @@ def __repr__(self) -> str:
169170
fields = f"{', '.join(repr(column) for column in self.fields)}, " if self.fields else ""
170171
return f"SortOrder({fields}order_id={self.order_id})"
171172

173+
def check_compatible(self, schema: Schema) -> None:
174+
schema_ids = schema._lazy_id_to_field
175+
for field in self.fields:
176+
if source_field := schema_ids.get(field.source_id):
177+
if not source_field.field_type.is_primitive:
178+
raise ValidationError(f"Cannot sort by non-primitive source field: {source_field}")
179+
if not field.transform.can_transform(source_field.field_type):
180+
raise ValidationError(f"Invalid source type {source_field.field_type} for transform: {field.transform}")
181+
else:
182+
raise ValidationError(f"Cannot find source column for sort field: {field}")
183+
172184

173185
UNSORTED_SORT_ORDER_ID = 0
174186
UNSORTED_SORT_ORDER = SortOrder(order_id=UNSORTED_SORT_ORDER_ID)

pyiceberg/table/update/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,12 @@ def update_table_metadata(
700700
if base_metadata.last_updated_ms == new_metadata.last_updated_ms:
701701
new_metadata = new_metadata.model_copy(update={"last_updated_ms": datetime_to_millis(datetime.now().astimezone())})
702702

703+
# Check correctness of partition spec, and sort order
704+
new_metadata.spec().check_compatible(new_metadata.schema())
705+
706+
if sort_order := new_metadata.sort_order_by_id(new_metadata.default_sort_order_id):
707+
sort_order.check_compatible(new_metadata.schema())
708+
703709
if enforce_validation:
704710
return TableMetadataUtil.parse_obj(new_metadata.model_dump())
705711
else:

tests/conftest.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
from pyiceberg.serializers import ToOutputFile
7171
from pyiceberg.table import FileScanTask, Table
7272
from pyiceberg.table.metadata import TableMetadataV1, TableMetadataV2, TableMetadataV3
73+
from pyiceberg.table.sorting import NullOrder, SortField, SortOrder
7374
from pyiceberg.transforms import DayTransform, IdentityTransform
7475
from pyiceberg.types import (
7576
BinaryType,
@@ -1894,6 +1895,11 @@ def test_partition_spec() -> Schema:
18941895
)
18951896

18961897

1898+
@pytest.fixture(scope="session")
1899+
def test_sort_order() -> SortOrder:
1900+
return SortOrder(SortField(source_id=1, transform=IdentityTransform(), null_order=NullOrder.NULLS_FIRST))
1901+
1902+
18971903
@pytest.fixture(scope="session")
18981904
def generated_manifest_entry_file(
18991905
avro_schema_manifest_entry: dict[str, Any], test_schema: Schema, test_partition_spec: PartitionSpec

tests/integration/test_catalog.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
NoSuchNamespaceError,
3434
NoSuchTableError,
3535
TableAlreadyExistsError,
36+
ValidationError,
3637
)
3738
from pyiceberg.io import WAREHOUSE
3839
from pyiceberg.partitioning import PartitionField, PartitionSpec
@@ -601,3 +602,56 @@ def test_register_table_existing(test_catalog: Catalog, table_schema_nested: Sch
601602
# Assert that registering the table again raises TableAlreadyExistsError
602603
with pytest.raises(TableAlreadyExistsError):
603604
test_catalog.register_table(identifier, metadata_location=table.metadata_location)
605+
606+
607+
@pytest.mark.integration
608+
@pytest.mark.parametrize("test_catalog", CATALOGS)
609+
def test_incompatible_partitioned_schema_evolution(
610+
test_catalog: Catalog, test_schema: Schema, test_partition_spec: PartitionSpec, database_name: str, table_name: str
611+
) -> None:
612+
if isinstance(test_catalog, HiveCatalog):
613+
pytest.skip("HiveCatalog does not support schema evolution")
614+
615+
identifier = (database_name, table_name)
616+
test_catalog.create_namespace(database_name)
617+
table = test_catalog.create_table(identifier, test_schema, partition_spec=test_partition_spec)
618+
assert test_catalog.table_exists(identifier)
619+
620+
with pytest.raises(ValidationError):
621+
with table.update_schema() as update:
622+
update.delete_column("VendorID")
623+
624+
# Assert column was not dropped
625+
assert "VendorID" in table.schema().column_names
626+
627+
with table.transaction() as transaction:
628+
with transaction.update_spec() as spec_update:
629+
spec_update.remove_field("VendorID")
630+
631+
with transaction.update_schema() as schema_update:
632+
schema_update.delete_column("VendorID")
633+
634+
assert table.spec() == PartitionSpec(PartitionField(2, 1001, DayTransform(), "tpep_pickup_day"), spec_id=1)
635+
assert table.schema() == Schema(NestedField(2, "tpep_pickup_datetime", TimestampType(), False))
636+
637+
638+
@pytest.mark.integration
639+
@pytest.mark.parametrize("test_catalog", CATALOGS)
640+
def test_incompatible_sorted_schema_evolution(
641+
test_catalog: Catalog, test_schema: Schema, test_sort_order: SortOrder, database_name: str, table_name: str
642+
) -> None:
643+
if isinstance(test_catalog, HiveCatalog):
644+
pytest.skip("HiveCatalog does not support schema evolution")
645+
646+
identifier = (database_name, table_name)
647+
test_catalog.create_namespace(database_name)
648+
table = test_catalog.create_table(identifier, test_schema, sort_order=test_sort_order)
649+
assert test_catalog.table_exists(identifier)
650+
651+
with pytest.raises(ValidationError):
652+
with table.update_schema() as update:
653+
update.delete_column("VendorID")
654+
655+
assert table.schema() == Schema(
656+
NestedField(1, "VendorID", IntegerType(), False), NestedField(2, "tpep_pickup_datetime", TimestampType(), False)
657+
)

tests/table/test_partitioning.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import pytest
2323

24+
from pyiceberg.exceptions import ValidationError
2425
from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionField, PartitionSpec
2526
from pyiceberg.schema import Schema
2627
from pyiceberg.transforms import (
@@ -259,3 +260,36 @@ def test_deserialize_partition_field_v3() -> None:
259260

260261
field = PartitionField.model_validate_json(json_partition_spec)
261262
assert field == PartitionField(source_id=1, field_id=1000, transform=TruncateTransform(width=19), name="str_truncate")
263+
264+
265+
def test_incompatible_source_column_not_found() -> None:
266+
schema = Schema(NestedField(1, "foo", IntegerType()), NestedField(2, "bar", IntegerType()))
267+
268+
spec = PartitionSpec(PartitionField(3, 1000, IdentityTransform(), "some_partition"))
269+
270+
with pytest.raises(ValidationError) as exc:
271+
spec.check_compatible(schema)
272+
273+
assert "Cannot find source column for partition field: 1000: some_partition: identity(3)" in str(exc.value)
274+
275+
276+
def test_incompatible_non_primitive_type() -> None:
277+
schema = Schema(NestedField(1, "foo", StructType()), NestedField(2, "bar", IntegerType()))
278+
279+
spec = PartitionSpec(PartitionField(1, 1000, IdentityTransform(), "some_partition"))
280+
281+
with pytest.raises(ValidationError) as exc:
282+
spec.check_compatible(schema)
283+
284+
assert "Cannot partition by non-primitive source field: struct<>" in str(exc.value)
285+
286+
287+
def test_incompatible_transform_source_type() -> None:
288+
schema = Schema(NestedField(1, "foo", IntegerType()), NestedField(2, "bar", IntegerType()))
289+
290+
spec = PartitionSpec(PartitionField(1, 1000, YearTransform(), "some_partition"))
291+
292+
with pytest.raises(ValidationError) as exc:
293+
spec.check_compatible(schema)
294+
295+
assert "Invalid source type int for transform: year" in str(exc.value)

tests/table/test_sorting.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020

2121
import pytest
2222

23+
from pyiceberg.exceptions import ValidationError
24+
from pyiceberg.schema import Schema
2325
from pyiceberg.table.metadata import TableMetadataUtil
2426
from pyiceberg.table.sorting import (
2527
UNSORTED_SORT_ORDER,
@@ -28,7 +30,8 @@
2830
SortField,
2931
SortOrder,
3032
)
31-
from pyiceberg.transforms import BucketTransform, IdentityTransform, VoidTransform
33+
from pyiceberg.transforms import BucketTransform, IdentityTransform, VoidTransform, YearTransform
34+
from pyiceberg.types import IntegerType, NestedField, StructType
3235

3336

3437
@pytest.fixture
@@ -114,3 +117,36 @@ def test_serialize_sort_field_v3() -> None:
114117
expected = SortField(source_id=19, transform=IdentityTransform(), null_order=NullOrder.NULLS_FIRST)
115118
payload = '{"source-ids":[19],"transform":"identity","direction":"asc","null-order":"nulls-first"}'
116119
assert SortField.model_validate_json(payload) == expected
120+
121+
122+
def test_incompatible_source_column_not_found(sort_order: SortOrder) -> None:
123+
schema = Schema(NestedField(1, "foo", IntegerType()), NestedField(2, "bar", IntegerType()))
124+
125+
with pytest.raises(ValidationError) as exc:
126+
sort_order.check_compatible(schema)
127+
128+
assert "Cannot find source column for sort field: 19 ASC NULLS FIRST" in str(exc.value)
129+
130+
131+
def test_incompatible_non_primitive_type() -> None:
132+
schema = Schema(NestedField(1, "foo", StructType()), NestedField(2, "bar", IntegerType()))
133+
134+
sort_order = SortOrder(SortField(source_id=1, transform=IdentityTransform(), null_order=NullOrder.NULLS_FIRST))
135+
136+
with pytest.raises(ValidationError) as exc:
137+
sort_order.check_compatible(schema)
138+
139+
assert "Cannot sort by non-primitive source field: 1: foo: optional struct<>" in str(exc.value)
140+
141+
142+
def test_incompatible_transform_source_type() -> None:
143+
schema = Schema(NestedField(1, "foo", IntegerType()), NestedField(2, "bar", IntegerType()))
144+
145+
sort_order = SortOrder(
146+
SortField(source_id=1, transform=YearTransform(), null_order=NullOrder.NULLS_FIRST),
147+
)
148+
149+
with pytest.raises(ValidationError) as exc:
150+
sort_order.check_compatible(schema)
151+
152+
assert "Invalid source type int for transform: year" in str(exc.value)

0 commit comments

Comments
 (0)