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
2 changes: 2 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 @@ -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")
Expand Down
17 changes: 15 additions & 2 deletions src/arcadedb/_columnar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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(
Expand Down
20 changes: 16 additions & 4 deletions src/arcadedb/_native/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -584,16 +591,21 @@ 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):
"""Columns as the JVM build returns them (numpy int64/float64/bool/datetime64[ms] arrays, lists for text and JSON-typed
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:
Expand Down
24 changes: 17 additions & 7 deletions src/arcadedb/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
decode_columns_frame,
empty_arrow,
empty_columns,
frame_row_total,
frame_rows,
merge_arrow,
merge_columns,
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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
Expand All @@ -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."""
Expand All @@ -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(
Expand All @@ -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
Expand Down
29 changes: 29 additions & 0 deletions tests/test_columnar_readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,35 @@ 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()
and to_dataframe(): the readers dropped the row count with the (empty) column names.
"""
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)
# 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")],
Expand Down
10 changes: 10 additions & 0 deletions tests/test_dataframe_columns_behavior.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down
Loading