Skip to content
Closed
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
67 changes: 38 additions & 29 deletions pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2389,7 +2389,8 @@ def struct(
return pa.StructArray.from_arrays(
arrays=field_arrays,
fields=pa.struct(fields),
mask=struct_array.is_null() if isinstance(struct_array, pa.StructArray) else None,
# A validity bitmap on struct map keys aborts PyArrow: https://github.com/apache/arrow/issues/51029
mask=struct_array.is_null() if isinstance(struct_array, pa.StructArray) and struct_array.null_count else None,
)

def field(self, field: NestedField, _: pa.Array | None, field_array: pa.Array | None) -> pa.Array | None:
Expand All @@ -2398,19 +2399,24 @@ def field(self, field: NestedField, _: pa.Array | None, field_array: pa.Array |
def list(self, list_type: ListType, list_array: pa.Array | None, value_array: pa.Array | None) -> pa.Array | None:
if isinstance(list_array, (pa.ListArray, pa.LargeListArray, pa.FixedSizeListArray)) and value_array is not None:
list_initializer = pa.large_list if isinstance(list_array, pa.LargeListArray) else pa.list_
if isinstance(value_array, pa.StructArray):
# This can be removed once this has been fixed:
# https://github.com/apache/arrow/issues/38809
# Keep the validity and offsets buffers of the original array, otherwise null lists become empty lists
list_array = pa.Array.from_buffers(
list_initializer(value_array.type),
len(list_array),
list_array.buffers()[:2],
list_array.null_count,
list_array.offset,
[value_array],
)
value_array = self._cast_if_needed(list_type.element_field, value_array)
# Rebuild the list around the projected values, so the cast below does not cast the unprojected children.
# Keep the validity and offsets buffers of the original array, otherwise null lists become empty lists.
# A fixed-size list has no offsets buffer, so keep its validity buffer and list size instead.
if isinstance(list_array, pa.FixedSizeListArray):
arrow_list_type = pa.list_(value_array.type, list_array.type.list_size)
buffers = list_array.buffers()[:1]
else:
arrow_list_type = list_initializer(value_array.type)
buffers = list_array.buffers()[:2]
list_array = pa.Array.from_buffers(
arrow_list_type,
len(list_array),
buffers,
list_array.null_count,
list_array.offset,
[value_array],
)
arrow_field = list_initializer(self._construct_field(list_type.element_field, value_array.type))
return list_array.cast(arrow_field)
else:
Expand All @@ -2422,26 +2428,29 @@ def map(
if isinstance(map_array, pa.MapArray) and key_result is not None and value_result is not None:
key_result = self._cast_if_needed(map_type.key_field, key_result)
value_result = self._cast_if_needed(map_type.value_field, value_result)
# Temporary fix until PyArrow 26 is the minimum supported version (https://github.com/apache/arrow/issues/51029):
# map keys are never null, but filtering can give them a validity bitmap, and casting such a map aborts PyArrow
key_type = key_result.type
if not pa.types.is_nested(key_type) and not pa.types.is_dictionary(key_type) and key_result.buffers()[0] is not None:
key_result = pa.Array.from_buffers(
key_type, len(key_result), [None, *key_result.buffers()[1:]], 0, key_result.offset
)
arrow_field = pa.map_(
self._construct_field(map_type.key_field, key_result.type),
self._construct_field(map_type.value_field, value_result.type),
)
if isinstance(value_result, pa.StructArray):
# Arrow does not allow reordering of fields, therefore we have to copy the array :(
entries = pa.StructArray.from_arrays(
[key_result, value_result], fields=[arrow_field.key_field, arrow_field.item_field]
)
# Keep the validity and offsets buffers of the original array, otherwise null maps become empty maps
return pa.Array.from_buffers(
arrow_field,
len(map_array),
map_array.buffers()[:2],
map_array.null_count,
map_array.offset,
[entries],
)
else:
return map_array.cast(arrow_field)
entries = pa.StructArray.from_arrays(
[key_result, value_result], fields=[arrow_field.key_field, arrow_field.item_field]
)
# Keep the validity and offsets buffers of the original array, otherwise null maps become empty maps
return pa.Array.from_buffers(
arrow_field,
len(map_array),
map_array.buffers()[:2],
map_array.null_count,
map_array.offset,
[entries],
)
else:
return None

Expand Down
144 changes: 144 additions & 0 deletions tests/io/test_pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4659,6 +4659,150 @@ def test__to_requested_schema_null_list_of_structs(list_type: Callable[[pa.DataT
assert result.column(1).to_pylist() == [[], None, [2, None]]


def test__to_requested_schema_list_of_lists_of_renamed_structs() -> None:
# The renamed struct fields are only in the projected values, so every list around them has to be rebuilt
file_struct = StructType(NestedField(4, "a b", IntegerType(), required=False))
requested_struct = StructType(NestedField(4, "a_b", IntegerType(), required=False))
file_schema = Schema(
NestedField(
1,
"col",
ListType(2, ListType(3, file_struct, element_required=False), element_required=False),
required=False,
),
)
requested_schema = Schema(
NestedField(
1,
"col",
ListType(2, ListType(3, requested_struct, element_required=False), element_required=False),
required=False,
),
)
struct_type = pa.struct([pa.field("a b", pa.int32())])
builders: list[Callable[[pa.DataType], pa.DataType]] = [pa.list_, pa.large_list, lambda value_type: pa.list_(value_type, 2)]
rows = [[[{"a b": 1}, None], [{"a b": 2}, {"a b": None}]], None, [None, [{"a b": 3}, {"a b": 4}]]]
expected = [[[{"a_b": 1}, None], [{"a_b": 2}, {"a_b": None}]], None, [None, [{"a_b": 3}, {"a_b": 4}]]]
for outer_builder in builders:
for inner_builder in builders:
batch = pa.RecordBatch.from_arrays([pa.array(rows, type=outer_builder(inner_builder(struct_type)))], names=["col"])

result = _to_requested_schema(requested_schema, file_schema, batch)
assert result.column(0).to_pylist() == expected

# A sliced batch has to keep the nulls as well
result = _to_requested_schema(requested_schema, file_schema, batch.slice(1, 2))
assert result.column(0).to_pylist() == expected[1:]


def test__to_requested_schema_map_of_lists_of_renamed_structs() -> None:
# The renamed struct fields are in the list values of a map, so the map has to keep the projected values
file_struct = StructType(NestedField(5, "a b", IntegerType(), required=False))
requested_struct = StructType(NestedField(5, "a_b", IntegerType(), required=False))
file_schema = Schema(
NestedField(
1,
"col",
MapType(2, StringType(), 3, ListType(4, file_struct, element_required=False), value_required=False),
required=False,
),
)
requested_schema = Schema(
NestedField(
1,
"col",
MapType(2, StringType(), 3, ListType(4, requested_struct, element_required=False), value_required=False),
required=False,
),
)
struct_type = pa.struct([pa.field("a b", pa.int32())])
builders: list[Callable[[pa.DataType], pa.DataType]] = [pa.list_, pa.large_list, lambda value_type: pa.list_(value_type, 2)]
rows = [[("k", [{"a b": 1}, None])], None, [("j", None), ("m", [{"a b": 2}, {"a b": 3}])]]
expected = [[("k", [{"a_b": 1}, None])], None, [("j", None), ("m", [{"a_b": 2}, {"a_b": 3}])]]
for builder in builders:
batch = pa.RecordBatch.from_arrays([pa.array(rows, type=pa.map_(pa.string(), builder(struct_type)))], names=["col"])

result = _to_requested_schema(requested_schema, file_schema, batch)
assert result.column(0).to_pylist() == expected

# A sliced batch has to keep the null maps and the null list values as well
result = _to_requested_schema(requested_schema, file_schema, batch.slice(1, 2))
assert result.column(0).to_pylist() == expected[1:]


def test_append_fixed_size_lists_of_structs(catalog: InMemoryCatalog) -> None:
# The writer sanitizes "a b", so the struct field is renamed inside the fixed-size list
catalog.create_namespace("default")
list_type = pa.list_(pa.struct([("a b", pa.int32())]), 2)
values = [{"a b": 1}, None]
columns = [
pa.array([values, None], list_type),
pa.array([[("k", values), ("j", None)], None], pa.map_(pa.string(), list_type)),
]
for i, column in enumerate(columns):
arrow_table = pa.table({"v": column})
table = catalog.create_table(f"default.test_append_fixed_size_lists_of_structs_{i}", schema=arrow_table.schema)

table.append(arrow_table)

assert table.scan().to_arrow().to_pylist() == arrow_table.to_pylist()


def test_append_lists_and_maps_of_ns_temporals(catalog: InMemoryCatalog, monkeypatch: pytest.MonkeyPatch) -> None:
# Nested values are downcast like a top-level column: 1 s + 1 us + 1 ns is stored as 1 s + 1 us
monkeypatch.setenv("PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE", "True")
catalog.create_namespace("default")
value_ns = 1_000_001_001
for i, (value_type, stored) in enumerate(
[
(pa.timestamp("ns"), datetime(1970, 1, 1, 0, 0, 1, 1)),
(pa.timestamp("ns", tz="UTC"), datetime(1970, 1, 1, 0, 0, 1, 1, tzinfo=UTC)),
(pa.time64("ns"), time(0, 0, 1, 1)),
]
):
arrow_table = pa.table(
{
"list": pa.array([[value_ns, None], None], pa.list_(value_type)),
"large_list": pa.array([[value_ns, None], None], pa.large_list(value_type)),
"fixed_size_list": pa.array([[value_ns, None], None], pa.list_(value_type, 2)),
"map": pa.array([[(value_ns, value_ns)], None], pa.map_(value_type, value_type)),
}
)
table = catalog.create_table(f"default.test_append_lists_and_maps_of_ns_temporals_{i}", schema=arrow_table.schema)

table.append(arrow_table)

assert table.scan().to_arrow().to_pydict() == {
"list": [[stored, None], None],
"large_list": [[stored, None], None],
"fixed_size_list": [[stored, None], None],
"map": [[(stored, stored)], None],
}


def test_filtered_batch_reader_of_maps(catalog: InMemoryCatalog) -> None:
# PyArrow < 26 aborts when casting a map whose keys have a validity bitmap (https://github.com/apache/arrow/issues/51029).
# The row filter gives string keys one, and the projection must not give struct keys one either.
catalog.create_namespace("default")
struct_type = pa.struct([("x", pa.string())])
cases: list[tuple[pa.DataType, pa.DataType, list[Any], list[Any]]] = [
(pa.string(), pa.int64(), ["a", "b", "c"], [1, 2]),
(pa.string(), struct_type, ["a", "b", "c"], [{"x": "p"}, {"x": None}]),
(struct_type, pa.int64(), [{"x": "a"}, {"x": None}, {"x": "c"}], [1, 2]),
]
for i, (key_type, value_type, keys, values) in enumerate(cases):
schema = pa.schema([pa.field("id", pa.int64(), nullable=False), pa.field("m", pa.map_(key_type, value_type))])
rows = [
{"id": 1, "m": [(keys[0], values[0])]},
{"id": 2, "m": [(keys[1], values[1]), (keys[2], None)]},
{"id": 3, "m": None},
]
table = catalog.create_table(f"default.test_filtered_batch_reader_of_maps_{i}", schema=schema)
table.append(pa.Table.from_pylist(rows, schema=schema))

assert table.scan(row_filter="id = 2").to_arrow_batch_reader().read_all().to_pylist() == [rows[1]]


@skip_if_pyarrow_too_old
@pytest.mark.parametrize("scheme", ["abfs", "abfss", "wasb", "wasbs"])
def test_adls_account_name_from_location(scheme: str) -> None:
Expand Down