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
1 change: 1 addition & 0 deletions docs/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
** xref:how-to/concurrency.adoc[Concurrency, processes and crashes]
** xref:how-to/asyncio.adoc[asyncio: AsyncDatabase]
** xref:how-to/durability.adoc[Durability settings]
** xref:how-to/key-value.adoc[Key-value storage with SQL]
** xref:how-to/async-executor.adoc[The async executor]
** xref:how-to/logs.adoc[Where the logs go]
** xref:how-to/bulk-loads.adoc[Bulk loads and commit size]
Expand Down
12 changes: 10 additions & 2 deletions docs/modules/ROOT/pages/how-to/durability.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ You need this page if a commit that returned must survive a power loss or an ope

* By default a commit that returned survives a crash of the process, but the engine does not flush its write-ahead log (WAL) at commit, so it can lose recent commits in a power loss.
* `db.set_wal_flush("yes_nometadata")` or `db.set_wal_flush("yes_full")` makes every commit flush the WAL. It applies to the open `Database`, to every thread, and is not saved.
* `ALTER DATABASE` with `arcadedb.txWalFlush` stores the same choice with the database, as the level `0`, `1` or `2`.
* `ALTER DATABASE` with `arcadedb.txWalFlush` stores the same choice with the database, as the level `0`, `1` or `2`. A database that is already open does not follow it: close and open it again (see the warning in <<engine-settings,The settings of the engine>>).
* `GraphBatch` and the async executor do not follow either. Each has its own setting, which this page lists.
* This page gives no timing. A flush waits for the disk, and what that costs on your storage is yours to measure. No default is recommended here.

Expand Down Expand Up @@ -111,6 +111,7 @@ Invalid WAL flush mode: fsync. Must be one of: ['no', 'yes_nometadata', 'yes_ful

It applies to the transactions of every thread of that `Database`, also of a thread that never called it, and not to another database in the process. The JVM build has tests that read the flush type of a thread's next transaction from the engine: after the call, a second thread and the calling thread both use the chosen type, a second open database keeps its own, and a reopened database goes back to the configured one. The native build calls the same engine method. Python cannot read the effective flush type there, so the native tests check that the call is accepted, refused or stored as described above, and no more.

[[engine-settings]]
== The settings of the engine

`ALTER DATABASE` stores a database setting in the configuration of the database, so it is still there after a reopen. It is the same statement on both builds:
Expand All @@ -127,7 +128,14 @@ db.command("sql", "ALTER DATABASE `arcadedb.txWalFlush` 0")
1
----

A test reopens a database after `ALTER DATABASE` and reads the level again on both builds. On the JVM build, a thread that starts after the statement commits with the stored level. The engine reads the configured level when a thread gets its first transaction context, so this page does not say what the statement does to a thread that has a transaction context already. To change the flush of the running process at once, use `set_wal_flush`.
A test reopens a database after `ALTER DATABASE` and reads the level again on both builds. On the JVM build, a thread that starts after the statement commits with the stored level.

[WARNING]
====
A database that is open when you run `ALTER DATABASE` `arcadedb.txWalFlush` does not follow the new level in the thread that ran it, and the setting still reads back as the new level. The engine reads the configured level when a thread gets its first transaction context, and a thread that has one keeps it. In `strace` runs of 26.11.1.post4 on both builds, 300 commits after the statement on the open database made 0 or 1 `fdatasync` calls. After closing and opening the database again they made 302 or 304, and with `-Darcadedb.txWalFlush=1` at process start 305. A read-back of `schema:database` is not proof that commits flush.

Close the database and open it again after the statement, set the system property at process start, or call `set_wal_flush` on the open database (300 `fdatasync` calls in the same run). The page xref:how-to/key-value.adoc#flush-check[Key-value storage with SQL] shows the `strace` check.
====

Group commit is a database setting too:

Expand Down
166 changes: 166 additions & 0 deletions docs/modules/ROOT/pages/how-to/key-value.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
= Key-value storage with SQL
:description: A durable key-value store in ArcadeDB through plain SQL on both builds: a document type with a unique index, upsert, get, delete and prefix scan, how to make every commit survive a power loss, and how to check with strace that it does.

// Sources: ArcadeDB 26.11.1 (RedisProtocolPlugin, the "Key/Value with the Redis Wire Protocol" section of the main manual). The blocks are pinned by tests/test_docs_key_value_page.py. The sync counts come from strace runs of 26.11.1.post4 of both packages on 2026-12-04. What a crash loses is the engine's statement: no test here can lose power.

You need this page if your program keeps keys and values in ArcadeDB, and a write that returned must still be there after the process is killed or the machine loses power. The recipe is one document type with a unique index on `key`, written and read with SQL. It works the same on both builds. The short version:

* An upsert is `UPDATE kv SET key = ?, value = ? UPSERT WHERE key = ?` inside a transaction. A get is `db.lookup_by_key(...)` or a `SELECT` on `key`. Both use the unique index.
* A prefix scan is a range on `key`, in index order.
* A commit that returned survives a crash of the process with the default settings. To survive a power loss as well, set `arcadedb.txWalFlush` to `1` or `2`, and make sure the setting is active. `ALTER DATABASE` alone is not enough in a database that is already open.
* The simple string commands of the Redis protocol plugin (`SET`, `GET`) are not for this. The main manual says they work on an in-memory namespace (see {arcadedb-docs-url}/concepts/key-value[Key/Value]).

The blocks on this page run one after the other against one empty database, and a test in the repository runs them that way (`tests/test_docs_key_value_page.py`) on the JVM build and on the native build. Each block that prints something is followed by its output. Every block assumes that `db` is an open database.

== The type

A document type with a `key` and a `value`, and a unique index on `key`. The index is what makes the upsert and the get cost a lookup, and what stops two records from having the same key:

[source,python]
----
db.command("sql", "CREATE DOCUMENT TYPE kv")
db.command("sql", "CREATE PROPERTY kv.key STRING")
db.command("sql", "CREATE PROPERTY kv.value STRING")
db.command("sql", "CREATE INDEX ON kv (key) UNIQUE")
----

== Put, get and delete

`UPSERT` updates the record with that key, or inserts one when there is none. Put the key in both the `SET` and the `WHERE`, so that an insert gets it. `lookup_by_key` takes the properties of the index, in its order, and returns the record or `None`:

[source,python]
----
def put(key, value):
with db.transaction():
db.command("sql", "UPDATE kv SET key = ?, value = ? UPSERT WHERE key = ?", key, value, key)


def get(key):
record = db.lookup_by_key("kv", ["key"], [key])
return None if record is None else record.get("value")


def delete(key):
with db.transaction():
db.command("sql", "DELETE FROM kv WHERE key = ?", key)


put("user:7", "Ada")
put("user:7", "Ada L.")
put("user:9", "Grace")
put("order:1", "x")
print(get("user:7"))
print(get("user:8"))
delete("user:9")
print(get("user:9"))
----

[source,text]
----
Ada L.
None
None
----

The same get as SQL is `SELECT value FROM kv WHERE key = ?`. `EXPLAIN` of it shows `FETCH FROM INDEX kv[key]`.

== Scan by prefix

Keys are kept in order in the index, so a prefix is the range from the prefix up to the prefix with its last character raised by one. The query uses the index for the range:

[source,python]
----
def scan(prefix, limit=100):
upper = prefix[:-1] + chr(ord(prefix[-1]) + 1)
rows = db.query(
"sql",
f"SELECT key, value FROM kv WHERE key >= ? AND key < ? ORDER BY key LIMIT {int(limit)}",
prefix,
upper,
)
return [(row.get("key"), row.get("value")) for row in rows]


put("user:9", "Grace")
print(scan("user:"))
print(scan("order:"))
----

[source,text]
----
[('user:7', 'Ada L.'), ('user:9', 'Grace')]
[('order:1', 'x')]
----

== Make a commit survive a power loss

With the default `arcadedb.txWalFlush` of `0` the engine does not flush its write-ahead log at commit. The key-value store above then survives a crash of the process, and can lose the last commits in a power loss. Level `1` flushes the data of the log at every commit and `2` flushes the file metadata too (see xref:how-to/durability.adoc[Durability settings] for what each level documents).

[WARNING]
====
`ALTER DATABASE` with `arcadedb.txWalFlush` changes what the database stores and what `schema:database` reports, at once. It does not change the commits of the open database. In a run on both builds, 300 commits after `ALTER DATABASE` on the open database made 0 or 1 `fdatasync` calls, while the setting read back as `1`. A read-back is not proof that the setting is active.

Take one of these routes, and check it as shown below:

* Close the database and open it again after the `ALTER DATABASE`.
* Or set the process default before the engine starts: `ARCADEDB_JVM_ARGS="-Darcadedb.txWalFlush=1"` for `{jvm-pkg-name}`, and `ARCADEDB_NATIVE_ISOLATE_ARGS="-Darcadedb.txWalFlush=1"` for `arcadedb`.
* Or call `db.set_wal_flush("yes_nometadata")` on the open database after every open.
====

The first route in code. The setting is stored with the database, so the database that is opened again follows it:

[source,python]
----
import arcadedb

db.command("sql", "ALTER DATABASE `arcadedb.txWalFlush` 1")
path = db.get_database_path()
db.close()
db = arcadedb.open_database(path)
row = db.query("sql", "SELECT settings FROM schema:database").first()
print(next(s["value"] for s in row.get("settings") if s["key"] == "arcadedb.txWalFlush"))
print(get("user:7"))
----

[source,text]
----
1
Ada L.
----

[[flush-check]]
== Check that every commit syncs

Count the sync calls of the process with `strace` (Linux). With the setting active, each commit makes about one `fdatasync` call (level `1`) or `fsync` call (level `2`). Run a script that makes 300 commits like the `put` above, on a database on a real disk (a `tmpfs` accepts the calls and does nothing with them, but the counts are still right):

[source,shell]
----
strace -f -c -e trace=fsync,fdatasync -o counts.txt python kv_check.py
grep -E "fdatasync|fsync" counts.txt
----

Counts of 300 commits on 26.11.1.post4, the same on `arcadedb` and `arcadedb-jvm`. The other `fsync` calls (17 to 22 in these runs) come from creating the database and the index:

[cols="3,1"]
|===
| How the setting was made | `fdatasync` calls

| Default (`0`)
| 0

| `ALTER DATABASE` on the open database
| 0 (one run: 1)

| `ALTER DATABASE`, then close and open again
| 302 (another run: 304)

| `db.set_wal_flush("yes_nometadata")`
| 300

| `ARCADEDB_JVM_ARGS` or `ARCADEDB_NATIVE_ISOLATE_ARGS` set to `-Darcadedb.txWalFlush=1`
| 305
|===

A count near the number of commits means that every commit waited for the disk. A count near zero means it did not, whatever `schema:database` says. With a synced commit a write costs a disk flush, so on a hard disk or a network volume expect each commit to take milliseconds, and measure it on your storage.

What the async executor and `GraphBatch` do with these settings is on xref:how-to/durability.adoc[Durability settings].
73 changes: 73 additions & 0 deletions tests/test_docs_key_value_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Every Python block of the Antora page ``docs/modules/ROOT/pages/how-to/key-value.adoc`` runs, and prints what the page says.

Same pattern as ``test_docs_durability_page.py``: the blocks are chained on purpose, they run in the order of the page, in one
namespace, against one fresh temporary database that the namespace holds as ``db``. A block that is followed by a
``[source,text]`` block must print exactly that text. One block closes the database and opens it again, so the test closes
whatever ``db`` is at the end. The test uses no Java object, so it runs on the JVM build and the native build alike. The sync
counts on the page come from ``strace`` and are not checked here.
"""

import contextlib
import io
import re
from pathlib import Path

PAGE = (
Path(__file__).resolve().parents[1]
/ "docs"
/ "modules"
/ "ROOT"
/ "pages"
/ "how-to"
/ "key-value.adoc"
)

# a Python listing, then (optionally, directly after it) the text listing with its output
BLOCK_RE = re.compile(
r"\[source,python[^\]\n]*\]\n----\n(?P<code>.*?)\n----\n"
r"(?:\n\[source,text\]\n----\n(?P<out>.*?)\n----\n)?",
re.DOTALL,
)


def _blocks():
text = PAGE.read_text(encoding="utf-8")
found = [(m.group("code"), m.group("out")) for m in BLOCK_RE.finditer(text)]
# no Python listing may escape the extraction (a different spelling of the block header would run nowhere)
assert text.count("[source,python") == len(found)
return found


def test_the_page_has_its_blocks():
blocks = _blocks()
assert len(blocks) == 4
assert sum(1 for _, out in blocks if out is not None) == 3


def test_the_page_keeps_its_rules():
text = PAGE.read_text(encoding="utf-8")
assert "pip install" not in text
assert "arcadedb-" "embedded" not in text
assert "—" not in text


def test_every_block_runs_in_order_and_prints_what_the_page_says(temp_db):
namespace = {"db": temp_db, "__name__": "key_value_page"}
try:
for number, (code, expected) in enumerate(_blocks(), start=1):
captured = io.StringIO()
compiled = compile(code, f"key-value.adoc python block {number}", "exec")
with contextlib.redirect_stdout(captured):
exec(compiled, namespace) # nosec B102 - the page of this repository
if expected is not None:
assert (
captured.getvalue().strip() == expected.strip()
), f"block {number} printed other text than the page shows:\n{code}"
else:
assert (
captured.getvalue() == ""
), f"block {number} prints, the page shows no output"
finally:
reopened = namespace["db"]
if reopened is not temp_db and reopened.is_open():
reopened.close()
Loading