Skip to content
Merged
21 changes: 21 additions & 0 deletions mkdocs/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 9 additions & 5 deletions pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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] = []
Expand Down
125 changes: 87 additions & 38 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
from pyiceberg.transforms import IdentityTransform
from pyiceberg.typedef import (
EMPTY_DICT,
ArrowStreamExportable,
IcebergBaseModel,
IcebergRootModel,
Identifier,
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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
"""
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
"""
Expand All @@ -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,
Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)``.

Expand Down
12 changes: 12 additions & 0 deletions pyiceberg/typedef.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion tests/catalog/test_catalog_behaviors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_writes/test_partitioned_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test_writes/test_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
Loading
Loading