diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index f823a2fc60..d0d6d08332 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -407,6 +407,27 @@ long: [[4.896029,-122.431297,6.0989],[6.56667]] In the case of `tbl.delete(delete_filter="city == 'Groningen'")`, the whole Parquet file will be dropped without checking it contents, since from the Iceberg metadata PyIceberg can derive that all the content in the file matches the predicate. +### Arrow PyCapsule interface + + +`tbl.append()` and `tbl.overwrite()` accept any object that implements the [Arrow PyCapsule stream interface](https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html) (`__arrow_c_stream__`), so a dataframe from a library such as Polars can be written without converting it to PyArrow first: + +```python +import polars as pl + +tbl.append(pl.DataFrame({"city": ["Groningen"], "lat": [53.21917], "long": [6.56667]})) +``` + +Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. A streamed batch is never split, so a dataframe that exports one large batch is written as one file. + +The stream's schema must match the table's, including nullability. Polars exports every column as optional, so a Polars dataframe cannot be written to a table with required fields. + +Scans implement the same interface, so any Arrow consumer can read one directly: + +```python +df = pl.DataFrame(tbl.scan(row_filter="lat > 50")) +``` + ### Partial overwrites When using the `overwrite` API, you can use an `overwrite_filter` to delete data that matches the filter before appending new data into the table. For example, consider the following Iceberg table: diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index d0b7031c3f..304be94ac5 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3369,6 +3369,15 @@ def _dataframe_to_data_files( property_name=TableProperties.WRITE_TARGET_FILE_SIZE_BYTES, default=TableProperties.WRITE_TARGET_FILE_SIZE_BYTES_DEFAULT, ) + # Cast view types to large_string and large_binary. PyArrow cannot yet + # filter on view types or combine them with the string and binary columns + # of other data files, so a table written with them could not be scanned + # with a filter or deleted from. This cast can be removed once PyArrow + # supports both. + arrow_schema = visit_pyarrow(df.schema, _ConvertViewTypes()) + if arrow_schema != df.schema: + df = df.cast(arrow_schema) + name_mapping = table_metadata.schema().name_mapping downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False task_schema = pyarrow_to_schema( @@ -3443,11 +3452,6 @@ def _determine_partitions(spec: PartitionSpec, schema: Schema, arrow_table: pa.T - Then we produce a set of partitions by filtering on each of the combinations - We combine the chunks to create a copy to avoid GIL congestion on the original table """ - # PyArrow has no group by, filter or take kernels for view types, so replace them with their large counterparts - arrow_schema = visit_pyarrow(arrow_table.schema, _ConvertViewTypes()) - if arrow_schema != arrow_table.schema: - arrow_table = arrow_table.cast(arrow_schema) - # Assign unique names to columns where the partition transform has been applied # to avoid conflicts with the data columns partition_fields: list[str] = [] diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index a8fcdb16e6..a96d67c6a0 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -107,6 +107,7 @@ from pyiceberg.transforms import IdentityTransform from pyiceberg.typedef import ( EMPTY_DICT, + ArrowStreamExportable, IcebergBaseModel, IcebergRootModel, Identifier, @@ -521,16 +522,46 @@ def update_partition_statistics(self) -> UpdatePartitionStatistics: """ return UpdatePartitionStatistics(transaction=self) + def _prepare_arrow_input( + self, df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable + ) -> pa.Table | pa.RecordBatchReader: + """Return the write input as Arrow data that matches the table schema.""" + import pyarrow as pa + + from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible + + if isinstance(df, (pa.Table, pa.RecordBatchReader)): + arrow_data, read_into_memory = df, False + elif hasattr(df, "__arrow_c_stream__"): + # Streaming writes need an unpartitioned table, so the stream is + # read into memory for a partitioned one + arrow_data = pa.RecordBatchReader.from_stream(df) + read_into_memory = not self.table_metadata.spec().is_unpartitioned() + else: + raise ValueError( + f"Expected pa.Table, pa.RecordBatchReader, or an object implementing the " + f"Arrow PyCapsule interface (__arrow_c_stream__), got: {df!r}" + ) + + _check_pyarrow_schema_compatible( + self.table_metadata.schema(), + provided_schema=arrow_data.schema, + downcast_ns_timestamp_to_us=Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False, + format_version=self.table_metadata.format_version, + ) + + return arrow_data.read_all() if read_into_memory else arrow_data + def append( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, snapshot_properties: dict[str, str] = EMPTY_DICT, branch: str | None = MAIN_BRANCH, ) -> None: """ Shorthand API for appending PyArrow data to a table transaction. - Accepts either a fully materialised ``pa.Table`` or a streaming + Accepts a fully materialised ``pa.Table`` or a streaming ``pa.RecordBatchReader``. Streaming is microbatched by ``write.target-file-size-bytes`` so memory stays bounded; the reader is consumed once and cannot be reused. @@ -540,6 +571,11 @@ def append( ``NotImplementedError``. See https://github.com/apache/iceberg-python/issues/2152. + Any other object implementing the Arrow PyCapsule stream interface + (``__arrow_c_stream__``), such as a Polars DataFrame, is accepted as + well. It is streamed into an unpartitioned table and read into memory + for a partitioned one. + Note: When ``df`` is a ``pa.RecordBatchReader`` the reader is consumed once and cannot be replayed. If the catalog commit fails (e.g. @@ -567,7 +603,7 @@ def append( rolling-``ParquetWriter`` with ``OutputStream.tell()`` (#2998). Args: - df: An Arrow Table or a RecordBatchReader of records to append. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to append. snapshot_properties: Custom properties to be added to the snapshot summary branch: Branch Reference to run the append operation """ @@ -576,18 +612,9 @@ def append( except ModuleNotFoundError as e: raise ModuleNotFoundError("For writes PyArrow needs to be installed") from e - from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _dataframe_to_data_files - - if not isinstance(df, (pa.Table, pa.RecordBatchReader)): - raise ValueError(f"Expected pa.Table or pa.RecordBatchReader, got: {df}") + from pyiceberg.io.pyarrow import _dataframe_to_data_files - downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False - _check_pyarrow_schema_compatible( - self.table_metadata.schema(), - provided_schema=df.schema, - downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, - format_version=self.table_metadata.format_version, - ) + df = self._prepare_arrow_input(df) with self._append_snapshot_producer(snapshot_properties, branch=branch) as append_files: # For pa.Table we can short-circuit empty inputs cheaply. For a @@ -677,7 +704,7 @@ def dynamic_partition_overwrite( def overwrite( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, overwrite_filter: BooleanExpression | str = ALWAYS_TRUE, snapshot_properties: dict[str, str] = EMPTY_DICT, case_sensitive: bool = True, @@ -686,7 +713,7 @@ def overwrite( """ Shorthand for adding a table overwrite with a PyArrow table or RecordBatchReader to the transaction. - Accepts either a fully materialised ``pa.Table`` or a streaming + Accepts a fully materialised ``pa.Table`` or a streaming ``pa.RecordBatchReader``. Streaming is microbatched by ``write.target-file-size-bytes`` so memory stays bounded; the reader is consumed once and cannot be reused. @@ -696,6 +723,11 @@ def overwrite( ``NotImplementedError``. See https://github.com/apache/iceberg-python/issues/2152. + Any other object implementing the Arrow PyCapsule stream interface + (``__arrow_c_stream__``), such as a Polars DataFrame, is accepted as + well. It is streamed into an unpartitioned table and read into memory + for a partitioned one. + Note: When ``df`` is a ``pa.RecordBatchReader`` the reader is consumed once and cannot be replayed. If the catalog commit fails (e.g. @@ -729,7 +761,7 @@ def overwrite( - APPEND: In case new data is being inserted into the table. Args: - df: An Arrow Table or a RecordBatchReader of records to write. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to write. overwrite_filter: ALWAYS_TRUE when you overwrite all the data, or a boolean expression in case of a partial overwrite snapshot_properties: Custom properties to be added to the snapshot summary @@ -741,18 +773,9 @@ def overwrite( except ModuleNotFoundError as e: raise ModuleNotFoundError("For writes PyArrow needs to be installed") from e - from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible, _dataframe_to_data_files - - if not isinstance(df, (pa.Table, pa.RecordBatchReader)): - raise ValueError(f"Expected pa.Table or pa.RecordBatchReader, got: {df}") + from pyiceberg.io.pyarrow import _dataframe_to_data_files - downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) or False - _check_pyarrow_schema_compatible( - self.table_metadata.schema(), - provided_schema=df.schema, - downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, - format_version=self.table_metadata.format_version, - ) + df = self._prepare_arrow_input(df) if overwrite_filter != AlwaysFalse(): # Only delete when the filter is != AlwaysFalse @@ -1832,19 +1855,20 @@ def upsert( def append( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, snapshot_properties: dict[str, str] = EMPTY_DICT, branch: str | None = MAIN_BRANCH, ) -> None: """ Shorthand API for appending PyArrow data to the table. - Accepts either a ``pa.Table`` or a streaming ``pa.RecordBatchReader``. - See :meth:`Transaction.append` for streaming semantics and partition + Accepts a ``pa.Table``, a streaming ``pa.RecordBatchReader`` or any other + object implementing the Arrow PyCapsule stream interface. See + :meth:`Transaction.append` for streaming semantics and partition limitations. Args: - df: An Arrow Table or a RecordBatchReader of records to append. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to append. snapshot_properties: Custom properties to be added to the snapshot summary branch: Branch Reference to run the append operation """ @@ -1867,7 +1891,7 @@ def dynamic_partition_overwrite( def overwrite( self, - df: pa.Table | pa.RecordBatchReader, + df: pa.Table | pa.RecordBatchReader | ArrowStreamExportable, overwrite_filter: BooleanExpression | str = ALWAYS_TRUE, snapshot_properties: dict[str, str] = EMPTY_DICT, case_sensitive: bool = True, @@ -1876,8 +1900,9 @@ def overwrite( """ Shorthand for overwriting the table with a PyArrow Table or RecordBatchReader. - Accepts either a ``pa.Table`` or a streaming ``pa.RecordBatchReader``. - See :meth:`Transaction.overwrite` for streaming semantics and partition + Accepts a ``pa.Table``, a streaming ``pa.RecordBatchReader`` or any other + object implementing the Arrow PyCapsule stream interface. See + :meth:`Transaction.overwrite` for streaming semantics and partition limitations. An overwrite may produce zero or more snapshots based on the operation: @@ -1887,7 +1912,7 @@ def overwrite( - APPEND: In case new data is being inserted into the table. Args: - df: An Arrow Table or a RecordBatchReader of records to write. + df: An Arrow Table, RecordBatchReader or PyCapsule stream of records to write. overwrite_filter: ALWAYS_TRUE when you overwrite all the data, or a boolean expression in case of a partial overwrite snapshot_properties: Custom properties to be added to the snapshot summary @@ -2518,14 +2543,18 @@ def _to_arrow_via_file_scan_tasks( def _to_arrow_batch_reader_via_file_scan_tasks( - scan: BaseScan, projected_schema: Schema, tasks: Iterable[FileScanTask], dictionary_columns: tuple[str, ...] = () + scan: BaseScan, + projected_schema: Schema, + tasks: Iterable[FileScanTask], + dictionary_columns: tuple[str, ...] = (), + include_field_ids: bool = True, ) -> pa.RecordBatchReader: """Stream a scan into an Arrow ``RecordBatchReader`` given its planned ``FileScanTask``s.""" import pyarrow as pa from pyiceberg.io.pyarrow import ArrowScan, schema_to_pyarrow - target_schema = schema_to_pyarrow(projected_schema) + target_schema = schema_to_pyarrow(projected_schema, include_field_ids=include_field_ids) batches = ArrowScan( scan.table_metadata, scan.io, @@ -2677,6 +2706,16 @@ def to_arrow_batch_reader(self, dictionary_columns: tuple[str, ...] = ()) -> pa. self, self.projection(), self.plan_files(), dictionary_columns=dictionary_columns ) + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export this scan's result as an Arrow C stream (PyCapsule interface). + + Field IDs are dropped, as in to_arrow(). They only have meaning + inside this table, and a write to another table would match columns + by them. + """ + reader = _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files(), include_field_ids=False) + return reader.__arrow_c_stream__(requested_schema) + def count(self) -> int: from pyiceberg.io.pyarrow import ArrowScan @@ -2856,6 +2895,16 @@ def to_arrow_batch_reader(self) -> pa.RecordBatchReader: """ return _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files()) + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export this scan's result as an Arrow C stream (PyCapsule interface). + + Field IDs are dropped, as in to_arrow(). They only have meaning + inside this table, and a write to another table would match columns + by them. + """ + reader = _to_arrow_batch_reader_via_file_scan_tasks(self, self.projection(), self.plan_files(), include_field_ids=False) + return reader.__arrow_c_stream__(requested_schema) + def _validate_and_resolve_snapshots(self) -> tuple[int | None, int]: """Resolve the configured range to ``(from_snapshot_id_exclusive, to_snapshot_id_inclusive)``. diff --git a/pyiceberg/typedef.py b/pyiceberg/typedef.py index de4d036fe7..58735f6e62 100644 --- a/pyiceberg/typedef.py +++ b/pyiceberg/typedef.py @@ -113,6 +113,18 @@ def __setitem__(self, pos: int, value: Any) -> None: """Assign a value to a StructProtocol.""" +class ArrowStreamExportable(Protocol): # pragma: no cover + """Any object implementing the Arrow PyCapsule stream interface. + + Covers pa.Table, pa.RecordBatchReader, and third-party producers + (polars, arro3, nanoarrow, ...) without depending on any of them. + """ + + @abstractmethod + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export the object as an Arrow C stream PyCapsule.""" + + class IcebergBaseModel(BaseModel): """ This class extends the Pydantic BaseModel to set default values by overriding them. diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index cface2e0d0..a798b56b37 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -1528,7 +1528,7 @@ def test_append_invalid_input_type_raises(catalog: Catalog) -> None: identifier = f"default.append_invalid_input_{catalog.name}" pa_table = _simple_arrow_table() tbl = catalog.create_table(identifier=identifier, schema=pa_table.schema) - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.append("not an arrow object") diff --git a/tests/integration/test_writes/test_partitioned_writes.py b/tests/integration/test_writes/test_partitioned_writes.py index 040c0cfeea..45b2eebf37 100644 --- a/tests/integration/test_writes/test_partitioned_writes.py +++ b/tests/integration/test_writes/test_partitioned_writes.py @@ -771,7 +771,7 @@ def test_invalid_arguments(spark: SparkSession, session_catalog: Catalog) -> Non properties={"format-version": "1"}, ) - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader, got: not a df"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.append("not a df") diff --git a/tests/integration/test_writes/test_writes.py b/tests/integration/test_writes/test_writes.py index ba367b0f9c..a3eb9d2e69 100644 --- a/tests/integration/test_writes/test_writes.py +++ b/tests/integration/test_writes/test_writes.py @@ -792,10 +792,10 @@ def test_invalid_arguments(spark: SparkSession, session_catalog: Catalog, arrow_ identifier = "default.arrow_data_files" tbl = _create_table(session_catalog, identifier, {"format-version": "1"}, []) - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader, got: not a df"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.overwrite("not a df") - with pytest.raises(ValueError, match="Expected pa.Table or pa.RecordBatchReader, got: not a df"): + with pytest.raises(ValueError, match="Expected pa.Table, pa.RecordBatchReader, or an object implementing"): tbl.append("not a df") diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index e1e99be4c7..113f09f6e8 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -85,6 +85,7 @@ StatsAggregator, _check_pyarrow_schema_compatible, _ConvertToArrowSchema, + _ConvertViewTypes, _create_arrow_read_format, _determine_partitions, _primitive_to_physical, @@ -99,6 +100,7 @@ expression_to_pyarrow, parquet_path_to_id_mapping, schema_to_pyarrow, + visit_pyarrow, write_file, ) from pyiceberg.manifest import DataFile, DataFileContent, FileFormat, ManifestEntry, ManifestEntryStatus @@ -3580,6 +3582,8 @@ def test_determine_partitions_with_view_types(transform: Transform[Any, Any]) -> {"region": None, "payload": b"c", "info": {"tags": ["y", None], "attrs": []}}, ] arrow_table = pa.Table.from_pylist(rows, schema=arrow_schema) + # View types are cast before the table is split into partitions + arrow_table = arrow_table.cast(visit_pyarrow(arrow_schema, _ConvertViewTypes())) partitions = list(_determine_partitions(spec, schema, arrow_table)) @@ -3713,6 +3717,43 @@ def test_append_view_types_to_partitioned_table(catalog: InMemoryCatalog) -> Non assert sorted(table.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == arrow_table.to_pylist() +def test_append_view_types_to_unpartitioned_table(catalog: InMemoryCatalog) -> None: + schema = Schema( + NestedField(id=1, name="id", field_type=LongType(), required=False), + NestedField(id=2, name="region", field_type=StringType(), required=False), + NestedField(id=3, name="payload", field_type=BinaryType(), required=False), + NestedField(id=4, name="tags", field_type=ListType(element_id=5, element_type=StringType(), element_required=False)), + ) + catalog.create_namespace("default") + plain_table = pa.table( + { + "id": pa.array([1], type=pa.int64()), + "region": pa.array(["us"], type=pa.string()), + "payload": pa.array([b"a"], type=pa.binary()), + "tags": pa.array([["x"]], type=pa.list_(pa.string())), + } + ) + view_table = pa.table( + { + "id": pa.array([2, 3], type=pa.int64()), + "region": pa.array(["us", "eu"], type=pa.string_view()), + "payload": pa.array([b"a", b"b"], type=pa.binary_view()), + "tags": pa.array([["x"], ["y"]], type=pa.list_(pa.string_view())), + } + ) + + for name, df in (("table", view_table), ("reader", view_table.to_reader())): + table = catalog.create_table(f"default.test_append_view_types_{name}", schema=schema) + table.append(plain_table) + table.append(df) + + assert sorted(table.scan().to_arrow()["tags"].to_pylist()) == [["x"], ["x"], ["y"]], name + assert sorted(table.scan(row_filter="region == 'us'").to_arrow()["id"].to_pylist()) == [1, 2], name + assert sorted(table.scan(row_filter=EqualTo("payload", b"a")).to_arrow()["id"].to_pylist()) == [1, 2], name + table.delete("region == 'us'") + assert table.scan().to_arrow()["id"].to_pylist() == [3], name + + def test_append_to_table_bucketed_by_time(catalog: InMemoryCatalog) -> None: schema = Schema( NestedField(id=1, name="id", field_type=LongType(), required=False), diff --git a/tests/table/test_arrow_capsule.py b/tests/table/test_arrow_capsule.py new file mode 100644 index 0000000000..4ca8b3db35 --- /dev/null +++ b/tests/table/test_arrow_capsule.py @@ -0,0 +1,203 @@ +# 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"]))