From 8340528d3b1d47ad2e9f93f73e79f411638071a5 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Sun, 22 Nov 2026 18:40:00 +0900 Subject: [PATCH 1/2] Rows without properties keep their count in to_arrow, to_polars and to_dataframe A result whose rows have no property (records created with none) had N rows in to_list() and count() and no row in the columnar readers: merge_arrow and merge_columns returned the empty result whenever there were no column names, and the row count went with them. merge_arrow now returns a table of N rows and no column, and to_dataframe gets the row count next to the dict of columns on both wheels, so it returns a frame of N rows and no column. to_polars follows to_arrow. to_columns() keeps returning {} for such a result: a dict of columns has no place for a row count. Its docstring and the how-to page say so. Closes #429 --- .../pages/how-to/dataframes-and-columns.adoc | 2 ++ src/arcadedb/_columnar.py | 17 ++++++++-- src/arcadedb/_native/database.py | 20 ++++++++--- src/arcadedb/results.py | 24 ++++++++++---- tests/test_columnar_readers.py | 33 +++++++++++++++++++ 5 files changed, 83 insertions(+), 13 deletions(-) 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 9cf0d116..4398fc91 100644 --- a/docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc +++ b/docs/modules/ROOT/pages/how-to/dataframes-and-columns.adoc @@ -280,6 +280,8 @@ The next block stores one record with every value and one record with none, then * `to_polars()` goes through Arrow, so it keeps the type too. * `to_dataframe()` returns a pandas frame with the pandas types, `NaN` for a gap in a number and `NaT` in a date-time. +A result whose rows have no property at all (records created with none) keeps its rows in `to_arrow()`, `to_polars()` and `to_dataframe()`: a table or frame of that many rows and no column. `to_columns()` returns `{}` for it, because a dict of columns has no place for a row count. + [source,python] ---- db.command("sql", "CREATE DOCUMENT TYPE Rec") diff --git a/src/arcadedb/_columnar.py b/src/arcadedb/_columnar.py index 70ac47e5..63f5816f 100644 --- a/src/arcadedb/_columnar.py +++ b/src/arcadedb/_columnar.py @@ -412,13 +412,22 @@ def _pandas_would_round(values) -> bool: return any(type(v) is int and not -_TWO53 <= v <= _TWO53 for v in values) -def dataframe_from_columns(columns): +def frame_row_total(batches) -> int: + """The number of rows in the decoded frames ``batches`` (a list of ``(count, parts)``).""" + return sum(count for count, _ in batches) + + +def dataframe_from_columns(columns, rows: int = 0): """The ``pandas.DataFrame`` of the ``to_columns`` dict ``columns`` (what both wheels' ``to_dataframe`` builds). A column that is a list holding an integer beyond +-2**53 next to a float is an ``object`` column of the exact Python values, as ``to_columns()`` returns them: pandas would make it float64 and round the integer (#340). Every other column is handed to pandas as it was. + ``rows`` is the row count of the result: a dict with no column cannot carry it, so rows that have no property come as it. """ import pandas as pd + if not columns and rows: + # rows that have no property: a frame of that many rows and no column, as pandas.DataFrame([{}, {}]) is (#429) + return pd.DataFrame(index=pd.RangeIndex(rows)) exact = { name: pd.Series(values, dtype=object) for name, values in columns.items() @@ -523,8 +532,12 @@ def merge_arrow( :func:`_unify_arrow_chunk_types`), a frame that lacks a column adds nulls.""" import pyarrow as pa - if not batches or not names: + if not batches: return empty_arrow(columns) + if not names: + # rows that have no property: a table of that many rows and no column (#429). pa.table({}) would have no rows. + rows = frame_row_total(batches) + return pa.Table.from_struct_array(pa.array([{}] * rows, pa.struct([]))) return pa.table( { n: pa.chunked_array( diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 68fe2f10..ede51ef6 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -573,9 +573,16 @@ def to_dataframe(self, convert_types: bool = True): """ # availability check: a missing pandas raises before the cursor is read __import__("pandas") - return _columnar.dataframe_from_columns(self._columns(25_000, None, True)) + return _columnar.dataframe_from_columns( + *self._columns_counted(25_000, None, True) + ) def _columns(self, batch_size, columns, micros): + return self._columns_counted(batch_size, columns, micros)[0] + + def _columns_counted(self, batch_size, columns, micros): + """``(columns, rows)``: the ``to_columns()`` dict and the row count of the result, which the dict cannot carry when the rows + have no property (#429).""" from . import colframes head_rows, batches = self._read_frames( @@ -584,8 +591,12 @@ def _columns(self, batch_size, columns, micros): lambda raw: colframes.decode_columns(raw, micros), 1 if micros else 0, ) - return colframes.columns_result( - head_rows, columns, micros, batches, self._vectors + rows = len(head_rows) + _columnar.frame_row_total(batches) + return ( + colframes.columns_result( + head_rows, columns, micros, batches, self._vectors + ), + rows, ) def to_columns(self, batch_size: int = 25_000, columns=None): @@ -593,7 +604,8 @@ def to_columns(self, batch_size: int = 25_000, columns=None): values, an object array of Decimal), decoded from column frames by the decoder both builds share. The arrays are writable, and a column's type belongs to the whole result, not to where a batch ends. A column is a float32 matrix when the property is a ``float[]`` (ARRAY_OF_FLOATS), and a list of lists when it is a LIST of numbers whatever the values; a null vector is a row of - NaN in the matrix (``to_dataframe()`` and ``to_arrow()`` keep it a null). An empty result is + NaN in the matrix (``to_dataframe()`` and ``to_arrow()`` keep it a null). Rows that have no property are ``{}`` as well: a + dict of columns has no place for a row count, so read such a result with ``to_arrow()``, ``to_dataframe()`` or ``count()``. An empty result is ``{}``, or the ``columns`` asked for as empty lists. None when numpy is missing. """ try: diff --git a/src/arcadedb/results.py b/src/arcadedb/results.py index d8a0f839..d398511d 100644 --- a/src/arcadedb/results.py +++ b/src/arcadedb/results.py @@ -18,6 +18,7 @@ decode_columns_frame, empty_arrow, empty_columns, + frame_row_total, frame_rows, merge_arrow, merge_columns, @@ -758,10 +759,10 @@ def to_dataframe(self, convert_types: bool = True): # Datetimes cross with their microseconds (datetime64[us]) and dates as # date objects, the values to_list() returns; to_columns() and # to_arrow() keep the documented milliseconds. - columns = self._read_columns(25_000, None, micros=True) - if columns is not None: + found = self._read_columns_counted(25_000, None, micros=True) + if found is not None: # a vector column is already one numpy array per cell, None for a null - return dataframe_from_columns(columns) + return dataframe_from_columns(*found) return pd.DataFrame(self.to_list(convert_types=convert_types)) @@ -826,7 +827,9 @@ def to_columns( holds only nulls for it takes the type of the batches that have values. The arrays are writable. A vector column is a ``(count, dim)`` matrix and a null vector is a row of NaN in it (``to_dataframe()`` and ``to_arrow()`` keep - it a null). An empty result is ``{}``, or, when + it a null). Rows that have no property are ``{}`` as well: a dict of + columns has no place for a row count, so read such a result with + ``to_arrow()``, ``to_dataframe()`` or ``count()``. An empty result is ``{}``, or, when ``columns`` is given, those columns as empty lists. The columns are the union of every row's property names, in order of @@ -848,7 +851,14 @@ def to_columns( return self._read_columns(batch_size, columns, micros=False) def _read_columns(self, batch_size, columns, micros): - """``to_columns()``; with ``micros`` a column of datetimes is a + """The dict of :meth:`_read_columns_counted`, or None.""" + found = self._read_columns_counted(batch_size, columns, micros) + return None if found is None else found[0] + + def _read_columns_counted(self, batch_size, columns, micros): + """``(columns, rows)``: the ``to_columns()`` dict and the row count of the + result, which the dict cannot carry when the rows have no property (#429). + With ``micros`` a column of datetimes is a ``datetime64[us]`` array and a column holding DATE values is an object column of ``date`` objects, which is what ``to_dataframe()`` needs to return the values ``to_list()`` does.""" @@ -874,7 +884,7 @@ def _read_columns(self, batch_size, columns, micros): spec = json.dumps(list(columns)) if columns is not None else "" size = frame_rows(batch_size) if not self._readable(): - return empty_columns(columns) + return empty_columns(columns), 0 while True: try: java_batch = column_batcher.nextColumnBatch( @@ -894,7 +904,7 @@ def _read_columns(self, batch_size, columns, micros): names.append(name) batches.append((count, parts)) - return merge_columns(names, batches, columns) + return merge_columns(names, batches, columns), frame_row_total(batches) def to_arrow( self, batch_size: int = 25_000, columns: Optional[Sequence[str]] = None diff --git a/tests/test_columnar_readers.py b/tests/test_columnar_readers.py index 58e47293..8a7946c5 100644 --- a/tests/test_columnar_readers.py +++ b/tests/test_columnar_readers.py @@ -223,6 +223,39 @@ def test_to_columns_of_differing_rows_keeps_what_to_list_returns( assert _typed(column) == _typed(expected) +@pytest.mark.parametrize("batch_size", [25_000, 2]) +def test_rows_without_properties_keep_their_count(temp_db_path, batch_size): + """#429: three vertices created with no property were three rows in to_list() and count(), and no row in to_arrow(), + to_polars() and to_dataframe(): the readers dropped the row count with the (empty) column names. + """ + import polars as pl # in the test extra; the repository accepts no skips + + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE VERTEX TYPE Bare") + with db.transaction(): + for _ in range(3): + db.command("sql", "CREATE VERTEX Bare") + q = "SELECT FROM Bare" + assert len(db.query("sql", q).to_list()) == 3 + table = db.query("sql", q).to_arrow(batch_size=batch_size) + assert (table.num_rows, table.num_columns) == (3, 0) + assert db.query("sql", q).to_dataframe().shape == (3, 0) + frame = db.query("sql", q).to_polars(batch_size=batch_size) + assert isinstance(frame, pl.DataFrame) and frame.shape == (3, 0) + # a dict of columns has no place for a row count: documented, not a loss of rows elsewhere + assert db.query("sql", q).to_columns(batch_size=batch_size) == {} + + +def test_an_empty_result_is_still_empty_in_every_reader(temp_db_path): + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE VERTEX TYPE Bare") + q = "SELECT FROM Bare" + table = db.query("sql", q).to_arrow() + assert (table.num_rows, table.num_columns) == (0, 0) + assert db.query("sql", q).to_dataframe().shape == (0, 0) + assert db.query("sql", q).to_columns() == {} + + DECIMAL_CASES = { "36 digits": [Decimal("12345678901234567890.123456789012345678")], "whole amounts only": [Decimal("2"), Decimal("3")], From 897ea1df919def22638fbd21cb19d748d0bfc355 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Sun, 22 Nov 2026 19:19:03 +0900 Subject: [PATCH 2/2] Tests for #429: the Polars assertion moves to the file that needs Polars The free-threaded leg (Python 3.14t) runs test_columnar_readers.py without Polars installed, so the import in the new test failed there. The to_polars() assertion is now its own test in test_dataframe_columns_behavior.py, which the legs without Polars do not run. --- tests/test_columnar_readers.py | 8 ++------ tests/test_dataframe_columns_behavior.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/tests/test_columnar_readers.py b/tests/test_columnar_readers.py index 8a7946c5..804ed5e2 100644 --- a/tests/test_columnar_readers.py +++ b/tests/test_columnar_readers.py @@ -225,11 +225,9 @@ def test_to_columns_of_differing_rows_keeps_what_to_list_returns( @pytest.mark.parametrize("batch_size", [25_000, 2]) def test_rows_without_properties_keep_their_count(temp_db_path, batch_size): - """#429: three vertices created with no property were three rows in to_list() and count(), and no row in to_arrow(), - to_polars() and to_dataframe(): the readers dropped the row count with the (empty) column names. + """#429: three vertices created with no property were three rows in to_list() and count(), and no row in to_arrow() + and to_dataframe(): the readers dropped the row count with the (empty) column names. """ - import polars as pl # in the test extra; the repository accepts no skips - with arcadedb.create_database(temp_db_path) as db: db.command("sql", "CREATE VERTEX TYPE Bare") with db.transaction(): @@ -240,8 +238,6 @@ def test_rows_without_properties_keep_their_count(temp_db_path, batch_size): table = db.query("sql", q).to_arrow(batch_size=batch_size) assert (table.num_rows, table.num_columns) == (3, 0) assert db.query("sql", q).to_dataframe().shape == (3, 0) - frame = db.query("sql", q).to_polars(batch_size=batch_size) - assert isinstance(frame, pl.DataFrame) and frame.shape == (3, 0) # a dict of columns has no place for a row count: documented, not a loss of rows elsewhere assert db.query("sql", q).to_columns(batch_size=batch_size) == {} diff --git a/tests/test_dataframe_columns_behavior.py b/tests/test_dataframe_columns_behavior.py index aa6459f6..99aad2aa 100644 --- a/tests/test_dataframe_columns_behavior.py +++ b/tests/test_dataframe_columns_behavior.py @@ -195,6 +195,16 @@ def test_a_uint64_column_at_the_signed_limit_loads(temp_db): ] +def test_to_polars_keeps_rows_that_have_no_property(temp_db): + """#429: to_polars() reads to_arrow(), which now keeps the rows of a result whose rows have no property.""" + temp_db.command("sql", "CREATE VERTEX TYPE Bare") + with temp_db.transaction(): + for _ in range(3): + temp_db.command("sql", "CREATE VERTEX Bare") + frame = temp_db.query("sql", "SELECT FROM Bare").to_polars() + assert isinstance(frame, pl.DataFrame) and frame.shape == (3, 0) + + def test_a_type_with_no_mapping_is_refused_before_a_row_is_written(temp_db): temp_db.command("sql", "CREATE DOCUMENT TYPE NoMap") with pytest.raises(TypeError, match="no ArcadeDB mapping"):