From a23d10aff93355b8e598e8fbac6055e0084aa995 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Thu, 3 Dec 2026 12:06:03 +0900 Subject: [PATCH 1/3] to_arrow_reader() and __arrow_c_stream__ on both builds: a RecordBatchReader with one batch per frame, the schema of the first batch (#322) --- .../pages/how-to/dataframes-and-columns.adoc | 8 + src/arcadedb/_columnar.py | 67 ++++++++ src/arcadedb/_native/database.py | 59 ++++++- src/arcadedb/results.py | 62 ++++++- tests/test_resultset_arrow_reader.py | 154 ++++++++++++++++++ 5 files changed, 342 insertions(+), 8 deletions(-) create mode 100644 tests/test_resultset_arrow_reader.py diff --git a/docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc b/docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc index 4398fc91..72d2a2ea 100644 --- a/docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc +++ b/docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc @@ -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. diff --git a/src/arcadedb/_columnar.py b/src/arcadedb/_columnar.py index ba00a7ec..7d0c2557 100644 --- a/src/arcadedb/_columnar.py +++ b/src/arcadedb/_columnar.py @@ -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()) diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 85cfe5c9..8039ba5b 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -582,6 +582,12 @@ 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: try: raw = lib.call_frame(self._rs, size, spec, flags) @@ -605,9 +611,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, diff --git a/src/arcadedb/results.py b/src/arcadedb/results.py index 9b201ceb..f8bfe9e6 100644 --- a/src/arcadedb/results.py +++ b/src/arcadedb/results.py @@ -991,6 +991,17 @@ 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: try: java_batch = column_batcher.nextColumnBatch( @@ -1004,13 +1015,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 diff --git a/tests/test_resultset_arrow_reader.py b/tests/test_resultset_arrow_reader.py new file mode 100644 index 00000000..11ef4139 --- /dev/null +++ b/tests/test_resultset_arrow_reader.py @@ -0,0 +1,154 @@ +"""Tests for ResultSet.to_arrow_reader() and the Arrow C Stream interface (#322), on both builds. + +A reader is a stream: it needs its schema before its first batch, so the schema is the first batch's (a table sees every batch first). +The tests below pin the batches, the values against ``to_arrow()``, the Arrow C Stream consumers, the schema rules for a column that +varies, and that the result is closed when the reader ends or is closed. +""" + +import pytest + +import arcadedb +from arcadedb.exceptions import ArcadeDBError + +pa = pytest.importorskip("pyarrow") + +ROWS = 5_000 + + +@pytest.fixture +def db(temp_db_path): + with arcadedb.create_database(temp_db_path) as database: + database.command("sql", "CREATE DOCUMENT TYPE Rec") + with database.transaction(): + for i in range(ROWS): + database.command( + "sql", + "INSERT INTO Rec SET id = :i, name = :name, x = :x, ok = :ok", + {"i": i, "name": f"n{i}", "x": i / 2, "ok": i % 2 == 0}, + ) + yield database + + +QUERY = "SELECT id, name, x, ok FROM Rec ORDER BY id" + + +def test_the_batches_are_bounded_and_equal_to_to_arrow(db): + expected = db.query("sql", QUERY).to_arrow() + reader = db.query("sql", QUERY).to_arrow_reader(batch_size=700) + assert isinstance(reader, pa.RecordBatchReader) + batches = list(reader) + assert len(batches) > 1 + assert max(b.num_rows for b in batches) <= 700 + assert sum(b.num_rows for b in batches) == ROWS + assert pa.Table.from_batches(batches).equals(expected) + + +def test_the_reader_reads_the_cursor_only_when_a_batch_is_asked_for(db): + result = db.query("sql", QUERY) + reader = result.to_arrow_reader(batch_size=100) + first = reader.read_next_batch() + assert first.num_rows > 0 + assert not result._closed # rows are still in the cursor + reader.read_all() + assert result._closed + + +def test_closing_the_reader_closes_the_result(db): + result = db.query("sql", QUERY) + reader = result.to_arrow_reader(batch_size=100) + reader.read_next_batch() + reader.close() + # the generator finishes on close; a result that was read to the middle is closed + del reader + import gc + + gc.collect() + assert result._closed + + +def test_columns_are_passed_on(db): + reader = db.query("sql", QUERY).to_arrow_reader(columns=["id", "name"]) + table = reader.read_all() + assert table.column_names == ["id", "name"] + assert table.num_rows == ROWS + + +def test_an_empty_result_is_a_reader_with_no_batch(db): + reader = db.query("sql", "SELECT FROM Rec WHERE id < 0").to_arrow_reader( + columns=["id"] + ) + assert reader.schema.names == ["id"] + assert list(reader) == [] + + +def test_pyarrow_table_reads_the_result_through_the_c_stream(db): + expected = db.query("sql", QUERY).to_arrow() + result = db.query("sql", QUERY) + assert hasattr(result, "__arrow_c_stream__") + assert pa.table(result).equals(expected) + assert result._closed + + +def test_polars_reads_the_result_through_the_c_stream(db): + pl = pytest.importorskip("polars") + frame = pl.DataFrame(db.query("sql", QUERY)) + assert frame.shape == (ROWS, 4) + assert frame["id"].to_list() == list(range(ROWS)) + + +def test_duckdb_reads_the_reader_and_a_result_is_one_shot(db): + """DuckDB calls ``__arrow_c_stream__`` of an object more than once, which a cursor cannot serve twice: give DuckDB the reader.""" + duckdb = pytest.importorskip("duckdb") + # DuckDB finds the variable by its name in the SQL text + reader = db.query("sql", QUERY).to_arrow_reader(batch_size=700) # noqa: F841 + rel = duckdb.sql("SELECT count(*), sum(id) FROM reader") + assert rel.fetchall() == [(ROWS, sum(range(ROWS)))] + + +def test_a_second_read_of_a_result_has_no_rows(db): + result = db.query("sql", QUERY) + assert pa.table(result).num_rows == ROWS + assert pa.table(result).num_rows == 0 + + +def test_a_column_that_first_appears_in_a_later_batch_is_refused(temp_db_path): + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE DOCUMENT TYPE V") + with db.transaction(): + for i in range(300): + db.command("sql", "INSERT INTO V SET id = :i", {"i": i}) + db.command("sql", "INSERT INTO V SET id = 300, late = 'x'") + query = "SELECT FROM V ORDER BY id" + # a table sees every batch, so it has the column + assert "late" in db.query("sql", query).to_arrow(batch_size=100).column_names + reader = db.query("sql", query).to_arrow_reader(batch_size=100) + with pytest.raises(ArcadeDBError, match="late"): + reader.read_all() + + +def test_a_column_that_is_missing_from_a_later_batch_gets_nulls(temp_db_path): + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE DOCUMENT TYPE V") + with db.transaction(): + for i in range(300): + db.command("sql", "INSERT INTO V SET id = :i, tag = 'x'", {"i": i}) + for i in range(300, 600): + db.command("sql", "INSERT INTO V SET id = :i", {"i": i}) + table = ( + db.query("sql", "SELECT FROM V ORDER BY id") + .to_arrow_reader(batch_size=100) + .read_all() + ) + assert table.num_rows == 600 + assert table.column("tag").null_count == 300 + + +def test_a_result_with_rows_and_no_property_keeps_its_rows(temp_db_path): + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE DOCUMENT TYPE E") + with db.transaction(): + for _ in range(3): + db.command("sql", "INSERT INTO E CONTENT {}") + table = db.query("sql", "SELECT FROM E").to_arrow_reader().read_all() + assert table.num_rows == 3 + assert table.num_columns == 0 From c9cbd00687e2c52bdbcd3b4c63a9624e8fca2b26 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Thu, 3 Dec 2026 12:17:13 +0900 Subject: [PATCH 2/3] to_arrow_reader: a query that fails in the middle of the frames raises from the reader and closes the result (the test #331 left open) --- tests/test_resultset_arrow_reader.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/test_resultset_arrow_reader.py b/tests/test_resultset_arrow_reader.py index 11ef4139..06c57a29 100644 --- a/tests/test_resultset_arrow_reader.py +++ b/tests/test_resultset_arrow_reader.py @@ -152,3 +152,26 @@ def test_a_result_with_rows_and_no_property_keeps_its_rows(temp_db_path): table = db.query("sql", "SELECT FROM E").to_arrow_reader().read_all() assert table.num_rows == 3 assert table.num_columns == 0 + + +def test_a_query_that_fails_in_the_middle_of_the_frames_raises_and_closes_the_result( + temp_db_path, +): + """The batches before the failing frame are delivered, then the engine's error comes out of the reader, and the result is closed + (the missing test of #331 for a failure in the middle of a frame stream).""" + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE DOCUMENT TYPE R") + with db.transaction(): + for i in range(6000): + text = "bad" if i == 4000 else str(i) + db.command( + "sql", "INSERT INTO R SET id = :i, s = :s", {"i": i, "s": text} + ) + result = db.query("sql", "SELECT id, s.asLong() AS v FROM R") + reader = result.to_arrow_reader(batch_size=500) + delivered = 0 + with pytest.raises(ArcadeDBError, match="NumberFormatException"): + for batch in reader: + delivered += batch.num_rows + assert 0 < delivered <= 4000 + assert result._closed From f29f97e4a7fa3952ae56e77181d28a827c750e8d Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Thu, 3 Dec 2026 12:25:35 +0900 Subject: [PATCH 3/3] Result frame reads check that the database is still open before each frame; the reader test closes the database mid-read instead of relying on an engine error --- src/arcadedb/_native/database.py | 1 + src/arcadedb/results.py | 4 ++++ tests/test_resultset_arrow_reader.py | 28 ++++++++++++---------------- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 8039ba5b..5f977e5d 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -589,6 +589,7 @@ def _read_frames(self, batch_size, columns, decode, flags=0): 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: diff --git a/src/arcadedb/results.py b/src/arcadedb/results.py index f8bfe9e6..7dfc6a68 100644 --- a/src/arcadedb/results.py +++ b/src/arcadedb/results.py @@ -1003,6 +1003,10 @@ 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 diff --git a/tests/test_resultset_arrow_reader.py b/tests/test_resultset_arrow_reader.py index 06c57a29..ff12c0f4 100644 --- a/tests/test_resultset_arrow_reader.py +++ b/tests/test_resultset_arrow_reader.py @@ -154,24 +154,20 @@ def test_a_result_with_rows_and_no_property_keeps_its_rows(temp_db_path): assert table.num_columns == 0 -def test_a_query_that_fails_in_the_middle_of_the_frames_raises_and_closes_the_result( +def test_closing_the_database_in_the_middle_of_the_frames_raises_from_the_reader( temp_db_path, ): - """The batches before the failing frame are delivered, then the engine's error comes out of the reader, and the result is closed - (the missing test of #331 for a failure in the middle of a frame stream).""" - with arcadedb.create_database(temp_db_path) as db: + """The batches already read are the caller's; the next frame of a reader whose database was closed raises the engine-independent + 'Database is closed' error and does not touch the closed engine.""" + db = arcadedb.create_database(temp_db_path) + try: db.command("sql", "CREATE DOCUMENT TYPE R") with db.transaction(): for i in range(6000): - text = "bad" if i == 4000 else str(i) - db.command( - "sql", "INSERT INTO R SET id = :i, s = :s", {"i": i, "s": text} - ) - result = db.query("sql", "SELECT id, s.asLong() AS v FROM R") - reader = result.to_arrow_reader(batch_size=500) - delivered = 0 - with pytest.raises(ArcadeDBError, match="NumberFormatException"): - for batch in reader: - delivered += batch.num_rows - assert 0 < delivered <= 4000 - assert result._closed + db.command("sql", "INSERT INTO R SET id = :i", {"i": i}) + reader = db.query("sql", "SELECT id FROM R").to_arrow_reader(batch_size=500) + assert reader.read_next_batch().num_rows > 0 + finally: + db.close() + with pytest.raises(ArcadeDBError, match="closed"): + reader.read_all()