Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,14 @@ datetime64[ms] timestamp[ms]

A missing library does not fail the same way everywhere. `to_columns()` returns `None` when numpy is missing and `to_arrow()` returns `None` when pyarrow is missing, so that a caller can fall back to another reader. `to_polars()` and `to_dataframe()` raise `ImportError`. Check for `None` before you use the result of the first two.

== Read a large result in batches

`to_arrow()` builds the whole table, so its peak memory grows with the result. `result.to_arrow_reader(batch_size=25_000)` returns a `pyarrow.RecordBatchReader` instead: one record batch per frame of at most `batch_size` rows, read from the engine only when the next batch is asked for. It returns `None` when pyarrow is missing, as `to_arrow()` does. The result is closed when the reader has been read to its end or is closed.

A result also implements the Arrow C Stream interface (`__arrow_c_stream__`), so `pyarrow.table(result)` and `polars.DataFrame(result)` read it through the reader. A result is a cursor, so it is read once: a second read has no rows. DuckDB asks an object for its stream more than once and so cannot read a result directly. Pass it the reader: `reader = result.to_arrow_reader()`, then `duckdb.sql("SELECT count(*) FROM reader")`.

The types are those of `to_arrow()`, with one difference that a stream cannot avoid. A reader must tell its schema before the first batch, so the schema is the one of the first batch, while `to_arrow()` sees every batch before it picks a type. A later batch that lacks a column adds nulls, and a value that converts without loss is converted. A column that first appears in a later batch, or a value that does not convert, raises `ArcadeDBError` that names the column. For a result whose properties vary from row to row, use `to_arrow()`, or name the `columns`. The first batch of a native result is the rows of its first reply. Memory and speed are not measured yet.

== Differences between the two builds

The calls above, the types and the results are the same on `arcadedb` and `arcadedb-jvm`, and so is how `to_columns()` and `to_arrow()` get the rows: both read the result from the engine as packed columns, in requests of at most `batch_size` rows, so `batch_size` sets how many rows cross at a time. One thing differs, the message of a missing pandas: the JVM package adds the `uv add` hint to the `ImportError` of `to_dataframe()`, and the native package raises the plain `ImportError`. Another difference is how `insert_arrow` and `insert_dataframe` pass a timestamp or date column to the engine, which is described on xref:how-to/bulk-loads.adoc#columnar-loads[Bulk loads and commit size]. The stored values are the same on both packages.
Expand Down
67 changes: 67 additions & 0 deletions src/arcadedb/_columnar.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,3 +628,70 @@ def merge_arrow(
for n in names
}
)


def arrow_batch_reader(frames, columns, close):
"""A ``pyarrow.RecordBatchReader`` over ``frames``, an iterator of ``(count, chunks)`` as :func:`decode_arrow_frame` returns them
(empty frames left out). One record batch comes out per frame, and a frame is read from the cursor only when a batch is asked for.

A reader needs its schema before the first batch, so the schema is the first frame's columns and types (a table, :func:`merge_arrow`,
sees every frame first). A later frame that lacks a column adds nulls, and a chunk is cast to the column's type when the cast keeps
every value. A column that first appears in a later frame, or a type that does not cast, raises ``ArcadeDBError`` that names
the column: read such a result with ``to_arrow()``, or name ``columns``. ``close()`` is called once, when the frames end, the
reader is closed, or a frame fails.
"""
import pyarrow as pa

from .exceptions import ArcadeDBError

it = iter(frames)
try:
first = next(it, None)
except BaseException:
close()
raise
if first is None:
close()
schema = pa.schema([(n, pa.null()) for n in (columns or ())])
return pa.RecordBatchReader.from_batches(schema, iter(()))

names = list(first[1])
schema = pa.schema([(n, first[1][n].type) for n in names])

def batch(frame):
count, chunks = frame
for n in chunks:
if n not in schema.names:
raise ArcadeDBError(
f"The column {n!r} first appears after the first batch of the reader, whose schema is fixed by that batch. "
"Read this result with to_arrow(), which sees every batch, or name the columns."
)
if not names:
return pa.RecordBatch.from_struct_array(
pa.array([{}] * count, pa.struct([]))
)
arrays = []
for field in schema:
arr = chunks.get(field.name)
if arr is None:
arr = pa.nulls(count, field.type)
elif arr.type != field.type:
try:
arr = arr.cast(field.type)
except (pa.ArrowInvalid, pa.ArrowNotImplementedError):
raise ArcadeDBError(
f"The column {field.name!r} has type {field.type} in the first batch of the reader and {arr.type} in a later one, "
"and the values do not convert. Read this result with to_arrow(), which gives the column one type."
) from None
arrays.append(arr)
return pa.RecordBatch.from_arrays(arrays, schema=schema)

def generate():
try:
yield batch(first)
for frame in it:
yield batch(frame)
finally:
close()

return pa.RecordBatchReader.from_batches(schema, generate())
60 changes: 58 additions & 2 deletions src/arcadedb/_native/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,14 @@ def _read_frames(self, batch_size, columns, decode, flags=0):
self._buf.clear()
if self._pending_error is not None:
self._fill() # the rows before the error are consumed: raise it
batches = list(self._frames(size, spec, decode, flags))
self._finish()
return head_rows, batches

def _frames(self, size, spec, decode, flags):
"""``(count, parts)`` of each column frame the cursor yields, read as the caller asks; ``decode(frame_bytes)`` makes the parts."""
while self._more and self._rs:
self._readable() # raises when the database was closed since the last frame
try:
raw = lib.call_frame(self._rs, size, spec, flags)
except lib.ColumnFrameError as exc:
Expand All @@ -605,9 +612,58 @@ def _read_frames(self, batch_size, columns, decode, flags=0):
f"{size}). This is a bug in the library or in the wheel."
)
if count:
batches.append((count, parts))
yield count, parts

def _arrow_batches(self, size, spec, columns):
"""``(count, chunks)`` of the rest of the result as Arrow chunks: the rows this object holds as dicts first (one frame), then
each column frame of the cursor. The result is finished when the frames end."""
from . import colframes

head_rows = [props for props, _ in self._buf]
self._buf.clear()
if self._pending_error is not None:
self._fill() # the rows before the error are consumed: raise it
if head_rows:
frame, side = colframes._head_frame(
head_rows, columns, self._vectors, False
)
count, chunks, _ = _columnar.decode_arrow_frame(
frame, side, colframes._head_json_values
)
yield count, chunks
yield from self._frames(size, spec, colframes.decode_arrow, 0)
self._finish()
return head_rows, batches

def to_arrow_reader(self, batch_size: int = 25_000, columns=None):
"""The rest of the result as a ``pyarrow.RecordBatchReader``, one record batch per frame (the rows of the first reply as one,
then at most ``batch_size`` rows each), read from the library only when the next batch is asked for. The types are those of
:meth:`to_arrow`, but the schema is fixed by the first batch: a later batch that lacks a column adds nulls, a lossless cast is
applied, and anything else (a column that first appears later) raises ``ArcadeDBError`` naming the column. Use :meth:`to_arrow`
for a result whose columns vary by row. The result is closed when the reader has been read to its end or closed. None when
pyarrow or numpy is missing."""
try:
__import__("numpy") # availability check
__import__("pyarrow")
except ImportError:
return None
size = _columnar.frame_rows(batch_size)
if not self._readable():
return _columnar.arrow_batch_reader(iter(()), columns, self.close)
spec = json.dumps(list(columns)).encode("utf-8") if columns is not None else b""
return _columnar.arrow_batch_reader(
self._arrow_batches(size, spec, columns), columns, self.close
)

def __arrow_c_stream__(self, requested_schema=None):
"""The Arrow C Stream interface: ``pyarrow.table(result)``, ``polars.from_arrow(result)`` and DuckDB read the rest of the
result through :meth:`to_arrow_reader`. Raises ``ImportError`` when pyarrow or numpy is missing.
"""
reader = self.to_arrow_reader()
if reader is None:
raise ImportError(
"The Arrow C Stream interface needs pyarrow and numpy. Install with: uv add 'arcadedb[arrow]'"
)
return reader.__arrow_c_stream__(requested_schema)

def to_dataframe(self, convert_types: bool = True):
"""The rows as a ``pandas.DataFrame``, read as column frames (no dict per row). The values are the ones ``to_list()`` returns,
Expand Down
66 changes: 60 additions & 6 deletions src/arcadedb/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -991,7 +991,22 @@ def to_arrow(
size = frame_rows(batch_size)
if not self._readable():
return empty_arrow(columns)
for count, chunks in self._arrow_frames(column_batcher, size, spec):
for name in chunks:
if name not in names:
names.append(name)
batches.append((count, chunks))

return merge_arrow(names, batches, columns)

def _arrow_frames(self, column_batcher: Any, size: int, spec: str) -> Iterator:
"""``(count, chunks)`` of each column frame of the rest of the result, read from the cursor as the caller asks. The result is
finished when the frames end."""
while True:
if (
not self._readable()
): # raises when the database was closed since the last frame
return
try:
java_batch = column_batcher.nextColumnBatch(
self._java_result_set, size, spec, False
Expand All @@ -1004,13 +1019,52 @@ def to_arrow(
)
if count == 0:
self._finish()
break
for name in chunks:
if name not in names:
names.append(name)
batches.append((count, chunks))
return
yield count, chunks

return merge_arrow(names, batches, columns)
def to_arrow_reader(
self, batch_size: int = 25_000, columns: Optional[Sequence[str]] = None
) -> Any:
"""
The rest of the result as a ``pyarrow.RecordBatchReader``, one record batch per column frame (at most ``batch_size`` rows), read from
the engine only when the next batch is asked for. Peak memory is one batch, not the whole result as in :meth:`to_arrow`.

The types are those of :meth:`to_arrow`, with one difference that a stream cannot avoid: the schema is fixed by the first batch.
A later batch that lacks a column adds nulls and a value that converts without loss is converted (an ``int64`` chunk into a
``float64`` column), and anything else, such as a column that first appears in a later batch, raises ``ArcadeDBError`` naming the
column. Use :meth:`to_arrow` for a result whose columns vary by row, or pass ``columns``. The result is closed when the reader
has been read to its end or closed; close the reader, or this result, when you stop early.

Returns None when pyarrow, numpy, or the bridge jar is unavailable, as :meth:`to_arrow` does.
"""
try:
__import__("numpy") # availability check
__import__("pyarrow") # availability check
except ImportError:
return None
column_batcher = _bridge_class("ColumnBatcher")
if column_batcher is None:
return None
from ._columnar import arrow_batch_reader

spec = json.dumps(list(columns)) if columns is not None else ""
size = frame_rows(batch_size)
if not self._readable():
return arrow_batch_reader(iter(()), columns, self.close)
return arrow_batch_reader(
self._arrow_frames(column_batcher, size, spec), columns, self.close
)

def __arrow_c_stream__(self, requested_schema: Any = None) -> Any:
"""The Arrow C Stream interface: ``pyarrow.table(result)``, ``polars.from_arrow(result)`` and DuckDB read the rest of the result
through :meth:`to_arrow_reader` without a copy. Raises ``ImportError`` when pyarrow, numpy or the bridge jar is missing.
"""
reader = self.to_arrow_reader()
if reader is None:
raise ImportError(
"The Arrow C Stream interface needs pyarrow, numpy and the bridge jar. Install with: uv add 'arcadedb-jvm[arrow]'"
)
return reader.__arrow_c_stream__(requested_schema)

def iter_chunks(
self, size: int = 1000, convert_types: bool = True
Expand Down
Loading
Loading