Skip to content
Draft
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
8 changes: 7 additions & 1 deletion src/arcadedb/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,13 @@ def _column_to_java(name, values):
# a string, bytes, or object array: its elements are Python objects (str, None, ...), converted one by one below
values = list(values.astype(object, copy=False))
elif not isinstance(values, (list, tuple)):
if isinstance(values, _java_class("com.arcadedb.python.TemporalColumn")):
if isinstance(
values,
(
_java_class("com.arcadedb.python.TemporalColumn"),
_java_class("com.arcadedb.python.StringColumn"),
),
):
return values, int(values.rows())
values = list(values)
column = _string_column(values)
Expand Down
44 changes: 44 additions & 0 deletions src/arcadedb/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,42 @@ def _temporal_column(chunk, pa):
)


def _arrow_string_column(chunk, pa):
"""A string or large string chunk as one bridge ``StringColumn`` built from Arrow's own buffers, or None when the chunk is not that.

Arrow already holds a string column as offsets plus one UTF-8 blob, which is what ``StringColumn`` takes: the offsets are rebased to
start at 0 (a batch of ``to_batches`` is a slice of the table) and narrowed to int32, and the blob is the bytes between the first and
the last offset. No Python ``str`` is made per cell, where ``to_pylist`` made one per row and ``core._string_column`` then encoded
them again. None (the chunk then goes the ``to_pylist`` way) when the chunk is empty, a text offset does not fit an int32 (a blob of
2 GiB or more), or a null row has text (the bridge reads a flagged row as an empty range).
"""
import numpy as np

n = len(chunk)
if not n:
return None
large = pa.types.is_large_string(chunk.type)
validity, offset_buffer, data_buffer = chunk.buffers()[:3]
offsets = np.frombuffer(offset_buffer, dtype=np.int64 if large else np.int32)[
chunk.offset : chunk.offset + n + 1
]
first, last = int(offsets[0]), int(offsets[-1])
if last - first > _JAVA_INT_MAX:
return None
mask = None
if chunk.null_count:
is_null = chunk.is_null().to_numpy(zero_copy_only=False)
if (np.diff(offsets)[is_null] != 0).any():
return None
mask = jpype.JArray(jpype.JBoolean)(is_null)
blob = b"" if data_buffer is None else memoryview(data_buffer)[first:last].tobytes()
return jpype.JClass("com.arcadedb.python.StringColumn")(
jpype.JArray(jpype.JByte)(blob),
jpype.JArray(jpype.JInt)((offsets - first).astype(np.int32)),
mask,
)


def _temporal_to_tagged(chunk, pa):
"""A timestamp or date chunk as tagged values (``T`` date-time, ``D`` date) for the native backend, with the same
reading rules as :func:`_temporal_column`: ISO text of the integer epoch value, so a nanosecond value keeps its
Expand Down Expand Up @@ -431,6 +467,14 @@ def _column_values(
matrix = _float32_matrix(pa, chunk)
if matrix is not None:
return matrix
if (
not native
and kind == "string"
and (types.is_string(chunk.type) or types.is_large_string(chunk.type))
):
column = _arrow_string_column(chunk, pa)
if column is not None:
return column
if kind in ("timestamp", "date"):
return _temporal_to_tagged(chunk, pa) if native else _temporal_column(chunk, pa)
if native and kind in ("decimal", "binary"):
Expand Down
3 changes: 3 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@
collect_ignore.append("test_native_vector_provider.py")
# the copy of a record's values as read that save() compares with the stored row (arcadedb._native.records), counted through its seams
collect_ignore.append("test_native_save_baseline.py")
# the parameters of the UPDATE of save(): only the changed values are merged (arcadedb._native.records), read at the statement seam
collect_ignore.append("test_native_save_merge.py")
# crossing and foreign-call counts of the transaction entry points (lib.tx and lib.call are the native library's ctypes doors)
collect_ignore.append("test_native_tx_crossings.py")
# counts the statement texts the native backend hands to the engine (the JPype backend has no such layer)
Expand Down Expand Up @@ -177,6 +179,7 @@
"test_graph_batch_vector_crossings_jvm.py": "the JPype crossings of the JVM wheel's create_vertices vector path (the bridge classes, the property-matrix fallback)",
"test_insert_columns_string_blob.py": "the bridge's StringColumn and the JVM wheel's core._column_to_java (JPype arrays, a spy on the per-element conversion)",
"test_arrow_vector_column_jvm.py": "the JPype crossings of the JVM wheel's Arrow vector column (core.convert_python_to_java, the bridge's FloatVectors.Matrix) and its Python heap",
"test_arrow_string_column_jvm.py": "the JVM wheel's Arrow string column (dataframe._arrow_string_column, the bridge's StringColumn, JPype arrays)",
"test_arrow_temporal_column_jvm.py": "the JPype calls of the JVM wheel's Arrow timestamp and date columns (the bridge's TemporalColumn, core._column_to_java, java.time classes)",
"test_async_proxy_cache.py": "the JPype proxy classes of the JVM build's async executor",
"test_read_crossings.py": "crossing counts of the JVM build's read path (JPype proxies of the Java objects and the bridge classes)",
Expand Down
87 changes: 87 additions & 0 deletions tests/test_arrow_string_column_jvm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""The JVM wheel builds a string column of insert_arrow and insert_dataframe from Arrow's own buffers.

An Arrow string column is already offsets plus one UTF-8 blob, which is what the bridge's ``StringColumn`` takes. Before, every batch went
through ``to_pylist`` (one Python ``str`` per row) and ``core._string_column`` encoded those again. Now ``dataframe._arrow_string_column``
rebases the offsets (a batch of ``to_batches`` is a slice) and sends the bytes between the first and the last offset. These tests check
that the column is a ``StringColumn`` (it fails on the code before, where the column is a list) and that the stored table is the one the
``to_pylist`` route stores, for slices, nulls, large_string and non-BMP text.
"""

import jpype
import pytest

np = pytest.importorskip("numpy")
pa = pytest.importorskip("pyarrow")

from arcadedb import dataframe # noqa: E402

TEXTS = [
"plain",
"",
"emoji \U0001f600 \U0010ffff",
"embedded\x00nul",
"中文 한글 é",
"x" * 3000,
]


def _string_column_class():
return jpype.JClass("com.arcadedb.python.StringColumn")


def _java_strings(column):
return [column.get(i) for i in range(column.rows())]


@pytest.mark.parametrize(
"kind", [pa.string(), pa.large_string()], ids=["string", "large"]
)
def test_a_string_chunk_is_one_string_column_that_reads_back_the_same(temp_db, kind):
values = [None if i % 4 == 1 else TEXTS[i % len(TEXTS)] for i in range(40)]
out = dataframe._column_values("label", pa.array(values, type=kind), pa)
assert isinstance(out, _string_column_class())
assert _java_strings(out) == values


def test_a_slice_of_a_chunk_is_rebased(temp_db):
values = [TEXTS[i % len(TEXTS)] + str(i) for i in range(50)]
chunk = pa.array(values).slice(7, 20)
assert chunk.offset == 7
out = dataframe._column_values("label", chunk, pa)
assert _java_strings(out) == values[7:27]


def test_a_null_row_with_text_or_an_empty_chunk_keeps_the_to_pylist_route(temp_db):
offsets = pa.array([0, 1, 3, 4], type=pa.int32())
data = pa.py_buffer(b"abcd")
validity = pa.py_buffer(bytes([0b101])) # row 1 is null but holds "bc"
chunk = pa.Array.from_buffers(
pa.string(), 3, [validity, offsets.buffers()[1], data]
)
assert chunk.to_pylist() == ["a", None, "d"]
assert dataframe._column_values("label", chunk, pa) == ["a", None, "d"]
assert dataframe._column_values("label", pa.array([], type=pa.string()), pa) == []


def test_insert_arrow_stores_the_strings_and_makes_no_python_string_per_row(
temp_db, monkeypatch
):
from arcadedb import core

temp_db.command("sql", "CREATE DOCUMENT TYPE S")
temp_db.command("sql", "CREATE PROPERTY S.id LONG")
temp_db.command("sql", "CREATE PROPERTY S.label STRING")
n = 5_000
label = [
None if i % 6 == 2 else TEXTS[i % len(TEXTS)] + str(i % 5) for i in range(n)
]
table = pa.table(
{"id": pa.array(range(n), type=pa.int64()), "label": pa.array(label)}
)
monkeypatch.setattr(
core, "_string_column", lambda values: pytest.fail("a str per row was built")
)
# batch_size 1_300 makes every batch after the first a slice of the table
assert temp_db.insert_arrow("S", table, batch_size=1_300) == n
rows = temp_db.query("sql", "SELECT FROM S ORDER BY id").to_list()
assert [(r["id"], r.get("label")) for r in rows] == list(zip(range(n), label))