Skip to content
Open
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
109 changes: 101 additions & 8 deletions pyiceberg/expressions/visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,13 +862,30 @@ def inclusive_projection(
return InclusiveProjection(schema, spec, case_sensitive).project


# These predicates use Arrow's NULL behavior. != and NOT IN retain the existing default-value result (see #4276).
_NULL_STRICT_PREDICATES = (
BoundEqualTo,
BoundIn,
BoundLessThan,
BoundLessThanOrEqual,
BoundGreaterThan,
BoundGreaterThanOrEqual,
BoundIsNull,
BoundNotNull,
)

# A NOT over these predicates is pushed into their complements, so NOT (c != 5) is handled as c = 5
_NESTED_NOT_PREDICATES = (*_NULL_STRICT_PREDICATES, BoundNotEqualTo, BoundNotIn)


class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]):
"""Converts the column names with the ones in the actual file.

Args:
file_schema (Schema): The schema of the file.
case_sensitive (bool): Whether to consider case when binding a reference to a field in a schema, defaults to True.
projected_field_values (Dict[int, Any]): Values for projected fields not present in the data file.
table_schema (Schema | None): The table schema, used to find the struct ancestors of a missing field.

Raises:
TypeError: In the case of an UnboundPredicate.
Expand All @@ -878,11 +895,19 @@ class _ColumnNameTranslator(BooleanExpressionVisitor[BooleanExpression]):
file_schema: Schema
case_sensitive: bool
projected_field_values: dict[int, Any]
table_schema: Schema | None

def __init__(self, file_schema: Schema, case_sensitive: bool, projected_field_values: dict[int, Any] = EMPTY_DICT) -> None:
def __init__(
self,
file_schema: Schema,
case_sensitive: bool,
projected_field_values: dict[int, Any] = EMPTY_DICT,
table_schema: Schema | None = None,
) -> None:
self.file_schema = file_schema
self.case_sensitive = case_sensitive
self.projected_field_values = projected_field_values
self.table_schema = table_schema

def visit_true(self) -> BooleanExpression:
return AlwaysTrue()
Expand Down Expand Up @@ -926,11 +951,16 @@ 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
)
return (
AlwaysTrue()
if expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive)(Record(field_value))
else AlwaysFalse()
)
evaluate = expression_evaluator(Schema(field), pred, case_sensitive=self.case_sensitive)
matches_value = evaluate(Record(field_value))
if self.table_schema is None or not isinstance(predicate, _NULL_STRICT_PREDICATES):
return AlwaysTrue() if matches_value else AlwaysFalse()
# A row whose optional ancestor struct is NULL reads the field as NULL, so it matches like a NULL value
matches_null = evaluate(Record(None))
if matches_value == matches_null:
return AlwaysTrue() if matches_value else AlwaysFalse()
present = self._ancestors_present(self.table_schema, field.field_id)
return present if matches_value else Not(present)

if isinstance(predicate, BoundUnaryPredicate):
return predicate.as_unbound(file_column_name)
Expand All @@ -941,11 +971,74 @@ def visit_bound_predicate(self, predicate: BoundPredicate) -> BooleanExpression:
else:
raise ValueError(f"Unsupported predicate: {predicate}")

def _ancestors_present(self, table_schema: Schema, field_id: int) -> BooleanExpression:
"""Return the rows in which every optional struct around a missing field is present."""
present: BooleanExpression = AlwaysTrue()
for parent_id in _ancestor_ids(table_schema, field_id):
parent = table_schema.find_field(parent_id)
if not parent.required:
parent_name = self.file_schema.find_column_name(parent_id)
if parent_name is None:
# The struct is missing from the file too, so its value is the same in every row
if self.projected_field_values.get(parent_id, parent.initial_default) is None:
return AlwaysFalse()
else:
present = And(present, NotNull(parent_name))
return present


def _ancestor_ids(schema: Schema, field_id: int) -> list[int]:
"""Return the IDs of the parents of a field, from the nearest one outwards."""
ancestor_ids: list[int] = []
parent_id = schema._lazy_id_to_parent.get(field_id)
while parent_id is not None:
ancestor_ids.append(parent_id)
parent_id = schema._lazy_id_to_parent.get(parent_id)
return ancestor_ids


def _is_missing_nested_field(predicate: BoundPredicate, file_schema: Schema, table_schema: Schema) -> bool:
"""Return whether the predicate reads a field that is missing from the file, under an optional struct."""
field_id = predicate.term.ref().field.field_id
return file_schema.find_column_name(field_id) is None and any(
not table_schema.find_field(parent_id).required for parent_id in _ancestor_ids(table_schema, field_id)
)


def _rewrite_nested_not(
expr: BooleanExpression, file_schema: Schema, table_schema: Schema, negated: bool = False
) -> BooleanExpression:
"""Push NOT down to the predicates, and complement those on a missing nested field.

A row whose optional struct is NULL reads such a field as NULL. NOT (c < 4) must not match that row, as c >= 4
does not. Other negations are kept, so their results stay the same as on main.
"""
if isinstance(expr, Not):
return _rewrite_nested_not(expr.child, file_schema, table_schema, not negated)
if isinstance(expr, (And, Or)):
# De Morgan's laws: NOT (A AND B) is NOT A OR NOT B, and NOT (A OR B) is NOT A AND NOT B
left = _rewrite_nested_not(expr.left, file_schema, table_schema, negated)
right = _rewrite_nested_not(expr.right, file_schema, table_schema, negated)
if isinstance(expr, And) != negated:
return And(left, right)
return Or(left, right)
if not negated:
return expr
if isinstance(expr, _NESTED_NOT_PREDICATES) and _is_missing_nested_field(expr, file_schema, table_schema):
return ~expr
return Not(child=expr)


def translate_column_names(
expr: BooleanExpression, file_schema: Schema, case_sensitive: bool = True, projected_field_values: dict[int, Any] = EMPTY_DICT
expr: BooleanExpression,
file_schema: Schema,
case_sensitive: bool = True,
projected_field_values: dict[int, Any] = EMPTY_DICT,
table_schema: Schema | None = None,
) -> BooleanExpression:
return visit(expr, _ColumnNameTranslator(file_schema, case_sensitive, projected_field_values))
if table_schema is not None:
expr = _rewrite_nested_not(expr, file_schema, table_schema)
return visit(expr, _ColumnNameTranslator(file_schema, case_sensitive, projected_field_values, table_schema))


class _ExpressionFieldIDs(BooleanExpressionVisitor[set[int]]):
Expand Down
36 changes: 24 additions & 12 deletions pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,17 +946,19 @@ def _get_field_name(self, term: BoundTerm) -> str | tuple[str, ...]:
For nested struct fields, returns a tuple of field names (e.g., ("mazeMetadata", "run_id")).
For top-level fields, returns just the field name as a string.

The path is built from the field IDs, because a struct name can contain a dot (e.g., "old.pt").
PyArrow requires nested field references as tuples, not dotted strings.
"""
if self._schema is not None:
# Use the schema to get the full dotted path for nested fields
full_name = self._schema.find_column_name(term.ref().field.field_id)
if full_name is not None:
# If the field name contains dots, it's a nested field
# Convert "parent.child" to ("parent", "child") for PyArrow
if "." in full_name:
return tuple(full_name.split("."))
return full_name
field_id = term.ref().field.field_id
if self._schema.find_column_name(field_id) is not None:
# Walk up the struct ancestors by field ID, instead of splitting the dotted full name
names = [self._schema.find_field(field_id).name]
parent_id = self._schema._lazy_id_to_parent.get(field_id)
while parent_id is not None:
names.insert(0, self._schema.find_field(parent_id).name)
parent_id = self._schema._lazy_id_to_parent.get(parent_id)
return tuple(names) if len(names) > 1 else names[0]
# Fallback to just the field name if schema is not available
return term.ref().field.name

Expand Down Expand Up @@ -1871,10 +1873,12 @@ def _task_to_record_batches(
pyarrow_filter = None
if bound_row_filter is not AlwaysTrue():
translated_row_filter = translate_column_names(
bound_row_filter, file_schema, case_sensitive=case_sensitive, projected_field_values=projected_missing_fields
bound_row_filter,
file_schema,
case_sensitive=case_sensitive,
projected_field_values=projected_missing_fields,
table_schema=table_schema,
)
# Rewrite NOT into the complementary predicates, as the manifest and metrics evaluators do, so a row
# matches the same predicate that decided whether its file was read
bound_file_filter = rewrite_not(bind(file_schema, translated_row_filter, case_sensitive=case_sensitive))
pyarrow_filter = expression_to_pyarrow(bound_file_filter, file_schema)

Expand Down Expand Up @@ -2056,6 +2060,14 @@ def __init__(
# Register extension types before inspecting any data file schemas.
self._arrow_schema = schema_to_pyarrow(projected_schema, include_field_ids=False)
self._bound_row_filter = bind(table_metadata.schema(), row_filter, case_sensitive=case_sensitive)
# A filter on a nested field also reads its struct ancestors, which are NULL where the field reads as NULL
schema = table_metadata.schema()
self._filter_ancestor_field_ids: set[int] = set()
for field_id in extract_field_ids(self._bound_row_filter):
parent_id = schema._lazy_id_to_parent.get(field_id)
while parent_id is not None and isinstance(schema.find_type(parent_id), StructType):
self._filter_ancestor_field_ids.add(parent_id)
parent_id = schema._lazy_id_to_parent.get(parent_id)
self._case_sensitive = case_sensitive
self._limit = limit
self._downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE)
Expand All @@ -2065,7 +2077,7 @@ def __init__(
def _projected_field_ids(self) -> set[int]:
"""Set of field IDs that should be projected from the data files."""
schema = self._table_metadata.schema()
filter_field_ids = extract_field_ids(self._bound_row_filter)
filter_field_ids = extract_field_ids(self._bound_row_filter) | self._filter_ancestor_field_ids
# A list or map cannot be projected by its own ID, so a filter on one reads its nested fields instead
nested_field_ids = prune_columns(
schema, {id for id in filter_field_ids if isinstance(schema.find_type(id), (MapType, ListType))}
Expand Down
16 changes: 16 additions & 0 deletions tests/expressions/test_visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1770,6 +1770,22 @@ def test_translate_column_names_different_column_names() -> None:
assert translated_expr.literal == literal("test_value")


def test_translate_column_names_not_on_missing_top_level_column_keeps_its_result() -> None:
"""NOT over a predicate on a missing top-level column keeps the result of its default-value constant."""
table_schema = Schema(
NestedField(field_id=1, name="id", field_type=IntegerType(), required=False),
NestedField(field_id=2, name="d", field_type=IntegerType(), required=False),
schema_id=1,
)
file_schema = Schema(NestedField(field_id=1, name="id", field_type=IntegerType(), required=False), schema_id=1)
for unbound_expr, expected in [
(Not(LessThan("d", 4)), AlwaysTrue()),
(Not(IsNull("d")), AlwaysFalse()),
]:
bound_expr = visit(unbound_expr, visitor=BindVisitor(schema=table_schema, case_sensitive=True))
assert translate_column_names(bound_expr, file_schema, case_sensitive=True) == expected, unbound_expr


def test_translate_column_names_missing_column() -> None:
"""Test translate_column_names when column is missing from file schema (such as in schema evolution)."""
# Original schema
Expand Down
Loading
Loading