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
82 changes: 79 additions & 3 deletions src/arcadedb/_columnar.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
vector, ``dim``), then for each column its null bitmap (bit i of byte i/8 set means row i is null) and its buffer. A column type is
``i8`` (int64), ``f8`` (float64), ``b1`` (one byte per bool), ``dt`` and ``dtu`` (int64 epoch milliseconds and microseconds),
``f4v`` and ``f8v`` (``dim`` floats per row), ``str`` (int32 offsets, count + 1 of them, then the UTF-8 bytes: Arrow's own string
layout), ``dec`` (a BigDecimal as text in the string layout) and ``json`` (a JSON array of the column, for values no fixed layout
carries: nested lists and maps, RIDs, a DATE next to datetimes, a mixed column).
layout), ``dec`` (a BigDecimal as text in the string layout), ``rid`` (two int64 per row: the bucket and the position of a record
link), ``li8`` and ``lf8`` (a list of int64 or of float64 per row: int32 offsets, count + 1 of them, a bitmap of the null elements, one
bit per element of the flat array, then the elements of every list one after the other) and ``json`` (a JSON array of the column, for
values no fixed layout carries: maps, nested lists, lists of anything else, embedded records, a DATE next to datetimes, a mixed
column). A writer that does not know ``rid``, ``li8`` and ``lf8`` writes ``json`` for those columns, and the decoder reads both.

The interface and the format are shared, the plumbing is per wheel: what differs is how the bytes get here (JPype or ctypes) and the
text of a ``json`` column (the JVM wheel's tagged JSON with a side array of Java objects, the native library's tagged JSON), so the
Expand Down Expand Up @@ -66,6 +69,34 @@ def _decode_decimals(data, count: int, mask) -> list:
]


def rid_texts(pairs) -> list:
"""The RID texts (``"#bucket:position"``) of the ``(count, 2)`` int64 array of a ``rid`` column."""
return [f"#{b}:{p}" for b, p in pairs.tolist()]


def _decode_list_column(data, count: int, ctype: str):
"""``(offsets, flat, null_elements)`` of a ``li8`` or ``lf8`` column buffer: int32 offsets (count + 1), the bitmap of the null
elements, then the flat int64 or float64 array of every list's elements. ``null_elements`` is a bool array (True = null) or None
when no element is null."""
import numpy as np

offs = np.frombuffer(data[: (count + 1) * 4], dtype="<i4")
total = int(offs[count])
start = (count + 1) * 4
bitmap = (total + 7) // 8
bits = np.frombuffer(data[start : start + bitmap], dtype=np.uint8)
emask = (
np.unpackbits(bits, bitorder="little")[:total].astype(bool)
if bits.any()
else None
)
start += bitmap
flat = np.frombuffer(
data[start : start + total * 8], dtype="<i8" if ctype == "li8" else "<f8"
)
return offs, flat, emask


def _missing_column_part(count: int, template):
"""A batch of ``count`` rows that lack a column some other batch has: nulls in
the shape ``to_columns`` uses for that column (NaN for numbers, NaT for
Expand Down Expand Up @@ -253,14 +284,18 @@ def read_header(buf) -> Tuple[Dict[str, Any], int]:


def decode_columns_frame(
buf, side, json_values: Callable, micros: bool = False
buf, side, json_values: Callable, micros: bool = False, rid_values: Callable = None
) -> Tuple[int, Dict[str, Any], Dict[str, Any]]:
"""``(count, parts, header)`` of one frame as ``to_columns`` columns: ``parts`` maps a column name to a numpy array
(int64, float64, bool, datetime64) or a Python list (text, JSON-typed values, a bool column with nulls); a count of 0 has
no parts. A vector column is a (count, dim) matrix, a null row of it NaN.

``micros`` is the ``to_dataframe`` form: a naive datetime column is ``datetime64[us]`` (``dtu``), and a vector column is a
list with one numpy array per cell and None for a null (a NaN row would read as a vector of NaN, not as a missing value).

A ``rid`` column is a list of what ``rid_values(pairs, side, col)`` makes of the ``(count, 2)`` int64 array of its cells (the
wheel's own RID object; the null rows are set to None here), or of the RID texts without it. A ``li8`` or ``lf8`` column is a list
of Python lists (ints or floats, None for a null element), None for a null row.
"""
import numpy as np

Expand Down Expand Up @@ -319,6 +354,27 @@ def decode_columns_frame(
values = [
None if has_nulls and mask[i] else values[i] for i in range(count)
]
elif ctype == "rid":
pairs = np.frombuffer(data, dtype="<i8").reshape(count, 2)
values = (
rid_texts(pairs)
if rid_values is None
else list(rid_values(pairs, side, col))
)
if has_nulls:
for i in np.flatnonzero(mask).tolist():
values[i] = None
elif ctype in ("li8", "lf8"):
offs, flat, emask = _decode_list_column(data, count, ctype)
items = flat.tolist()
if emask is not None:
for j in np.flatnonzero(emask).tolist():
items[j] = None
bounds = offs.tolist()
values = [
None if has_nulls and mask[i] else items[bounds[i] : bounds[i + 1]]
for i in range(count)
]
elif ctype == "json":
values = json_values(data, side, count)
elif ctype == "dec":
Expand Down Expand Up @@ -493,6 +549,26 @@ def decode_arrow_frame(
arr = pa.FixedSizeListArray.from_arrays(child, dim)
if mask is not None:
arr = pa.array(arr.to_pylist(), type=arr.type, mask=mask)
elif ctype == "rid":
# text, as the column of RID objects of the json form degrades to (pyarrow has no type for a RID object)
texts = rid_texts(np.frombuffer(data, dtype="<i8").reshape(count, 2))
if has_nulls:
for i in np.flatnonzero(mask).tolist():
texts[i] = None
arr = pa.array(texts, type=pa.string())
elif ctype in ("li8", "lf8"):
# a list<int64> or list<double> over the frame's own offsets and flat array, with a validity for null rows and elements
offs, flat, emask = _decode_list_column(data, count, ctype)
child = pa.array(flat, mask=emask)
validity = (
None if not has_nulls else pa.py_buffer(np.invert(null_bits).tobytes())
)
arr = pa.ListArray.from_buffers(
pa.list_(child.type),
count,
[validity, pa.py_buffer(offs.tobytes())],
children=[child],
)
elif ctype == "json":
values = json_values(data, side, count)
try:
Expand Down
17 changes: 13 additions & 4 deletions src/arcadedb/_native/colframes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
the shared decoder reads. The first reply of a query (up to ``_FIRST_BATCH`` rows) is JSON text that the row APIs read, and a columnar read
finds those rows (and any the caller read by row) as dicts in the result's buffer. They cannot be read again from the cursor, so they are
written here as one more frame, in the layout the library writes, by the rules the library's encoder follows, and read by the same
decoder: a column has one type however a result splits into the first reply and frames. The JSON reply names the properties that were
decoder: a column has one type however a result splits into the first reply and frames. A column of RIDs, or of lists of numbers, is a
``json`` column here, and a frame of the library may carry it as ``rid``, ``li8`` or ``lf8``: the decoder gives the same values for both forms. The JSON reply names the properties that were
``float[]`` or ``double[]`` (``fv`` and ``dv``): a list of numbers in a row cannot say that by itself, and a vector column is a column of
declared arrays, not a column of lists that happen to fit float32. This frame goes away with the JSON reply.
"""
Expand All @@ -15,7 +16,7 @@
from decimal import Decimal

from .. import _columnar
from .codec import loads_tagged
from .codec import RID, loads_tagged

_EPOCH = datetime(1970, 1, 1)
_MS = timedelta(milliseconds=1)
Expand All @@ -29,6 +30,12 @@ def json_values(data, side, count):
return loads_tagged(bytes(data).decode("utf-8"))[0]


def rid_objects(pairs, side, col):
"""The RID objects of a ``rid`` column of a frame from the library: its bucket and position pairs, as the native build's ``RID`` of the text
the tagged JSON of a link value gives."""
return [RID(text) for text in _columnar.rid_texts(pairs)]


def _head_json_values(data, side, count):
"""The values of a ``json`` column of the head frame: the buffered values themselves, by the index the column carries."""
return side[int.from_bytes(bytes(data), "little")]
Expand Down Expand Up @@ -182,7 +189,9 @@ def _head_frame(rows, columns, hints, micros):


def decode_columns(raw, micros):
return _columnar.decode_columns_frame(memoryview(raw), (), json_values, micros)
return _columnar.decode_columns_frame(
memoryview(raw), (), json_values, micros, rid_objects
)


def decode_arrow(raw):
Expand All @@ -196,7 +205,7 @@ def columns_result(head_rows, columns, micros, batches, hints):
if head_rows:
frame, side = _head_frame(head_rows, columns, hints, micros)
count, parts, _ = _columnar.decode_columns_frame(
frame, side, _head_json_values, micros
frame, side, _head_json_values, micros, rid_objects
)
names.extend(parts)
parts_list.append((count, parts))
Expand Down
13 changes: 12 additions & 1 deletion src/arcadedb/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
frame_rows,
merge_arrow,
merge_columns,
rid_texts,
)
from ._logging import get_logger
from .callbacks import raise_pending_interrupt
Expand Down Expand Up @@ -103,6 +104,16 @@ def hook(obj):
return hook


def _typed_rid_values(pairs, side, col):
"""The engine's RID objects of a ``rid`` column of a ColumnBatcher frame: the bridge puts them into the side array in row order from
the index ``col["side"]`` (an RID is a record link of a database, which a bucket and a position cannot be turned back into here).
"""
start = col.get("side")
if start is None:
return rid_texts(pairs)
return [convert_java_to_python(side[start + i]) for i in range(len(pairs))]


def _typed_json_values(data, side, count):
"""The values of a ``json`` column of a ColumnBatcher frame: the tagged JSON (TypedRows) with its side array of Java objects."""
return json.loads(bytes(data), object_hook=_typed_hook(side))
Expand Down Expand Up @@ -894,7 +905,7 @@ def _read_columns_counted(self, batch_size, columns, micros):
raise _read_error(exc) from exc
buf = memoryview(bytes(java_batch[0]))
count, parts, _ = decode_columns_frame(
buf, java_batch[1], _typed_json_values, micros
buf, java_batch[1], _typed_json_values, micros, _typed_rid_values
)
if count == 0:
self._finish()
Expand Down
Loading
Loading