Skip to content
This repository was archived by the owner on Nov 21, 2026. It is now read-only.
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
10 changes: 10 additions & 0 deletions bindings/python/docs/api/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,16 @@ Close the database connection. It also closes the async executor
([`async_executor`](#async_executor)) if this handle handed it out, and a `Database`
that is garbage-collected closes itself.

A result set, a result, or a record read from the database keeps its `Database` alive,
so a function can open a database, query it, and return the result without closing
anything: the database closes when the last of them is freed. While one is alive the
engine refuses a second `open_database()` of the same path ("already in use"). After
`close()`, reading a record, a record row (`SELECT FROM T`), or a result set that was not
read to its end raises `ArcadeDBError` ("Database is closed"), as `db.query()` does; a
projection or command `Result` that was already returned keeps its own values and stays
readable. Earlier versions returned empty rows or `None` values and the engine logged
`Possible corrupted record` for each read (humemai/arcadedb-embedded-python#117).

A handle from `ArcadeDBServer.get_database()` or `ArcadeDBServer.create_database()`
belongs to the server: `close()` only marks that handle closed, and the database stays open for the
server and its other handles until `server.stop()`.
Expand Down
5 changes: 5 additions & 0 deletions bindings/python/docs/api/record-wrappers.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ The Python API provides wrapper classes for database records: `Document`, `Verte
| `Vertex` | Wrapper for graph vertices | Creating edges, traversal |
| `Edge` | Wrapper for graph edges | Accessing source/target vertices |

A record read from a database keeps that `Database` alive, and reading it after the
database was closed raises `ArcadeDBError` ("Database is closed"). The engine loads a
record's properties lazily from the open database, so there is nothing to return once
it is closed. See [`Database.close()`](database.md#close).

## Document Wrapper

The `Document` class is the base wrapper for all record types. Use it for documents and
Expand Down
10 changes: 10 additions & 0 deletions bindings/python/docs/api/results.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,16 @@ read it again: the rows it had not returned are gone, so run the query again. (U
which depended on the engine build.) To take one row and keep reading, use
`next(iter(rs))` rather than `first()`.

A result set, and each `Result` it returns, keeps its `Database` alive. Reading a result
set after the database was closed (`db.close()`, or leaving the `with` block that opened
it) raises `ArcadeDBError` ("Database is closed") unless it was already read to its end,
because the rows it has not returned may still be read lazily from the engine. A `Result`
that is a record row (`SELECT FROM T`) raises too: its properties are loaded lazily from
the open database, so there is nothing to return. A `Result` that is a projection
(`SELECT name FROM T`) or a command result (for example the one `IMPORT DATABASE`
returns) holds its own values and stays readable, so it can be read after the database
is closed. See [`Database.close()`](database.md#close).

Closing is not only memory hygiene: since 26.10.1's parallel scan
(ArcadeData/arcadedb#8524) a query whose `LIMIT` is satisfied keeps its scan's producer
threads parked until its result set is closed or
Expand Down
20 changes: 14 additions & 6 deletions bindings/python/docs/api/type_conversion.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ that JPype performs the conversion automatically (a Python `int` reaches Java as
|-------------|-----------|
| `None` | `null` |
| `Decimal` | `BigDecimal` |
| `set` | `HashSet` |
| `set` | `HashSet` (stored as a list, see below) |
| `dict` | `HashMap` |
| `list` | `ArrayList` |
| `tuple` | `ArrayList` |
Expand Down Expand Up @@ -136,7 +136,7 @@ Convert Java object to Python value.
| `LocalDateTime` | `datetime` |
| `Instant`, `ZonedDateTime`, `OffsetDateTime` | `datetime` (UTC) |
| `Map` | `dict` |
| `Set` | `set` |
| `Set` | `set` (a stored property is never a `Set`: it was written as a list) |
| `List`, `Collection` | `list` |

**Notes:**
Expand Down Expand Up @@ -296,9 +296,9 @@ with db.transaction():
vertex.set("tags", ["python", "java", "database"])
tags = vertex.get("tags") # list

# set → HashSet
# set → HashSet, stored as a list: a set is a set only until the commit
vertex.set("roles", {"admin", "user"})
roles = vertex.get("roles") # set
roles = vertex.get("roles") # set, in this transaction only

# Nested lists
vertex.set("matrix", [[1, 2], [3, 4]])
Expand Down Expand Up @@ -362,7 +362,7 @@ with db.transaction():
vertex.set("numbers", [3, 1, 4, 1, 5, 9])
numbers = vertex.get("numbers") # [3, 1, 4, 1, 5, 9]

# Sets remove duplicates
# Sets remove duplicates (in this transaction: see the note below)
vertex.set("unique", {3, 1, 4, 1, 5, 9})
unique = vertex.get("unique") # {1, 3, 4, 5, 9}

Expand All @@ -371,6 +371,14 @@ with db.transaction():
mapping = vertex.get("mapping") # {"a": 1, "b": 2, "c": 3}
```

**A `set` reads back as a `list`.** The engine has no set type (its `Type` enum has
`LIST` and `MAP`), so a `HashSet` is serialized as a list when the transaction
commits. The record you set it on still holds the `HashSet` until then, which is why
`vertex.get("roles")` returns a `set` inside the transaction. After the commit every
read (`lookup_by_rid()`, a query row's `get()`, `to_list()`) returns a `list`, in no
particular order. Duplicates are still removed. If your code needs a set, convert on
read: `set(vertex.get("roles"))`.

## Complete Example

```python
Expand Down Expand Up @@ -401,7 +409,7 @@ with db.transaction():

# Collections
product.set("tags", ["electronics", "laptop"]) # list
product.set("categories", {"computers", "tech"}) # set
product.set("categories", {"computers", "tech"}) # set, a list after the commit

# Nested structures
product.set("specs", {
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/docs/development/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ numpy_array = to_python_array(java_array)
| `None` | `null` | Automatic |
| `list` | `ArrayList` | Converted by `convert_python_to_java()` (used by `set()`, and by a bound parameter that is one of several arguments) |
| `tuple` | `ArrayList` | Converted by `convert_python_to_java()` |
| `set` | `HashSet` | Converted by `convert_python_to_java()` |
| `set` | `HashSet` | Converted by `convert_python_to_java()`; stored as a list, so it reads back as a `list` after the commit |
| `dict` | `HashMap` | Converted by `convert_python_to_java()` |
| `Decimal` | `BigDecimal` | Converted by `convert_python_to_java()` |
| `datetime` | `java.util.Date` | Converted by `convert_python_to_java()` |
Expand Down
14 changes: 14 additions & 0 deletions bindings/python/docs/development/testing/test-graph-batch.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ return 0, `out()` from the source 100, and the target vertex's
`get_in_edges()` is empty. Fails on 26.9.1, where the incoming Cypher pattern
returned 0.

### 9) a failed create_vertices leaves no transaction open

`test_graph_batch_create_vertices_failure_rolls_back` (JSON-bulk and
property-matrix paths): two rows with the same key on a unique index make
`create_vertices` raise `ArcadeDBError`, `db.is_transaction_active()` is `False`
afterwards, the batch still creates the next vertex, and an `INSERT` outside any
transaction is refused. Fails before humemai/arcadedb-embedded-python#121, where
the transaction stayed active and the insert was accepted and lost at close.
`test_graph_batch_create_vertices_keeps_the_callers_transaction` checks the other
half: a transaction the caller opened before the call is still active after the
failure. `test_graph_batch_create_vertices_keyboard_interrupt_rolls_back` raises
`KeyboardInterrupt` after the engine's transaction has begun and expects the
rollback to run.

## Why It Matters

`GraphBatch` is the repository's preferred bulk graph-ingest path from Python, so these tests protect the performance-oriented API surface and its configuration validation behavior.
11 changes: 11 additions & 0 deletions bindings/python/docs/development/testing/test-resultset.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ Since 26.10.1's parallel scan (ArcadeData/arcadedb#8524) a query whose `LIMIT` i
- **exhaustion, first and one close the Java result set**: `list(rs)`, `to_list()`, `first()`, and `one()` each leave the result set closed.
- **a set closed before its end raises when read again**: after `first()`, each of `list()`, `to_list()`, `first()`, `count()`, `iter_json_batches()`, and `to_columns()` raises `ArcadeDBError` ("closed before"), and so does `to_list()` after a `with` block that took one row; a set read to its end reads as empty through `list()`, `to_list()`, `first()`, and `iter_json_batches()`.

### Results and records after their database is closed (`test_results_after_close.py`)

A result, a result set, or a record keeps the `Database` it came from alive and raises `ArcadeDBError` ("Database is closed") once that database is closed (humemai/arcadedb-embedded-python#117). Before, a record row read `{}`, a record property read `None`, and a plain scan raised a raw `TransactionException`.

- **reads through a closed database raise**: after `db.close()`, `to_list()` and iteration of two open result sets, and `get`, `to_dict`, `to_json`, `get_vertex`, `get_element`, `get_property_names`, `has_property`, and `get_out_edges` on a row and a vertex taken earlier, each raise.
- **a projection result set is refused, a projection or command row is not**: an unread `SELECT name ...` result set raises after `close()`, because its rows may still be read lazily; a `Result` taken from it (or from a command) before the close holds its own values and still reads (example 16 reads an `IMPORT DATABASE` result after closing its database).
- **a set read to its end stays empty**: after `to_list()` and `close()`, `to_list()` returns `[]`.
- **a result keeps its dropped database open**: a function that opens a database, queries it, and returns the rows and a vertex without closing anything returns real data after `gc.collect()`, where it returned `[{}, {}, {}]` and `{}`.
- **the kept database is open for the engine**: while those results live a second `open_database()` of the path raises "already in use"; once they are deleted it opens.
- **the reference does not leak the database**: with every result and record deleted the wrapper's `__del__` closes the database and the path opens again.

## Handy patterns from the tests

```python
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ assert record.get("metadata")["version"] == 1

---

### test_a_python_set_is_a_set_only_until_the_commit

A Python `set` set on a vertex reads back as a `set` inside the transaction, and as a `list` from `lookup_by_rid()`, a query row's `get()`, and `to_list()` after the commit: the engine has no set type and serializes the `HashSet` as a list (humemai/arcadedb-embedded-python#122). The duplicate in `{"admin", "user", "admin"}` is gone either way. If the engine ever keeps sets this fails, and [Type Conversion](../../api/type_conversion.md) changes with it.

---

### test_nested_collection_conversion

Tests conversion of nested collections.
Expand Down Expand Up @@ -374,7 +380,7 @@ assert result.get("null_val") is None
| `Decimal` | `BigDecimal` | High precision |
| `list` | `ArrayList` | Ordered |
| `tuple` | `ArrayList` | Becomes list |
| `set` | `HashSet` | Unique items |
| `set` | `HashSet` | Unique items; stored as a list, so it reads back as a `list` after the commit |
| `dict` | `HashMap` | Key-value |

## Key Takeaways
Expand Down
20 changes: 10 additions & 10 deletions bindings/python/src/arcadedb_embedded/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,16 @@ def _java_class(name):
return cls


def _wrap_java_record(java_record):
def _wrap_java_record(java_record, database=None):
"""Wrap a Java record in the matching Python class (Vertex/Edge/Document)."""
if java_record is None:
return None
if isinstance(java_record, _java_class("com.arcadedb.graph.Vertex")):
return Vertex(java_record)
return Vertex(java_record, database)
if isinstance(java_record, _java_class("com.arcadedb.graph.Edge")):
return Edge(java_record)
return Edge(java_record, database)
if isinstance(java_record, _java_class("com.arcadedb.database.Document")):
return Document(java_record)
return Document(java_record, database)
return java_record


Expand Down Expand Up @@ -114,7 +114,7 @@ def query(self, language: str, command: str, *args) -> ResultSet:
java_result = self._java_db.query(language, command, *converted_args)
else:
java_result = self._java_db.query(language, command)
return ResultSet(java_result)
return ResultSet(java_result, self)
except Exception as e:
raise ArcadeDBError(f"Query failed: {e}") from e

Expand All @@ -129,7 +129,7 @@ def command(self, language: str, command: str, *args) -> Optional[ResultSet]:
java_result = self._java_db.command(language, command)

if java_result is not None:
return ResultSet(java_result)
return ResultSet(java_result, self)
return None
except Exception as e:
raise ArcadeDBError(f"Command failed: {e}") from e
Expand Down Expand Up @@ -218,7 +218,7 @@ def new_vertex(self, type_name: str) -> Vertex:
"""Create a new vertex."""
self._check_not_closed()
try:
return Vertex(self._java_db.newVertex(type_name))
return Vertex(self._java_db.newVertex(type_name), self)
except Exception as e:
raise ArcadeDBError(
f"Failed to create vertex of type '{type_name}': {e}"
Expand All @@ -228,7 +228,7 @@ def new_document(self, type_name: str) -> Document:
"""Create a new document."""
self._check_not_closed()
try:
return Document(self._java_db.newDocument(type_name))
return Document(self._java_db.newDocument(type_name), self)
except Exception as e:
raise ArcadeDBError(
f"Failed to create document of type '{type_name}': {e}"
Expand Down Expand Up @@ -424,7 +424,7 @@ def lookup_by_key(self, type_name: str, keys: List[str], values: List[Any]):
# Return first result wrapped, or None
if cursor.hasNext():
java_record = cursor.next().getRecord()
return Document.wrap(java_record)
return Document.wrap(java_record, self)
return None
except Exception as e:
raise ArcadeDBError(f"Failed to lookup by key in '{type_name}': {e}") from e
Expand Down Expand Up @@ -459,7 +459,7 @@ def lookup_by_rid(self, rid: str) -> Any:
def _lookup_by_java_rid(self, java_rid) -> Any:
"""Lookup by an already-Java RID, skipping string parsing (hot path)."""
java_record = self._java_db.lookupByRID(java_rid, True)
return _wrap_java_record(java_record)
return _wrap_java_record(java_record, self)

def to_java_rid(self, value):
self._check_not_closed()
Expand Down
Loading
Loading