diff --git a/src/arcadedb/_native/lib.py b/src/arcadedb/_native/lib.py index 55c6e93..2579698 100644 --- a/src/arcadedb/_native/lib.py +++ b/src/arcadedb/_native/lib.py @@ -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", @@ -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 @@ -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() diff --git a/tests/test_native_reply_reader.py b/tests/test_native_reply_reader.py index 0b78909..dbe8f72 100644 --- a/tests/test_native_reply_reader.py +++ b/tests/test_native_reply_reader.py @@ -13,6 +13,7 @@ import ctypes import json +import sys import numpy as np import pytest @@ -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