| # Licensed to the Apache Software Foundation (ASF) under one | |
| # or more contributor license agreements. See the NOTICE file | |
| # distributed with this work for additional information | |
| # regarding copyright ownership. The ASF licenses this file | |
| # to you under the Apache License, Version 2.0 (the | |
| # "License"); you may not use this file except in compliance | |
| # with the License. You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, | |
| # software distributed under the License is distributed on an | |
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| # KIND, either express or implied. See the License for the | |
| # specific language governing permissions and limitations | |
| # under the License. | |
| """Tests for Arrow PyCapsule stream input on writes and export from scans.""" | |
| from collections.abc import Iterator | |
| from pathlib import PosixPath | |
| from typing import Any | |
| import pyarrow as pa | |
| import pytest | |
| from pyiceberg.catalog.memory import InMemoryCatalog | |
| from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionField, PartitionSpec | |
| from pyiceberg.schema import Schema | |
| from pyiceberg.transforms import IdentityTransform | |
| from pyiceberg.types import IntegerType, NestedField, StringType | |
| SCHEMA = Schema( | |
| NestedField(1, "id", IntegerType(), required=False), | |
| NestedField(2, "region", StringType(), required=False), | |
| ) | |
| PARTITION_SPEC = PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="region")) | |
| class _ArrowStreamWrapper: | |
| """A minimal third-party-style Arrow producer. | |
| Exposes only ``__arrow_c_stream__`` -- it is deliberately *not* a | |
| ``pa.Table``/``pa.RecordBatchReader`` -- to stand in for libraries such as | |
| polars or arro3 without taking a dependency on them. | |
| """ | |
| def __init__(self, data: pa.Table | pa.RecordBatchReader): | |
| self._data = data | |
| def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: | |
| return self._data.__arrow_c_stream__(requested_schema) | |
| @pytest.fixture | |
| def catalog(tmp_path: PosixPath) -> InMemoryCatalog: | |
| catalog = InMemoryCatalog("test.in_memory.catalog", warehouse=tmp_path.absolute().as_posix()) | |
| catalog.create_namespace("default") | |
| return catalog | |
| def _data(ids: list[int], regions: list[str], region_type: pa.DataType | None = None) -> pa.Table: | |
| return pa.table({"id": pa.array(ids, type=pa.int32()), "region": pa.array(regions, type=region_type or pa.string())}) | |
| def _counting_reader(table: pa.Table) -> tuple[pa.RecordBatchReader, list[pa.RecordBatch]]: | |
| """Return a one-row-per-batch reader over the table and the list of batches pulled from it so far.""" | |
| pulled: list[pa.RecordBatch] = [] | |
| def batches() -> Iterator[pa.RecordBatch]: | |
| for batch in table.to_batches(max_chunksize=1): | |
| pulled.append(batch) | |
| yield batch | |
| return pa.RecordBatchReader.from_batches(table.schema, batches()), pulled | |
| def _rows(table: pa.Table) -> list[dict[str, Any]]: | |
| return sorted(table.to_pylist(), key=lambda r: r["id"]) | |
| def test_append_and_overwrite_accept_arrow_capsule(catalog: InMemoryCatalog) -> None: | |
| data = _data([1, 2, 3], ["us", "eu", "us"]) | |
| # A stream of several batches must be fully drained. | |
| for name, stream in (("single", data), ("multi", pa.Table.from_batches(data.to_batches(max_chunksize=1)))): | |
| tbl = catalog.create_table(f"default.append_{name}_batch", schema=SCHEMA) | |
| tbl.append(_ArrowStreamWrapper(stream)) | |
| assert _rows(tbl.scan().to_arrow()) == _rows(data), name | |
| tbl.overwrite(_ArrowStreamWrapper(_data([9], ["jp"]))) | |
| assert _rows(tbl.scan().to_arrow()) == _rows(_data([9], ["jp"])) | |
| def test_append_accepts_polars_dataframe(catalog: InMemoryCatalog) -> None: | |
| import polars as pl | |
| tbl = catalog.create_table("default.append_polars", schema=SCHEMA) | |
| tbl.append(pl.DataFrame({"id": [10, 11], "region": ["ca", "mx"]}, schema={"id": pl.Int32, "region": pl.String})) | |
| assert _rows(tbl.scan().to_arrow()) == _rows(_data([10, 11], ["ca", "mx"])) | |
| assert _rows(tbl.scan(row_filter="region == 'ca'").to_arrow()) == _rows(_data([10], ["ca"])) | |
| def test_append_arrow_capsule_to_partitioned_table(catalog: InMemoryCatalog) -> None: | |
| tbl = catalog.create_table("default.append_capsule_partitioned", schema=SCHEMA, partition_spec=PARTITION_SPEC) | |
| tbl.append(_ArrowStreamWrapper(_data([1, 2, 3], ["us", "eu", "us"], pa.string_view()))) | |
| assert len(tbl.inspect.partitions()) == 2 | |
| assert _rows(tbl.scan().to_arrow()) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) | |
| def test_arrow_capsule_is_streamed_into_an_unpartitioned_table_only(catalog: InMemoryCatalog) -> None: | |
| data = _data([1, 2, 3], ["us", "eu", "us"]) | |
| for name, spec, expected in (("unpartitioned", UNPARTITIONED_PARTITION_SPEC, 0), ("partitioned", PARTITION_SPEC, 3)): | |
| tbl = catalog.create_table(f"default.streamed_{name}", schema=SCHEMA, partition_spec=spec) | |
| reader, pulled = _counting_reader(data) | |
| tbl.transaction()._prepare_arrow_input(_ArrowStreamWrapper(reader)) | |
| assert len(pulled) == expected, name | |
| def test_append_checks_schema_before_reading_arrow_capsule(catalog: InMemoryCatalog) -> None: | |
| mismatched = pa.table({"id": ["a", "b"], "region": ["us", "eu"]}) | |
| for name, spec in (("unpartitioned", UNPARTITIONED_PARTITION_SPEC), ("partitioned", PARTITION_SPEC)): | |
| tbl = catalog.create_table(f"default.schema_check_{name}", schema=SCHEMA, partition_spec=spec) | |
| reader, pulled = _counting_reader(mismatched) | |
| with pytest.raises(ValueError, match="Mismatch in fields"): | |
| tbl.append(_ArrowStreamWrapper(reader)) | |
| assert not pulled, name | |
| def test_scan_arrow_c_stream_respects_filter_projection_and_limit(catalog: InMemoryCatalog) -> None: | |
| tbl = catalog.create_table("default.scan_stream_filtered", schema=SCHEMA) | |
| tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) | |
| scan = tbl.scan(row_filter="region == 'us'", selected_fields=("id",)) | |
| consumed = pa.table(scan) | |
| assert consumed.column_names == ["id"] | |
| assert sorted(consumed.column("id").to_pylist()) == [1, 3] | |
| assert pa.table(scan.update(limit=1)).num_rows == 1 | |
| def test_scan_arrow_c_stream_casts_to_requested_schema(catalog: InMemoryCatalog) -> None: | |
| tbl = catalog.create_table("default.stream_requested_schema", schema=SCHEMA) | |
| tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) | |
| requested = pa.schema([pa.field("id", pa.int64()), pa.field("region", pa.string())]) | |
| for scan in (tbl.scan(), tbl.incremental_append_scan()): | |
| consumed = pa.RecordBatchReader.from_stream(scan, schema=requested).read_all() | |
| assert consumed.schema == requested | |
| assert _rows(consumed) == _rows(_data([1, 2, 3], ["us", "eu", "us"])) | |
| def test_scan_arrow_c_stream_has_no_field_ids(catalog: InMemoryCatalog) -> None: | |
| tbl = catalog.create_table("default.stream_field_ids", schema=SCHEMA) | |
| tbl.append(_data([1, 2, 3], ["us", "eu", "us"])) | |
| for scan in (tbl.scan(), tbl.incremental_append_scan()): | |
| assert all(field.metadata is None for field in pa.table(scan).schema) | |
| def test_append_scan_matches_columns_by_name(catalog: InMemoryCatalog) -> None: | |
| """The source and destination give the same names to different field ids.""" | |
| src = catalog.create_table( | |
| "default.by_name_src", | |
| schema=Schema( | |
| NestedField(1, "last", StringType(), required=False), NestedField(2, "first", StringType(), required=False) | |
| ), | |
| ) | |
| src.append(pa.table({"last": ["Doe"], "first": ["Jane"]})) | |
| dst = catalog.create_table( | |
| "default.by_name_dst", | |
| schema=Schema( | |
| NestedField(1, "first", StringType(), required=False), NestedField(2, "last", StringType(), required=False) | |
| ), | |
| ) | |
| dst.append(src.scan()) | |
| assert dst.scan().to_arrow().to_pylist() == [{"first": "Jane", "last": "Doe"}] | |
| def test_incremental_append_scan_supports_arrow_c_stream(catalog: InMemoryCatalog) -> None: | |
| tbl = catalog.create_table("default.incremental_stream", schema=SCHEMA) | |
| tbl.append(_data([1, 2], ["us", "eu"])) | |
| first_snapshot_id = tbl.metadata.current_snapshot_id | |
| tbl.append(_data([3], ["us"])) | |
| consumed = pa.table(tbl.incremental_append_scan(from_snapshot_id_exclusive=first_snapshot_id)) | |
| assert _rows(consumed) == _rows(_data([3], ["us"])) |