diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index ad916171c5..827e8e7e86 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -569,14 +569,9 @@ def __getnewargs__(self) -> tuple[BoundTerm]: class BoundIsNull(BoundUnaryPredicate): - def __new__(cls, term: BoundTerm) -> BooleanExpression: # pylint: disable=W0221 - if term.ref().field.required: - return AlwaysFalse() - return super().__new__(cls) - def __invert__(self) -> BoundNotNull: """Transform the Expression into its negated version.""" - return BoundNotNull(self.term) + return BoundNotNull(term=self.term) @property def as_unbound(self) -> type[IsNull]: @@ -584,14 +579,9 @@ def as_unbound(self) -> type[IsNull]: class BoundNotNull(BoundUnaryPredicate): - def __new__(cls, term: BoundTerm) -> BooleanExpression: # pylint: disable=W0221 - if term.ref().field.required: - return AlwaysTrue() - return super().__new__(cls) - def __invert__(self) -> BoundIsNull: """Transform the Expression into its negated version.""" - return BoundIsNull(self.term) + return BoundIsNull(term=self.term) @property def as_unbound(self) -> type[NotNull]: @@ -604,6 +594,13 @@ class IsNull(UnaryPredicate): def __init__(self, term: str | UnboundTerm, **_: Any) -> None: super().__init__(term) + def bind(self, schema: Schema, case_sensitive: bool = True) -> BooleanExpression: + """Bind the term, folding to AlwaysFalse() if the field and all its ancestors are required.""" + bound_term = self.term.bind(schema, case_sensitive) + if schema.is_field_required_in_path(bound_term.ref().field.field_id): + return AlwaysFalse() + return BoundIsNull(term=bound_term) + def __invert__(self) -> NotNull: """Transform the Expression into its negated version.""" return NotNull(self.term) @@ -619,6 +616,13 @@ class NotNull(UnaryPredicate): def __init__(self, term: str | UnboundTerm, **_: Any) -> None: super().__init__(term) + def bind(self, schema: Schema, case_sensitive: bool = True) -> BooleanExpression: + """Bind the term, folding to AlwaysTrue() if the field and all its ancestors are required.""" + bound_term = self.term.bind(schema, case_sensitive) + if schema.is_field_required_in_path(bound_term.ref().field.field_id): + return AlwaysTrue() + return BoundNotNull(term=bound_term) + def __invert__(self) -> IsNull: """Transform the Expression into its negated version.""" return IsNull(self.term) diff --git a/pyiceberg/expressions/visitors.py b/pyiceberg/expressions/visitors.py index 7504548507..e629cd86f3 100644 --- a/pyiceberg/expressions/visitors.py +++ b/pyiceberg/expressions/visitors.py @@ -926,9 +926,12 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression: field_value = ( self.projected_field_values[field_id] if field.field_id in self.projected_field_values else field.initial_default ) + # The field is absent from the file, so a required field can still be null here. + # Evaluate against an optional copy, otherwise the required leaf makes IsNull fold to false. + optional_field = field.model_copy(update={"required": False}) return ( AlwaysTrue() - if expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive)(Record(field_value)) + if expression_evaluator(Schema(optional_field), pred, case_sensitive=self.case_sensitive)(Record(field_value)) else AlwaysFalse() ) diff --git a/pyiceberg/schema.py b/pyiceberg/schema.py index d57095f58d..a8854f9a49 100644 --- a/pyiceberg/schema.py +++ b/pyiceberg/schema.py @@ -308,6 +308,26 @@ def accessor_for_field(self, field_id: int) -> Accessor: return self._lazy_id_to_accessor[field_id] + def is_field_required_in_path(self, field_id: int) -> bool: + """Check whether a field and every struct ancestor on its path to the root are required. + + Args: + field_id (int): The ID of the field. + + Returns: + bool: True if the field and all of its ancestors are required, False otherwise. + """ + if not self.find_field(field_id).required: + return False + + parent_id = self._lazy_id_to_parent.get(field_id) + while parent_id is not None: + if not self.find_field(parent_id).required: + return False + parent_id = self._lazy_id_to_parent.get(parent_id) + + return True + def identifier_field_names(self) -> set[str]: """Return the names of the identifier fields. diff --git a/tests/expressions/test_expressions.py b/tests/expressions/test_expressions.py index ff0c5e80aa..81e1288cf5 100644 --- a/tests/expressions/test_expressions.py +++ b/tests/expressions/test_expressions.py @@ -86,7 +86,7 @@ def test_isnull_inverse() -> None: def test_isnull_bind() -> None: schema = Schema(NestedField(2, "a", IntegerType()), schema_id=1) - bound = BoundIsNull(BoundReference(schema.find_field(2), schema.accessor_for_field(2))) + bound = BoundIsNull(term=BoundReference(schema.find_field(2), schema.accessor_for_field(2))) assert IsNull(Reference("a")).bind(schema) == bound @@ -137,7 +137,7 @@ def test_notnull_inverse() -> None: def test_notnull_bind() -> None: schema = Schema(NestedField(2, "a", IntegerType()), schema_id=1) - bound = BoundNotNull(BoundReference(schema.find_field(2), schema.accessor_for_field(2))) + bound = BoundNotNull(term=BoundReference(schema.find_field(2), schema.accessor_for_field(2))) assert NotNull(Reference("a")).bind(schema) == bound @@ -159,7 +159,7 @@ def test_notnull_bind_top_struct() -> None: ), schema_id=1, ) - bound = BoundNotNull(BoundReference(schema.find_field(3), schema.accessor_for_field(3))) + bound = BoundNotNull(term=BoundReference(schema.find_field(3), schema.accessor_for_field(3))) assert NotNull(Reference("struct_col")).bind(schema) == bound @@ -819,19 +819,29 @@ def test_bound_reference_field_property() -> None: def test_bound_is_null(term: BoundReference) -> None: - bound_is_null = BoundIsNull(term) + bound_is_null = BoundIsNull(term=term) assert str(bound_is_null) == f"BoundIsNull(term={str(term)})" assert repr(bound_is_null) == f"BoundIsNull(term={repr(term)})" assert bound_is_null == eval(repr(bound_is_null)) def test_bound_is_not_null(term: BoundReference) -> None: - bound_not_null = BoundNotNull(term) + bound_not_null = BoundNotNull(term=term) assert str(bound_not_null) == f"BoundNotNull(term={str(term)})" assert repr(bound_not_null) == f"BoundNotNull(term={repr(term)})" assert bound_not_null == eval(repr(bound_not_null)) +def test_bound_null_predicates_do_not_fold_on_construction() -> None: + term = BoundReference( + field=NestedField(field_id=1, name="foo", field_type=StringType(), required=True), + accessor=Accessor(position=0), + ) + + assert isinstance(BoundIsNull(term=term), BoundIsNull) + assert isinstance(BoundNotNull(term=term), BoundNotNull) + + def test_is_null() -> None: ref = Reference("a") is_null = IsNull(ref) @@ -1302,19 +1312,61 @@ def test_eq_bound_expression(bound_reference_str: BoundReference) -> None: def test_nested_bind() -> None: schema = Schema(NestedField(1, "foo", StructType(NestedField(2, "bar", StringType()))), schema_id=1) - bound = BoundIsNull(BoundReference(schema.find_field(2), schema.accessor_for_field(2))) + bound = BoundIsNull(term=BoundReference(schema.find_field(2), schema.accessor_for_field(2))) assert IsNull(Reference("foo.bar")).bind(schema) == bound +def test_is_null_required_field_under_optional_ancestor_does_not_fold() -> None: + schema = Schema( + NestedField(1, "foo", StructType(NestedField(2, "bar", StringType(), required=True)), required=False), + schema_id=1, + ) + + assert isinstance(IsNull(Reference("foo.bar")).bind(schema), BoundIsNull) + assert isinstance(NotNull(Reference("foo.bar")).bind(schema), BoundNotNull) + + +def test_is_null_required_struct_between_optional_ancestor_and_leaf_does_not_fold() -> None: + schema = Schema( + NestedField( + 1, + "foo", + StructType( + NestedField( + 2, + "bar", + StructType(NestedField(3, "baz", StringType(), required=True)), + required=True, + ) + ), + required=False, + ), + schema_id=1, + ) + + assert isinstance(IsNull(Reference("foo.bar.baz")).bind(schema), BoundIsNull) + assert isinstance(NotNull(Reference("foo.bar.baz")).bind(schema), BoundNotNull) + + +def test_is_null_required_field_under_required_ancestor_folds() -> None: + schema = Schema( + NestedField(1, "foo", StructType(NestedField(2, "bar", StringType(), required=True)), required=True), + schema_id=1, + ) + + assert IsNull(Reference("foo.bar")).bind(schema) == AlwaysFalse() + assert NotNull(Reference("foo.bar")).bind(schema) == AlwaysTrue() + + def test_bind_dot_name() -> None: schema = Schema(NestedField(1, "foo.bar", StringType()), schema_id=1) - bound = BoundIsNull(BoundReference(schema.find_field(1), schema.accessor_for_field(1))) + bound = BoundIsNull(term=BoundReference(schema.find_field(1), schema.accessor_for_field(1))) assert IsNull(Reference("foo.bar")).bind(schema) == bound def test_nested_bind_with_dot_name() -> None: schema = Schema(NestedField(1, "foo.bar", StructType(NestedField(2, "baz", StringType()))), schema_id=1) - bound = BoundIsNull(BoundReference(schema.find_field(2), schema.accessor_for_field(2))) + bound = BoundIsNull(term=BoundReference(schema.find_field(2), schema.accessor_for_field(2))) assert IsNull(Reference("foo.bar.baz")).bind(schema) == bound diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 92d533651c..0290703bc3 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -78,6 +78,7 @@ LessThanOrEqual, Not, NotEqualTo, + NotNull, Or, ) from pyiceberg.expressions.literals import literal @@ -852,13 +853,13 @@ def bound_double_reference() -> BoundReference: def test_expr_is_null_to_pyarrow(bound_reference: BoundReference) -> None: assert ( - repr(expression_to_pyarrow(BoundIsNull(bound_reference))) + repr(expression_to_pyarrow(BoundIsNull(term=bound_reference))) == "" ) def test_expr_not_null_to_pyarrow(bound_reference: BoundReference) -> None: - assert repr(expression_to_pyarrow(BoundNotNull(bound_reference))) == "" + assert repr(expression_to_pyarrow(BoundNotNull(term=bound_reference))) == "" def test_expr_is_nan_to_pyarrow(bound_double_reference: BoundReference) -> None: @@ -972,14 +973,14 @@ def test_uuid_expressions_to_pyarrow() -> None: def test_and_to_pyarrow(bound_reference: BoundReference) -> None: assert ( - repr(expression_to_pyarrow(And(BoundEqualTo(bound_reference, literal("hello")), BoundIsNull(bound_reference)))) + repr(expression_to_pyarrow(And(BoundEqualTo(bound_reference, literal("hello")), BoundIsNull(term=bound_reference)))) == '' ) def test_or_to_pyarrow(bound_reference: BoundReference) -> None: assert ( - repr(expression_to_pyarrow(Or(BoundEqualTo(bound_reference, literal("hello")), BoundIsNull(bound_reference)))) + repr(expression_to_pyarrow(Or(BoundEqualTo(bound_reference, literal("hello")), BoundIsNull(term=bound_reference)))) == '' ) @@ -3674,6 +3675,32 @@ def test_scan_plans_uuid_identity_partitions(catalog: InMemoryCatalog) -> None: assert scan.count() == len(expected), row_filter +def test_scan_keeps_required_field_under_optional_ancestor(catalog: InMemoryCatalog) -> None: + schema = Schema( + NestedField(1, "s", StructType(NestedField(2, "x", LongType(), required=True)), required=False), + schema_id=1, + ) + catalog.create_namespace("default") + table = catalog.create_table("default.test_scan_is_null_nested", schema=schema) + table.append(pa.table({"s": pa.array([None], type=pa.struct([pa.field("x", pa.int64(), nullable=False)]))})) + + assert len(list(table.scan(row_filter=IsNull("s.x")).plan_files())) == 1 + assert table.scan(row_filter=IsNull("s.x")).to_arrow().num_rows == 1 + assert table.scan(row_filter=NotNull("s.x")).to_arrow().num_rows == 0 + + +def test_scan_keeps_required_field_added_after_file_write(catalog: InMemoryCatalog) -> None: + catalog.create_namespace("default") + table = catalog.create_table("default.test_scan_is_null_evolved", schema=Schema(NestedField(1, "id", LongType()))) + table.append(pa.table({"id": [1, 2]})) + + with table.update_schema() as update: + update.add_column("s", StructType(NestedField(3, "x", LongType(), required=True))) + + assert table.scan(row_filter=IsNull("s.x")).to_arrow()["id"].to_pylist() == [1, 2] + assert table.scan(row_filter=NotNull("s.x")).to_arrow().num_rows == 0 + + def test_scan_prunes_uuid_files_by_bounds(catalog: InMemoryCatalog) -> None: schema = Schema( NestedField(id=1, name="id", field_type=LongType(), required=False), diff --git a/tests/io/test_pyarrow_visitor.py b/tests/io/test_pyarrow_visitor.py index 23b2b0d685..6f8f082443 100644 --- a/tests/io/test_pyarrow_visitor.py +++ b/tests/io/test_pyarrow_visitor.py @@ -1016,7 +1016,7 @@ def bound_eq_double_field(bound_reference_double: BoundReference) -> BoundEqualT @pytest.fixture def bound_is_null_double_field(bound_reference_double: BoundReference) -> BoundIsNull: - return BoundIsNull(bound_reference_double) + return BoundIsNull(term=bound_reference_double) def test_collect_null_nan_unmentioned_terms( diff --git a/tests/table/test_init.py b/tests/table/test_init.py index b26b4db4f6..7386238040 100644 --- a/tests/table/test_init.py +++ b/tests/table/test_init.py @@ -2679,6 +2679,23 @@ def test_partial_delete_keeps_earlier_deletes_outside_the_filter(catalog: Catalo assert table.scan().to_arrow()["k"].to_pylist() == [3] +def test_delete_keeps_null_rows_when_required_field_under_optional_ancestor(catalog: Catalog) -> None: + import pyarrow as pa + + catalog.create_namespace("default") + schema = Schema( + NestedField(1, "id", LongType(), required=False), + NestedField(2, "s", StructType(NestedField(3, "x", LongType(), required=True)), required=False), + ) + table = catalog.create_table("default.delete_nested_optional_struct", schema=schema) + struct_type = pa.struct([pa.field("x", pa.int64(), nullable=False)]) + table.append(pa.table({"id": [1, 2], "s": pa.array([None, {"x": 5}], type=struct_type)})) + + table.delete("s.x == 5") + + assert table.scan().to_arrow()["id"].to_pylist() == [1] + + def test_static_table_forwards_location_to_table_file_io(metadata_location: str, monkeypatch: pytest.MonkeyPatch) -> None: seen_locations: list[str | None] = [] real_load_file_io = load_file_io diff --git a/tests/test_schema.py b/tests/test_schema.py index ed0982c409..8b4805b435 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -446,6 +446,45 @@ def __getitem__(self, pos: int) -> Any: assert inner_accessor.get(container) == "name" +def test_is_field_required_in_path() -> None: + schema = Schema( + NestedField(1, "req_top", StringType(), required=True), + NestedField(2, "opt_top", StringType(), required=False), + NestedField( + 3, + "opt_struct", + StructType(NestedField(4, "req_child", StringType(), required=True)), + required=False, + ), + NestedField( + 5, + "req_struct", + StructType(NestedField(6, "req_grandchild", StringType(), required=True)), + required=True, + ), + NestedField( + 7, + "deep_opt_struct", + StructType( + NestedField( + 8, + "deep_req_struct", + StructType(NestedField(9, "deep_req_child", StringType(), required=True)), + required=True, + ) + ), + required=False, + ), + schema_id=1, + ) + + assert schema.is_field_required_in_path(1) + assert not schema.is_field_required_in_path(2) + assert not schema.is_field_required_in_path(4) + assert schema.is_field_required_in_path(6) + assert not schema.is_field_required_in_path(9) + + def test_serialize_schema(table_schema_with_full_nested_fields: Schema) -> None: actual = table_schema_with_full_nested_fields.model_dump_json() expected = (