Transactions

This page covers what the Python bindings add to transactions: the context manager, the explicit calls, and what each does when something goes wrong. A transaction is a transaction of the engine, so what it guarantees (atomicity, isolation levels, when two writers conflict) belongs to the main manual: Transactions.

A transaction is not a Python object that you pass around. It belongs to the thread that began it, and every call of that thread on the database, db.command(…​) and db.query(…​) included, runs in it. The statements stay SQL or openCypher, as on Databases and queries.

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_transactions_page.py). Each block that prints something is followed by its output. Every block assumes that db is an open database. The first block creates a type with a unique index, which later blocks use to make a statement fail.

from arcadedb import ArcadeDBError

db.command("sql", "CREATE DOCUMENT TYPE Account")
db.command("sql", "CREATE PROPERTY Account.name STRING")
db.command("sql", "CREATE INDEX ON Account (name) UNIQUE")


def names():
    rows = db.query("sql", "SELECT name FROM Account ORDER BY name").to_list()
    return [row["name"] for row in rows]

The context manager

with db.transaction(): begins a transaction, commits it when the block ends, and rolls it back when an exception leaves the block. The exception is raised again unchanged, so your own except clause sees the error you raised, not a wrapper.

with db.transaction():
    db.command("sql", "INSERT INTO Account SET name = 'alice'")
print(names())

try:
    with db.transaction():
        db.command("sql", "INSERT INTO Account SET name = 'bob'")
        raise ValueError("stop")
except ValueError as error:
    print("raised", error)
print(names(), db.is_transaction_active())
['alice']
raised stop
['alice'] False

db.is_transaction_active() is True inside the block and False after it. A write outside a transaction commits on its own; see Outside a transaction.

begin, commit and rollback

db.begin(), db.commit() and db.rollback() do the same by hand. Use them when the start and the end of the transaction are not in one block, and put the rollback in a finally or an except clause, because nothing rolls back for you.

db.begin()
db.command("sql", "INSERT INTO Account SET name = 'bob'")
print(db.is_transaction_active())
db.rollback()
print(names())

db.begin()
db.command("sql", "INSERT INTO Account SET name = 'bob'")
db.commit()
print(names())
True
['alice']
['alice', 'bob']

Outside a transaction

A statement outside a transaction runs in a transaction of its own and commits when the statement ends, as in DuckDB, LadybugDB and asyncpg. This is auto-transaction, and it is on by default. db.is_transaction_active() is False before and after the statement, and every thread sees the rows at once.

db.command("sql", "INSERT INTO Account SET name = 'carol'")
print(names(), db.is_transaction_active(), db.is_auto_transaction())
['alice', 'bob', 'carol'] False True

A statement that fails leaves nothing behind. This one writes dora once, and then the unique index refuses the second dora. The first dora is gone with it.

try:
    db.command("sql", "INSERT INTO Account (name) VALUES ('dora'), ('dora')")
except ArcadeDBError as error:
    print("refused:", "DuplicatedKeyException" in str(error))
print(names())
refused: True
['alice', 'bob', 'carol']

A transaction that you open is yours: nothing in it commits until you commit, also with auto-transaction on. commit() with no transaction active raises ArcadeDBError with "Transaction not begun" in the message, in both modes. rollback() with nothing to roll back does nothing and raises nothing.

try:
    db.commit()
except ArcadeDBError as error:
    print("commit:", "Transaction not begun" in str(error))
db.rollback()
print("rollback: no error")
commit: True
rollback: no error

The same holds for the context manager. If the block calls db.commit() itself, no transaction is left when the block ends, and the commit at the end raises ArcadeDBError ("Transaction not begun"). The rows of the first commit stay. Leave the commit to the with statement.

Four things follow from the fact that every statement commits alone:

  • Statements that must succeed or fail together are one unit only inside a transaction. Without one, each statement commits on its own, and a failure in the third leaves the first two committed.

  • A script that you send with db.command("sqlscript", …​) commits each of its statements alone, unless the script has its own BEGIN and COMMIT. With them it commits or rolls back as one.

  • A transaction belongs to the thread that began it. A thread without one commits its writes alone, also while another thread has a transaction open, and a rollback in the other thread does not take them back.

  • insert_many and graph_batch open and commit their own transactions, as before, and the setting changes nothing for them. What the other bulk loads do inside a transaction of yours is on Bulk loads and commit size.

Schema statements such as CREATE TYPE apply at once and need no transaction, as on Quickstart.

Strict mode

db.set_auto_transaction(False) is the strict mode: a write outside a transaction raises ArcadeDBError with "Transaction not begun" in the message, and writes nothing. Use it when you want the engine to refuse every write that is not in a transaction of yours. db.is_auto_transaction() tells which mode a database is in. The setting is not stored: a database that you open starts with auto-transaction on, whatever an earlier run set.

db.set_auto_transaction(False)
try:
    db.command("sql", "INSERT INTO Account SET name = 'zed'")
except ArcadeDBError as error:
    print("write:", "Transaction not begun" in str(error))
print(names(), db.is_auto_transaction())
db.set_auto_transaction(True)
print(db.is_auto_transaction())
write: True
['alice', 'bob', 'carol'] False
True

What a commit costs

Every commit is work: the engine writes the changes to its write-ahead log (WAL), and with a WAL flush level of yes_nometadata or yes_full it waits for the disk (see Durability settings). A loop of single writes pays that price once for every row, with auto-transaction on and also when you wrote with db.transaction(): around each statement. One transaction around the loop pays it once. This is the one place where the default can be slow.

The table is a set of measurements on one laptop: Python 3.12, the Linux x86-64 wheels built from main on 24 November 2026, a fresh database in a directory on disk for each run, one INSERT with three parameters for each row, 5 repeats, and the median of the repeats. The laptop was hot and had other work running, so read the figures as an order of magnitude and run your own. The bare writes and the with db.transaction(): around each row ran at the same rate in every row of the table (within 10 percent), so the cost is the commit, not the setting.

WAL flush and rows Package One transaction, rows per second Bare writes, rows per second Ratio

default (set_wal_flush("no")), 10,000 rows

arcadedb-jvm

122,000

46,000

2.7

default (set_wal_flush("no")), 10,000 rows

arcadedb

105,000

23,200

4.5

set_wal_flush("yes_nometadata"), 2,000 rows

arcadedb-jvm

110,000

194

566

set_wal_flush("yes_nometadata"), 2,000 rows

arcadedb

60,700

183

331

set_wal_flush("yes_full"), 500 rows

arcadedb-jvm

45,500

174

262

set_wal_flush("yes_full"), 500 rows

arcadedb

39,600

190

209

With the default WAL level, a bare write is 3 to 5 times slower than a row in one transaction. With a flush level that waits for the disk, one commit took about 5 milliseconds on this laptop, so a loop of bare writes ran at 170 to 190 rows per second against tens of thousands of rows per second in one transaction. Put a loop of writes in one transaction, or use insert_many for documents and graph_batch for vertices and edges (see Bulk loads and commit size):

db.command("sql", "CREATE DOCUMENT TYPE Note")
with db.transaction():
    for number in range(3):
        db.command("sql", "INSERT INTO Note SET number = ?", number)
print(db.query("sql", "SELECT count(*) AS total FROM Note").first().get("total"))
3

What a transaction costs on the native build

On the arcadedb (native) package, begin(), commit(), rollback(), the block with db.transaction(): and db.is_transaction_active() each make a call into the library, and the library answers with the state of the transaction. From 26.11.1.post3 it answers with that state as one number. Before, it answered with a JSON text that the bindings copied, freed and decoded. What a transaction does, and what an error does to it, are the same as before. The arcadedb-jvm package does not change.

The table is one laptop study of the arcadedb (native) package: the time for each operation of the 26.11.1.post3 wheel against the 26.11.1.post2 wheel, with 20,000 operations in each run. The ratio is the median of the pair ratios (below 1 means less time) with its 95% interval. Auto-transaction was off in all three rows, which was the default then. The setup was Python 3.12, one fresh process for each run, the two builds alternated in both orders (ABBA), the first round dropped, 20 clean pairs for each figure, and an A/A control (the post2 wheel twice) whose median ratio was between 0.97 and 1.03 in every row. The figures come from one Linux x86_64 laptop with two cores for the process. The post3 wheels were the ones that CI built from the tagged commit. The wheels on PyPI were checked for the same engine as 26.11.1 and were not timed again.

What was timed Ratio, post3 over post2 (95% interval) Clean pairs

with db.transaction(): pass, one begin and one commit with an empty body

0.370 [0.368, 0.374]

20

with db.transaction(): around one INSERT through db.command

0.875 [0.873, 0.878]

20

set() and save() of one saved vertex, in transactions of 1,000 records

0.932 [0.928, 0.935]

20

In the third row each save() asks once for the transaction state, because auto-transaction was off. With auto-transaction on, which is the default from 26.12.1, it no longer asks (see Record ids in rows). The study did not time that case, so this page gives no speed for it. The study claims no gain in memory.

What a transaction sees

A transaction sees its own rows at once. Another thread sees them only after the commit. This block starts a thread for each count:

import threading


def count_in_other_thread():
    seen = []

    def read():
        seen.append(len(db.query("sql", "SELECT FROM Account").to_list()))

    thread = threading.Thread(target=read)
    thread.start()
    thread.join()
    return seen[0]


with db.transaction():
    db.command("sql", "INSERT INTO Account SET name = 'dave'")
    print("this thread:", len(names()), "other thread:", count_in_other_thread())
print("after the commit, other thread:", count_in_other_thread())
this thread: 4 other thread: 3
after the commit, other thread: 4

Share one Database between threads, as on Concurrency, processes and crashes. That page also covers what happens when two transactions change the same record.

A failed statement inside a transaction

A statement that fails inside your transaction is undone on its own, and the transaction goes on. This is the behavior of ArcadeDB 26.11.1 and later. Before it, a statement that had written part of its rows left them in the transaction, and the transaction could no longer be committed.

with db.transaction():
    db.command("sql", "INSERT INTO Account SET name = 'erin'")
    try:
        db.command("sql", "INSERT INTO Account (name) VALUES ('frank'), ('frank')")
    except ArcadeDBError as error:
        print("refused:", "DuplicatedKeyException" in str(error))
    print("still active:", db.is_transaction_active())
    db.command("sql", "INSERT INTO Account SET name = 'grace'")
print(names())
refused: True
still active: True
['alice', 'bob', 'carol', 'dave', 'erin', 'grace']

The second statement writes frank once, and then the unique index refuses the second frank. The first frank is gone with it, while erin from the statement before and grace from the statement after are committed. The engine keeps a journal of what each statement changes in order to undo it. When a statement changes more entries than arcadedb.txStatementSavepointMaxEntries (100,000 by default), the engine does not undo it, and the transaction can no longer be committed: roll it back. The setting is listed in the main manual: Settings.

A failed statement is one thing, and an exception that you let leave the with block is another: that one rolls the whole transaction back, as above. A Python function or a record event callback that raises fails its statement the same way, see Python functions and record events.

A second begin

db.begin() while a transaction is active does not join it. It opens a nested transaction of its own, and the next commit() or rollback() ends that nested one only. The two do not share their uncommitted rows:

  • The nested transaction does not see the rows that the outer one has not committed.

  • Committing the nested transaction makes its rows durable at once. A later rollback of the outer transaction does not take them back.

  • The outer transaction sees what the nested one committed, because it is committed data.

db.begin()
db.command("sql", "INSERT INTO Account SET name = 'outer'")
db.begin()
print("nested sees outer:", "outer" in names())
db.command("sql", "INSERT INTO Account SET name = 'inner'")
db.commit()
print("still active:", db.is_transaction_active())
db.rollback()
print("outer kept:", "outer" in names(), "inner kept:", "inner" in names())
nested sees outer: False
still active: True
outer kept: False inner kept: True

Nested with db.transaction(): blocks behave the same way, one transaction for each block. An exception in the inner block rolls back the inner one, and if you catch it inside the outer block, the outer transaction goes on. Because the nested transaction commits on its own, it is not a way to make one part of the work undoable: use one transaction for work that has to succeed or fail together.

run_in_transaction

db.run_in_transaction(fn, retries=12, backoff_s=0.005) calls fn in a transaction, commits, and returns what fn returned. When fn or the commit loses a conflict with another writer, it rolls back and calls fn again, up to retries more times, with a wait that grows by backoff_s each time. fn takes no arguments and must do all of its reading and writing itself, so that a repeat starts from the committed state. The loop, and what it cannot repeat, are on Concurrency, processes and crashes.

def add_account():
    db.command("sql", "INSERT INTO Account SET name = 'heidi'")
    return "added"


print(db.run_in_transaction(add_account))
added

GraphBatch inside a transaction

GraphBatch (db.graph_batch()) manages its own transactions. From engine 26.10.1 on, its create_vertices, flush and close, and new_edge and new_edges when the buffer is full, refuse to run inside a transaction that you opened. They raise ArcadeDBError and leave your transaction as it was. Engines before 26.10.1 committed your transaction instead. Commit or roll back your own work, then call the batch. The commit sizes of a batch are on Bulk loads and commit size. What a batch does with the durability settings of the database is on Durability settings.

db.command("sql", "CREATE VERTEX TYPE City")
with db.graph_batch(parallel_flush=False) as batch:
    db.begin()
    try:
        batch.create_vertices("City", 2)
    except ArcadeDBError:
        print("refused, transaction still active:", db.is_transaction_active())
    db.rollback()
refused, transaction still active: True