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
20 changes: 15 additions & 5 deletions src/arcadedb/_native/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
import os
import sys
import threading
from array import array
from pathlib import Path

from .. import _logdir
from ..exceptions import ArcadeDBError

try: # numpy is optional (the extra arcadedb[numpy]): without it the float32 tail is read with the standard library
import numpy as _np
except ImportError: # pragma: no cover
_np = None

_LIB_NAMES = {
"linux": "libarcadedb.so",
"darwin": "libarcadedb.dylib",
Expand Down Expand Up @@ -397,11 +403,14 @@ def _take(lib, th, ptr, tail: bool):
i = peek.rfind(_TAIL_KEY)
if i >= 0:
n = int(peek[i + 7 : -1])
import numpy as np

off = (end + 1 + 3) & ~3
floats = np.frombuffer(
ctypes.string_at(ptr + off, 4 * n), dtype=np.float32
raw = ctypes.string_at(ptr + off, 4 * n)
# a float32 numpy array; where NumPy is not installed an ``array.array("f")`` of the same bytes (float32 on every platform
# we build for): the decoder asks of it only slices and tolist(), and both give the same Python floats
floats = (
_np.frombuffer(raw, dtype=_np.float32)
if _np is not None
else array("f", raw)
)
# the text ends at the marker, closed by the "}" that the JSON object needs: written over the marker's comma
# in the reply's own memory (it is freed below), so the decode reads the JSON as it stands
Expand All @@ -421,7 +430,8 @@ def call(name: str, *args) -> dict:

def call_bin(name: str, *args):
"""Like :func:`call` for a reply that may carry a float32 tail (``arcadedb_n_exec*`` with flag 4): returns ``(text, floats)``,
floats a float32 numpy array or None. The JSON ends with ``,"bin":N}`` and the N floats follow its NUL, 4-byte aligned.
floats a float32 numpy array (an ``array.array`` of float32 where NumPy is not installed) or None. The JSON ends with ``,"bin":N}`` and the N
floats follow its NUL, 4-byte aligned.
"""
lib = _lib or _load()
th = _thread_handle()
Expand Down
46 changes: 46 additions & 0 deletions tests/test_native_reply_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import ctypes
import json
import sys

import numpy as np
import pytest
Expand Down Expand Up @@ -193,3 +194,48 @@ def test_the_public_readers_free_each_reply_once(temp_db, frees):
assert len(frees) == 1
lib.call("arcadedb_n_diag")
assert len(frees) == 2


def _without_numpy(monkeypatch):
"""The reader as it runs where the optional NumPy extra (``arcadedb[numpy]``) is not installed (#444)."""
monkeypatch.setitem(
sys.modules, "numpy", None
) # an import of it raises ImportError
monkeypatch.setattr(lib, "_np", None, raising=False) # and the module's own handle


@pytest.mark.parametrize(
"raw, values",
[
(
b'{"ok":true,"rows":[{"v":["B",0,4]}],"drained":true}',
[1.5, -2.5, 3.25, 4.0],
),
(b'{"ok":true}', []),
],
ids=["four floats", "no floats"],
)
def test_a_tail_is_read_without_numpy(temp_db, frees, monkeypatch, raw, values):
th = lib._thread_handle()
ptr, _ = _reply(raw, values)
_without_numpy(monkeypatch)
text, floats = lib._take(lib._lib, th, ptr, True)
assert json.loads(text) == json.loads(
raw
) # the text is a whole JSON value without the marker
assert floats.tolist() == values
assert floats[1:3].tolist() == values[1:3] # what the decoder asks of it
assert frees == [ptr]


def test_a_select_of_a_float_array_needs_no_numpy(temp_db, monkeypatch):
values = [
i / 4 for i in range(16)
] # 8 or more floats travel in the float32 tail; these are exact in float32
temp_db.command("sql", "CREATE DOCUMENT TYPE FloatDoc")
temp_db.command("sql", "CREATE PROPERTY FloatDoc.v ARRAY_OF_FLOATS")
with temp_db.transaction():
temp_db.command("sql", f"INSERT INTO FloatDoc SET v = {values!r}")
_without_numpy(monkeypatch)
assert temp_db.query("sql", "SELECT FROM FloatDoc").to_list()[0]["v"] == values
assert temp_db.query("sql", "SELECT FROM FloatDoc").to_json_list()[0]["v"] == values
Loading