diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index ad916171c5..ef5fa3fa7d 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -569,11 +569,6 @@ 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) @@ -584,11 +579,6 @@ 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) @@ -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(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(bound_term) + def __invert__(self) -> IsNull: """Transform the Expression into its negated version.""" return IsNull(self.term) 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..a55da55487 100644 --- a/tests/expressions/test_expressions.py +++ b/tests/expressions/test_expressions.py @@ -832,6 +832,16 @@ def test_bound_is_not_null(term: BoundReference) -> None: 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), BoundIsNull) + assert isinstance(BoundNotNull(term), BoundNotNull) + + def test_is_null() -> None: ref = Reference("a") is_null = IsNull(ref) @@ -1306,6 +1316,26 @@ def test_nested_bind() -> None: 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_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))) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 92d533651c..1893326db1 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 @@ -3674,6 +3675,20 @@ 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_prunes_uuid_files_by_bounds(catalog: InMemoryCatalog) -> None: schema = Schema( NestedField(id=1, name="id", field_type=LongType(), required=False), diff --git a/tests/test_schema.py b/tests/test_schema.py index ed0982c409..57989bbd72 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -446,6 +446,31 @@ 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, + ), + 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) + + def test_serialize_schema(table_schema_with_full_nested_fields: Schema) -> None: actual = table_schema_with_full_nested_fields.model_dump_json() expected = (