This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-3447-2308f9939cc7a6ac7b4b528853113ce860a75aae
in repository https://gitbox.apache.org/repos/asf/iceberg-python.git

commit d6a229cd1e1bdab72d254d959551fd615e19b92c
Author: Abanoub Doss <[email protected]>
AuthorDate: Thu Nov 26 08:07:07 2026 +0000

    feat: support arrow pycapsule streams (#3447)
    
    * feat: support arrow pycapsule streams
    
    Adopt the Arrow PyCapsule interface on both sides of the read/write
    boundary. append/overwrite accept any object implementing
    __arrow_c_stream__ (coerced to a streaming RecordBatchReader), and
    Table plus every scan expose __arrow_c_stream__ via BaseScan (not just
    DataScan) so any Arrow consumer can ingest them.
    
    * test: update arrow input error expectations
    
    * fix: keep BaseScan free of new abstract methods
    
    * fix: remove Table.__arrow_c_stream__
    
    * fix: export scan arrow c streams without field ids
    
    * fix: cast arrow view types on write
    
    * test: tighten arrow capsule coverage
    
    * fix: accept arrow c stream input for partitioned tables
    
    * docs: describe arrow c stream input and scan export
    
    * fix: clean up arrow c stream comments, docs and duplicate view cast
---
 mkdocs/docs/api.md                                 |  21 +++
 pyiceberg/io/pyarrow.py                            |  14 +-
 pyiceberg/table/__init__.py                        | 125 +++++++++----
 pyiceberg/typedef.py                               |  12 ++
 tests/catalog/test_catalog_behaviors.py            |   2 +-
 .../test_writes/test_partitioned_writes.py         |   2 +-
 tests/integration/test_writes/test_writes.py       |   4 +-
 tests/io/test_pyarrow.py                           |  41 +++++
 tests/table/test_arrow_capsule.py                  | 203 +++++++++++++++++++++
 9 files changed, 377 insertions(+), 47 deletions(-)

diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md
index f823a2fc6..d0d6d0833 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
+
+<!-- markdown-link-check-disable-next-line -->
+`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 5140f717e..e345e040f 100644
--- a/pyiceberg/io/pyarrow.py
+++ b/pyiceberg/io/pyarrow.py
@@ -3391,6 +3391,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(
@@ -3465,11 +3474,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 ba967754f..1c6d4c3a3 100644
--- a/pyiceberg/table/__init__.py
+++ b/pyiceberg/table/__init__.py
@@ -107,6 +107,7 @@ from pyiceberg.table.update.statistics import 
UpdateStatistics
 from pyiceberg.transforms import IdentityTransform
 from pyiceberg.typedef import (
     EMPTY_DICT,
+    ArrowStreamExportable,
     IcebergBaseModel,
     IcebergRootModel,
     Identifier,
@@ -524,16 +525,46 @@ class Transaction:
         """
         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.
@@ -543,6 +574,11 @@ class Transaction:
         ``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.
@@ -570,7 +606,7 @@ class Transaction:
             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
         """
@@ -579,18 +615,9 @@ class Transaction:
         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
@@ -680,7 +707,7 @@ class Transaction:
 
     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,
@@ -689,7 +716,7 @@ class Transaction:
         """
         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.
@@ -699,6 +726,11 @@ class Transaction:
         ``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.
@@ -732,7 +764,7 @@ class Transaction:
             - 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
@@ -744,18 +776,9 @@ class Transaction:
         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
@@ -1840,19 +1863,20 @@ class Table:
 
     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
         """
@@ -1875,7 +1899,7 @@ class Table:
 
     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,
@@ -1884,8 +1908,9 @@ class Table:
         """
         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:
@@ -1895,7 +1920,7 @@ class Table:
             - 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
@@ -2526,14 +2551,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,
@@ -2685,6 +2714,16 @@ class DataScan(TableScan):
             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
 
@@ -2864,6 +2903,16 @@ class IncrementalAppendScan(BaseScan):
         """
         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 de4d036fe..58735f6e6 100644
--- a/pyiceberg/typedef.py
+++ b/pyiceberg/typedef.py
@@ -113,6 +113,18 @@ class StructProtocol(Protocol):  # pragma: no cover
         """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 cface2e0d..a798b56b3 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 040c0cfee..45b2eebf3 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 c1a7b629d..519edc1be 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 428342f32..40ad3bd42 100644
--- a/tests/io/test_pyarrow.py
+++ b/tests/io/test_pyarrow.py
@@ -85,6 +85,7 @@ from pyiceberg.io.pyarrow import (
     StatsAggregator,
     _check_pyarrow_schema_compatible,
     _ConvertToArrowSchema,
+    _ConvertViewTypes,
     _create_arrow_read_format,
     _determine_partitions,
     _primitive_to_physical,
@@ -99,6 +100,7 @@ from pyiceberg.io.pyarrow import (
     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 000000000..4ca8b3db3
--- /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)
+
+
[email protected]
+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"]))

Reply via email to