diff --git a/pyiceberg/expressions/visitors.py b/pyiceberg/expressions/visitors.py index bc66dccbde..fec8666cf4 100644 --- a/pyiceberg/expressions/visitors.py +++ b/pyiceberg/expressions/visitors.py @@ -52,6 +52,7 @@ BoundUnaryPredicate, IsNull, Not, + NotIn, NotNull, Or, UnboundPredicate, @@ -925,6 +926,10 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression: if field.field_id in self.projected_field_values else field.initial_default_value ) + if field_value is None and not isinstance(pred, (IsNull, NotNull, NotIn)): + # A null value only decides IsNull and NotNull. The other predicates do not match it, + # as in a file that stores the null. NotIn is evaluated below, as it keeps nulls there too. + return AlwaysFalse() return ( AlwaysTrue() if expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive)(Record(field_value)) @@ -944,7 +949,8 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression: def translate_column_names( expr: BooleanExpression, file_schema: Schema, case_sensitive: bool = True, projected_field_values: dict[int, Any] = EMPTY_DICT ) -> BooleanExpression: - return visit(expr, _ColumnNameTranslator(file_schema, case_sensitive, projected_field_values)) + # Negations are pushed down first, so that Not does not turn a predicate on a missing null value into a match + return visit(rewrite_not(expr), _ColumnNameTranslator(file_schema, case_sensitive, projected_field_values)) class _ExpressionFieldIDs(BooleanExpressionVisitor[set[int]]): diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index 3ca9dead9c..c526b97517 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -1837,6 +1837,30 @@ def test_count_reads_null_partition_only_when_filter_compares_it(catalog: Catalo assert tbl.scan(row_filter=row_filter).count() == expected, row_filter +def test_scan_null_from_missing_column_matches_stored_null(catalog: Catalog) -> None: + catalog.create_namespace_if_not_exists("default") + tbl = catalog.create_table( + f"default.scan_missing_column_{catalog.name}", Schema(NestedField(1, "id", LongType(), required=False)) + ) + # This file has no status column + tbl.append(pa.Table.from_pydict({"id": [1, 2]}, schema=schema_to_pyarrow(tbl.schema()))) + with tbl.update_schema() as update: + update.add_column("status", StringType()) + tbl.append(pa.Table.from_pydict({"id": [3, 4, 5], "status": ["ok", "bad", None]}, schema=schema_to_pyarrow(tbl.schema()))) + + row_filters = ["status != 'ok'", "not status = 'ok'", "status not like 'o%'", "status not in ('ok', 'x')", "status is null"] + before = {row_filter: sorted(tbl.scan(row_filter=row_filter).to_arrow()["id"].to_pylist()) for row_filter in row_filters} + assert before["status != 'ok'"] == [4] + assert before["status is null"] == [1, 2, 5] + + # Rewriting the rows into one file stores the nulls, which must not change the results + tbl.overwrite(tbl.scan().to_arrow()) + for row_filter in row_filters: + scan = tbl.scan(row_filter=row_filter) + assert sorted(scan.to_arrow()["id"].to_pylist()) == before[row_filter], row_filter + assert scan.count() == len(before[row_filter]), row_filter + + def _nan_partitioned_table(catalog: Catalog, name: str) -> Table: iceberg_schema = Schema( NestedField(1, "id", IntegerType(), required=False), diff --git a/tests/expressions/test_visitors.py b/tests/expressions/test_visitors.py index 53d6f80ef3..81df087b7c 100644 --- a/tests/expressions/test_visitors.py +++ b/tests/expressions/test_visitors.py @@ -1888,6 +1888,77 @@ def test_translate_column_names_missing_column_match_explicit_null() -> None: assert translated_expr == AlwaysTrue() +@pytest.mark.parametrize( + "unbound_expr,expected", + [ + # A file that stores the null gives the same results, as the PyArrow filter drops unknown comparisons + (IsNull("missing_col"), AlwaysTrue()), + (NotNull("missing_col"), AlwaysFalse()), + (EqualTo("missing_col", "a"), AlwaysFalse()), + (NotEqualTo("missing_col", "a"), AlwaysFalse()), + (LessThan("missing_col", "a"), AlwaysFalse()), + (In("missing_col", {"a", "b"}), AlwaysFalse()), + (StartsWith("missing_col", "a"), AlwaysFalse()), + (NotStartsWith("missing_col", "a"), AlwaysFalse()), + (IsNaN("missing_double"), AlwaysFalse()), + (NotNaN("missing_double"), AlwaysFalse()), + (Not(EqualTo("missing_col", "a")), AlwaysFalse()), + (Not(IsNull("missing_col")), AlwaysFalse()), + # The PyArrow filter keeps nulls for NotIn + (NotIn("missing_col", {"a", "b"}), AlwaysTrue()), + ], +) +def test_translate_column_names_missing_column_null_only_decides_null_checks( + unbound_expr: BooleanExpression, expected: BooleanExpression +) -> None: + """Test translate_column_names when a missing column without a default is compared with a value.""" + original_schema = Schema( + NestedField(field_id=1, name="existing_col", field_type=StringType(), required=False), + NestedField(field_id=2, name="missing_col", field_type=StringType(), required=False), + NestedField(field_id=3, name="missing_double", field_type=DoubleType(), required=False), + schema_id=1, + ) + file_schema = Schema( + NestedField(field_id=1, name="existing_col", field_type=StringType(), required=False), + schema_id=1, + ) + + bound_expr = visit(unbound_expr, visitor=BindVisitor(schema=original_schema, case_sensitive=True)) + assert translate_column_names(bound_expr, file_schema, case_sensitive=True) == expected + # A null projected value, such as a null identity partition value, is treated the same way + assert translate_column_names(bound_expr, file_schema, projected_field_values={2: None, 3: None}) == expected + + +@pytest.mark.parametrize( + "unbound_expr,expected", + [ + (NotEqualTo("missing_col", "a"), AlwaysFalse()), + (NotEqualTo("missing_col", "b"), AlwaysTrue()), + (NotStartsWith("missing_col", "a"), AlwaysFalse()), + (NotStartsWith("missing_col", "b"), AlwaysTrue()), + (NotIn("missing_col", {"a", "b"}), AlwaysFalse()), + (NotIn("missing_col", {"b", "c"}), AlwaysTrue()), + (IsNull("missing_col"), AlwaysFalse()), + ], +) +def test_translate_column_names_missing_column_with_initial_default_negated_predicates( + unbound_expr: BooleanExpression, expected: BooleanExpression +) -> None: + """Test translate_column_names keeps evaluating negated predicates against the initial_default.""" + original_schema = Schema( + NestedField(field_id=1, name="existing_col", field_type=StringType(), required=False), + NestedField(field_id=2, name="missing_col", field_type=StringType(), required=False, initial_default="a"), + schema_id=1, + ) + file_schema = Schema( + NestedField(field_id=1, name="existing_col", field_type=StringType(), required=False), + schema_id=1, + ) + + bound_expr = visit(unbound_expr, visitor=BindVisitor(schema=original_schema, case_sensitive=True)) + assert translate_column_names(bound_expr, file_schema, case_sensitive=True) == expected + + def test_translate_column_names_missing_column_with_temporal_initial_default() -> None: """Test translate_column_names compares temporal initial_default values in the form the bound literal uses.""" file_schema = Schema(NestedField(field_id=1, name="existing_col", field_type=StringType(), required=False), schema_id=1)