Skip to content

Commit 25fabbd

Browse files
committed
Revert "UNPICK changes to review"
This reverts commit d71594e.
1 parent d71594e commit 25fabbd

File tree

18 files changed

+1376
-163
lines changed

18 files changed

+1376
-163
lines changed

docs/source/conf.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@
7272
suppress_warnings = ["autoapi.python_import_resolution"]
7373
autoapi_python_class_content = "both"
7474
autoapi_keep_files = False # set to True for debugging generated files
75+
autoapi_options = [
76+
"members",
77+
"undoc-members",
78+
"special-members",
79+
"show-inheritance",
80+
"show-module-summary",
81+
"imported-members",
82+
]
7583

7684

7785
def autoapi_skip_member_fn(app, what, name, obj, skip, options) -> bool: # noqa: ARG001

docs/source/contributor-guide/ffi.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ for our provider thusly:
161161

162162
.. code-block:: rust
163163
164-
let name = CString::new("datafusion_table_provider")?;
165-
let my_capsule = PyCapsule::new_bound(py, provider, Some(name))?;
164+
let name = pyo3::ffi::c_str!("datafusion_table_provider");
165+
let my_capsule = PyCapsule::new_bound(py, provider, Some(name.to_owned()))?;
166166
167167
On the receiving side, turn this pycapsule object into the ``FFI_TableProvider``, which
168168
can then be turned into a ``ForeignTableProvider`` the associated code is:

docs/source/user-guide/dataframe/index.rst

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,10 +145,44 @@ To materialize the results of your DataFrame operations:
145145
146146
# Display results
147147
df.show() # Print tabular format to console
148-
148+
149149
# Count rows
150150
count = df.count()
151151
152+
PyArrow Streaming
153+
-----------------
154+
155+
DataFusion DataFrames implement the ``__arrow_c_stream__`` protocol, enabling
156+
zero-copy streaming into libraries like `PyArrow <https://arrow.apache.org/>`_.
157+
Earlier versions eagerly converted the entire DataFrame when exporting to
158+
PyArrow, which could exhaust memory on large datasets. With streaming, batches
159+
are produced lazily so you can process arbitrarily large results without
160+
out-of-memory errors.
161+
162+
.. code-block:: python
163+
164+
import pyarrow as pa
165+
166+
# Create a PyArrow RecordBatchReader without materializing all batches
167+
reader = pa.RecordBatchReader.from_stream(df)
168+
for batch in reader:
169+
... # process each batch as it is produced
170+
171+
Note that streams retain the originating ``SessionContext`` internally, so the
172+
context can be safely dropped once the stream has been obtained.
173+
174+
DataFrames are also iterable, yielding :class:`datafusion.RecordBatch` objects
175+
that implement the Arrow C data interface. These batches can be consumed by
176+
libraries like PyArrow without copying:
177+
178+
.. code-block:: python
179+
180+
for batch in df:
181+
pa_batch = batch.to_pyarrow() # optional conversion
182+
... # process each batch as it is produced
183+
184+
See :doc:`../io/arrow` for additional details on the Arrow interface.
185+
152186
HTML Rendering
153187
--------------
154188

docs/source/user-guide/io/table_provider.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,13 @@ A complete example can be found in the `examples folder <https://github.com/apac
3737
&self,
3838
py: Python<'py>,
3939
) -> PyResult<Bound<'py, PyCapsule>> {
40-
let name = CString::new("datafusion_table_provider").unwrap();
40+
let name = pyo3::ffi::c_str!("datafusion_table_provider");
4141
4242
let provider = Arc::new(self.clone())
4343
.map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
4444
let provider = FFI_TableProvider::new(Arc::new(provider), false);
4545
46-
PyCapsule::new_bound(py, provider, Some(name.clone()))
46+
PyCapsule::new_bound(py, provider, Some(name.to_owned()))
4747
}
4848
}
4949

python/datafusion/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
)
5454
from .io import read_avro, read_csv, read_json, read_parquet
5555
from .plan import ExecutionPlan, LogicalPlan
56-
from .record_batch import RecordBatch, RecordBatchStream
56+
from .record_batch import RecordBatch, RecordBatchStream, to_record_batch_stream
5757
from .user_defined import (
5858
Accumulator,
5959
AggregateUDF,
@@ -107,6 +107,7 @@
107107
"read_json",
108108
"read_parquet",
109109
"substrait",
110+
"to_record_batch_stream",
110111
"udaf",
111112
"udf",
112113
"udtf",

python/datafusion/dataframe.py

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@
2525
from typing import (
2626
TYPE_CHECKING,
2727
Any,
28+
AsyncIterator,
2829
Iterable,
30+
Iterator,
2931
Literal,
3032
Optional,
3133
Union,
@@ -42,7 +44,11 @@
4244
from datafusion._internal import ParquetWriterOptions as ParquetWriterOptionsInternal
4345
from datafusion.expr import Expr, SortExpr, sort_or_default
4446
from datafusion.plan import ExecutionPlan, LogicalPlan
45-
from datafusion.record_batch import RecordBatchStream
47+
from datafusion.record_batch import (
48+
RecordBatch,
49+
RecordBatchStream,
50+
to_record_batch_stream,
51+
)
4652

4753
if TYPE_CHECKING:
4854
import pathlib
@@ -53,6 +59,7 @@
5359
import pyarrow as pa
5460

5561
from datafusion._internal import expr as expr_internal
62+
from datafusion.record_batch import RecordBatch
5663

5764
from enum import Enum
5865

@@ -289,6 +296,9 @@ def __init__(
289296
class DataFrame:
290297
"""Two dimensional table representation of data.
291298
299+
DataFrame objects are iterable; iterating over a DataFrame yields
300+
:class:`pyarrow.RecordBatch` instances lazily.
301+
292302
See :ref:`user_guide_concepts` in the online documentation for more information.
293303
"""
294304

@@ -1098,21 +1108,48 @@ def unnest_columns(self, *columns: str, preserve_nulls: bool = True) -> DataFram
10981108
return DataFrame(self.df.unnest_columns(columns, preserve_nulls=preserve_nulls))
10991109

11001110
def __arrow_c_stream__(self, requested_schema: object | None = None) -> object:
1101-
"""Export an Arrow PyCapsule Stream.
1111+
"""Export the DataFrame as an Arrow C Stream.
1112+
1113+
The DataFrame is executed using DataFusion's streaming APIs and exposed via
1114+
Arrow's C Stream interface. Record batches are produced incrementally, so the
1115+
full result set is never materialized in memory. When ``requested_schema`` is
1116+
provided, only straightforward projections such as column selection or
1117+
reordering are applied.
11021118
1103-
This will execute and collect the DataFrame. We will attempt to respect the
1104-
requested schema, but only trivial transformations will be applied such as only
1105-
returning the fields listed in the requested schema if their data types match
1106-
those in the DataFrame.
1119+
The returned capsule holds a reference to the originating
1120+
:class:`SessionContext`, keeping it alive until the stream is fully
1121+
consumed. The stream is explicitly closed before the context is
1122+
released, so it is safe to drop the original context after obtaining the
1123+
stream.
11071124
11081125
Args:
11091126
requested_schema: Attempt to provide the DataFrame using this schema.
11101127
11111128
Returns:
1112-
Arrow PyCapsule object.
1129+
Arrow PyCapsule object representing an ``ArrowArrayStream``.
11131130
"""
1131+
# ``DataFrame.__arrow_c_stream__`` in the Rust extension leverages
1132+
# ``execute_stream_partitioned`` under the hood to stream batches while
1133+
# preserving the original partition order.
11141134
return self.df.__arrow_c_stream__(requested_schema)
11151135

1136+
def __iter__(self) -> Iterator[pa.RecordBatch]:
1137+
"""Iterate over :class:`pyarrow.RecordBatch` objects.
1138+
1139+
Results are streamed without materializing the full DataFrame. This
1140+
implementation delegates to :func:`to_record_batch_stream`, which executes
1141+
the :class:`DataFrame` and returns a :class:`RecordBatchStream`.
1142+
"""
1143+
return to_record_batch_stream(self).__iter__()
1144+
1145+
def __aiter__(self) -> AsyncIterator[RecordBatch]:
1146+
"""Asynchronously yield record batches from the DataFrame.
1147+
1148+
This delegates to :func:`to_record_batch_stream` to obtain a
1149+
:class:`RecordBatchStream` and returns its asynchronous iterator.
1150+
"""
1151+
return to_record_batch_stream(self).__aiter__()
1152+
11161153
def transform(self, func: Callable[..., DataFrame], *args: Any) -> DataFrame:
11171154
"""Apply a function to the current DataFrame which returns another DataFrame.
11181155

python/datafusion/record_batch.py

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,13 @@
2525

2626
from typing import TYPE_CHECKING
2727

28+
import datafusion._internal as df_internal
29+
2830
if TYPE_CHECKING:
2931
import pyarrow as pa
3032
import typing_extensions
3133

32-
import datafusion._internal as df_internal
34+
from datafusion.dataframe import DataFrame
3335

3436

3537
class RecordBatch:
@@ -52,25 +54,28 @@ class RecordBatchStream:
5254
5355
These are typically the result of a
5456
:py:func:`~datafusion.dataframe.DataFrame.execute_stream` operation.
57+
58+
Call :py:meth:`close` when finished consuming the stream to avoid
59+
lingering background tasks.
5560
"""
5661

5762
def __init__(self, record_batch_stream: df_internal.RecordBatchStream) -> None:
5863
"""This constructor is typically not called by the end user."""
5964
self.rbs = record_batch_stream
6065

61-
def next(self) -> RecordBatch:
62-
"""See :py:func:`__next__` for the iterator function."""
66+
def next(self) -> pa.RecordBatch:
67+
"""Retrieve the next :py:class:`pa.RecordBatch`."""
6368
return next(self)
6469

65-
async def __anext__(self) -> RecordBatch:
66-
"""Async iterator function."""
70+
async def __anext__(self) -> pa.RecordBatch:
71+
"""Async iterator returning :py:class:`pa.RecordBatch`."""
6772
next_batch = await self.rbs.__anext__()
68-
return RecordBatch(next_batch)
73+
return next_batch.to_pyarrow()
6974

70-
def __next__(self) -> RecordBatch:
71-
"""Iterator function."""
75+
def __next__(self) -> pa.RecordBatch:
76+
"""Iterator returning :py:class:`pa.RecordBatch`."""
7277
next_batch = next(self.rbs)
73-
return RecordBatch(next_batch)
78+
return next_batch.to_pyarrow()
7479

7580
def __aiter__(self) -> typing_extensions.Self:
7681
"""Async iterator function."""
@@ -79,3 +84,25 @@ def __aiter__(self) -> typing_extensions.Self:
7984
def __iter__(self) -> typing_extensions.Self:
8085
"""Iterator function."""
8186
return self
87+
88+
def close(self) -> None:
89+
"""Close the stream and release associated resources.
90+
91+
This drains any remaining batches and allows the underlying
92+
:class:`SessionContext` to be released. Call this when you are
93+
done consuming the stream to avoid leaving tasks running in the
94+
background.
95+
"""
96+
self.rbs.close()
97+
98+
99+
def to_record_batch_stream(df: DataFrame) -> RecordBatchStream:
100+
"""Convert a DataFrame into a RecordBatchStream.
101+
102+
Args:
103+
df: DataFrame to convert.
104+
105+
Returns:
106+
A RecordBatchStream representing the DataFrame.
107+
"""
108+
return df.execute_stream()

python/tests/conftest.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import pyarrow as pa
1919
import pytest
20-
from datafusion import SessionContext
20+
from datafusion import DataFrame, SessionContext
2121
from pyarrow.csv import write_csv
2222

2323

@@ -49,3 +49,12 @@ def database(ctx, tmp_path):
4949
delimiter=",",
5050
schema_infer_max_records=10,
5151
)
52+
53+
54+
@pytest.fixture
55+
def fail_collect(monkeypatch):
56+
def _fail_collect(self, *args, **kwargs): # pragma: no cover - failure path
57+
msg = "collect should not be called"
58+
raise AssertionError(msg)
59+
60+
monkeypatch.setattr(DataFrame, "collect", _fail_collect)

0 commit comments

Comments
 (0)