From ac01e447d481f22d640be097f9253e0e21fd38f6 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Wed, 25 Nov 2026 00:48:51 +0900 Subject: [PATCH 1/2] A write outside a transaction commits on its own: auto-transaction is the default (closes #478) Every database that the bindings hand out (create_database, open_database, DatabaseFactory and the database of an embedded server, JVM and native) now has the engine flag autoTransaction on. set_auto_transaction(False) is the strict mode that raised "Transaction not begun"; is_auto_transaction() reads the flag. Why: of 23 Python database libraries that were run or read, none raises on a bare write (15 commit at once, 7 open a transaction on the first statement, LMDB has no write outside a transaction). The first write of the quickstart failed. Every bare write raised before, so no working program changes. Checked on both builds: begin() is not committed for you, nested blocks, a failed statement (whole statement undone), SQLScript with and without BEGIN, query(), save() and delete(), insert_many and graph_batch (ratio on/off 0.97 to 1.01 over 11 interleaved pairs, control 0.98 to 1.04), threads, the asyncio facade, a read-only database, the embedded server. Tests that asserted the strict default now set strict mode (9 tests); three more were found only by the full run (two graph_batch rollback tests and a callback test that used the bare-write error as proof that no transaction was left open). New tests in tests/test_auto_transaction_default.py. The cost is a loop of single writes: one commit per row, the same as a transaction around each row. Numbers and the way out are on the transactions page. --- README.md | 7 +- docs/modules/ROOT/pages/how-to/asyncio.adoc | 2 +- .../ROOT/pages/how-to/concurrency.adoc | 2 +- .../ROOT/pages/how-to/transactions.adoc | 134 ++++++++- .../ROOT/pages/how-to/values-and-records.adoc | 2 +- docs/modules/ROOT/pages/quickstart.adoc | 55 ++-- src/arcadedb/_native/database.py | 33 ++- src/arcadedb/_native/records.py | 12 +- src/arcadedb/_native/server.py | 4 +- src/arcadedb/aio.py | 4 +- src/arcadedb/core.py | 42 ++- src/arcadedb/server.py | 4 +- tests/test_auto_transaction_default.py | 269 ++++++++++++++++++ tests/test_graph_api.py | 7 +- tests/test_graph_batch.py | 9 + tests/test_native_one_row_crossings.py | 15 +- tests/test_python_callbacks.py | 12 +- tests/test_transactions_behavior.py | 34 ++- tests/test_values_and_records_behavior.py | 3 +- 19 files changed, 568 insertions(+), 82 deletions(-) create mode 100644 tests/test_auto_transaction_default.py diff --git a/README.md b/README.md index c4db43d2..d7dff3e3 100644 --- a/README.md +++ b/README.md @@ -63,15 +63,14 @@ with arcadedb.create_database("./mydb") as db: db.command("sql", "CREATE PROPERTY Person.name STRING") db.command("sql", "CREATE PROPERTY Person.age INTEGER") - # Writes need a transaction - with db.transaction(): - db.command("sql", "INSERT INTO Person SET name = ?, age = ?", "Alice", 30) + # A statement outside a transaction commits by itself + db.command("sql", "INSERT INTO Person SET name = ?, age = ?", "Alice", 30) for record in db.query("sql", "SELECT FROM Person WHERE age > 25"): print(f"Name: {record.get('name')}") ``` -This prints `Name: Alice` (the engine also logs to standard error). `create_database` raises if the path already holds a database, so run it in an empty directory, or call `open_or_create_database` to open the database when it exists and create it when it does not. Everything else goes through the same two calls, `db.command(...)` and `db.query(...)`, in SQL or openCypher. +This prints `Name: Alice` (the engine also logs to standard error). `create_database` raises if the path already holds a database, so run it in an empty directory, or call `open_or_create_database` to open the database when it exists and create it when it does not. Everything else goes through the same two calls, `db.command(...)` and `db.query(...)`, in SQL or openCypher. Statements that belong together go in `with db.transaction():`, which commits them as one and is much faster for many rows ([Transactions](https://docs.arcadedb.com/arcadedb-python/how-to/transactions.html)). ## What is included diff --git a/docs/modules/ROOT/pages/how-to/asyncio.adoc b/docs/modules/ROOT/pages/how-to/asyncio.adoc index 11076141..57e5fffa 100644 --- a/docs/modules/ROOT/pages/how-to/asyncio.adoc +++ b/docs/modules/ROOT/pages/how-to/asyncio.adoc @@ -47,7 +47,7 @@ asyncio.run(main()) ['hello'] ---- -Parameters bind as in `db.query`: positional `?` from the extra arguments, or by name from one `dict`. `command` returns a list of `dict` as well, or `None` when the engine returns no result set. An `INSERT`, `UPDATE` or `DELETE` through `command` needs a transaction, so send it through `run_in_transaction`, or switch on `db.set_auto_transaction(True)`, which commits each statement on its own (see xref:how-to/transactions.adoc#auto-transaction[Transactions]). Do not send `BEGIN` or `COMMIT` through `command`: the next call can run on another worker, where that transaction is not open. +Parameters bind as in `db.query`: positional `?` from the extra arguments, or by name from one `dict`. `command` returns a list of `dict` as well, or `None` when the engine returns no result set. An `INSERT`, `UPDATE` or `DELETE` through `command` commits on its own, as auto-transaction is on by default. A transaction cannot span awaits, so statements that belong together go through `run_in_transaction` (see xref:how-to/transactions.adoc#outside[Transactions]). Do not send `BEGIN` or `COMMIT` through `command`: the next call can run on another worker, where that transaction is not open. == Many tasks at once diff --git a/docs/modules/ROOT/pages/how-to/concurrency.adoc b/docs/modules/ROOT/pages/how-to/concurrency.adoc index 3108dff1..706aa75b 100644 --- a/docs/modules/ROOT/pages/how-to/concurrency.adoc +++ b/docs/modules/ROOT/pages/how-to/concurrency.adoc @@ -128,7 +128,7 @@ db.run_in_transaction( The engine keeps no record version, so the native build compares values. Inside the transaction of the update, `save()` reads the stored record and compares it with the values the object held as read. A record that differs is a lost update. A record that another transaction changed and then changed back is not detected. A `save()` of a new record has nothing to compare and is not checked. A second `save()` of the same object does not conflict with the first, because after a successful save the object holds the values it wrote. -`save()` of an existing record is a write, so it needs an open transaction on both builds (`with db.transaction():`, or `begin()`). Outside one it raises `ArcadeDBError` ("Transaction not begun"). To retry after a conflict, read the record again and repeat the change in a new transaction: `db.run_in_transaction(fn, retries=...)` does this when `fn` does the lookup, `modify()`, `set()` and `save()` itself. A retry that reuses the old object fails again, because the object still holds the old values. +`save()` of an existing record is a write. Outside a transaction it commits on its own, as every write does by default. The stale-record check and the write of a `save()` belong together only inside a transaction (`with db.transaction():`, or `begin()`), so put the `save()` in one when another writer may change the record. With `db.set_auto_transaction(False)`, the strict mode, `save()` outside a transaction raises `ArcadeDBError` ("Transaction not begun"). To retry after a conflict, read the record again and repeat the change in a new transaction: `db.run_in_transaction(fn, retries=...)` does this when `fn` does the lookup, `modify()`, `set()` and `save()` itself. A retry that reuses the old object fails again, because the object still holds the old values. [source,python] ---- diff --git a/docs/modules/ROOT/pages/how-to/transactions.adoc b/docs/modules/ROOT/pages/how-to/transactions.adoc index 23980976..1ef1a220 100644 --- a/docs/modules/ROOT/pages/how-to/transactions.adoc +++ b/docs/modules/ROOT/pages/how-to/transactions.adoc @@ -1,7 +1,7 @@ = Transactions -:description: Commit and roll back with the context manager or with begin, commit and rollback, what an exception, a failed statement and a second begin do, what other threads see before a commit, auto-transaction, what a transaction costs on the native build, run_in_transaction, and the GraphBatch rule. +:description: What a write outside a transaction does (it commits on its own), the context manager, begin, commit and rollback, what an exception, a failed statement and a second begin do, what other threads see before a commit, strict mode, what a commit costs, run_in_transaction, and the GraphBatch rule. -// Sources: src/arcadedb/core.py (begin, commit, rollback, transaction, run_in_transaction, set_auto_transaction), transactions.py and graph_batch.py. Every statement below is pinned by tests/test_transactions_behavior.py. +// Sources: src/arcadedb/core.py (begin, commit, rollback, transaction, run_in_transaction, set_auto_transaction), transactions.py and graph_batch.py. Every statement below is pinned by tests/test_transactions_behavior.py and tests/test_auto_transaction_default.py. 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: {arcadedb-docs-url}/concepts/transactions[Transactions]. @@ -49,7 +49,7 @@ raised stop ['alice'] False ---- -`db.is_transaction_active()` is `True` inside the block and `False` after it. A write outside a transaction does not run; see <>. +`db.is_transaction_active()` is `True` inside the block and `False` after it. A write outside a transaction commits on its own; see <>. == begin, commit and rollback @@ -79,14 +79,40 @@ True [[outside]] == Outside a transaction -A write outside a transaction raises `ArcadeDBError` with "Transaction not begun" in the message, and writes nothing. So does `commit()` when no transaction is active. `rollback()` with nothing to roll back does nothing and raises nothing. +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. + +[source,python] +---- +db.command("sql", "INSERT INTO Account SET name = 'carol'") +print(names(), db.is_transaction_active(), db.is_auto_transaction()) +---- + +[source,text] +---- +['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. [source,python] ---- try: - db.command("sql", "INSERT INTO Account SET name = 'carol'") + db.command("sql", "INSERT INTO Account (name) VALUES ('dora'), ('dora')") except ArcadeDBError as error: - print("write:", "Transaction not begun" in str(error)) + print("refused:", "DuplicatedKeyException" in str(error)) +print(names()) +---- + +[source,text] +---- +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. + +[source,python] +---- try: db.commit() except ArcadeDBError as error: @@ -97,37 +123,115 @@ print("rollback: no error") [source,text] ---- -write: True 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 xref:how-to/bulk-loads.adoc[Bulk loads and commit size]. + Schema statements such as `CREATE TYPE` apply at once and need no transaction, as on xref:quickstart.adoc[Quickstart]. -== Auto-transaction +[[strict-mode]] +[[auto-transaction]] +== Strict mode -`db.set_auto_transaction(True)` makes each statement outside a transaction run in a transaction of its own, which commits when the statement ends. It is off by default and is not stored: a reopened database starts with it off. Prefer an explicit transaction when several statements belong together, because with auto-transaction each one commits alone. +`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. [source,python] ---- -db.set_auto_transaction(True) -db.command("sql", "INSERT INTO Account SET name = 'carol'") -print("carol" in names(), db.is_transaction_active()) 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()) +---- + +[source,text] +---- +write: True +['alice', 'bob', 'carol'] False +True +---- + +[[commit-cost]] +== 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 xref:how-to/durability.adoc[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. + +[cols="3,2,2,2,1"] +|=== +| 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 xref:how-to/bulk-loads.adoc[Bulk loads and commit size]): + +[source,python] +---- +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")) ---- [source,text] ---- -True False +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, the default, in all three rows. 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. +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. [cols="5,3,1"] |=== @@ -146,7 +250,7 @@ The table is one laptop study of the `arcadedb` (native) package: the time for e | 20 |=== -In the third row each `save()` asks once for the transaction state, because auto-transaction was off. The study did not time `save()` with auto-transaction on, where it no longer asks (see xref:how-to/databases-and-queries.adoc#record-ids-in-rows[Record ids in rows]), so this page gives no speed for that case. The study claims no gain in memory. +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 xref:how-to/databases-and-queries.adoc#record-ids-in-rows[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 diff --git a/docs/modules/ROOT/pages/how-to/values-and-records.adoc b/docs/modules/ROOT/pages/how-to/values-and-records.adoc index 56c9a0eb..8ffb875e 100644 --- a/docs/modules/ROOT/pages/how-to/values-and-records.adoc +++ b/docs/modules/ROOT/pages/how-to/values-and-records.adoc @@ -239,7 +239,7 @@ A record object is a `Document`, a `Vertex` or an `Edge`. A vertex and an edge a A record has the same readers as a row (`get`, `has_property`, `get_property_names`, `to_dict`), and `to_dict()` holds the properties only. A record also has `get_type_name()`, and `get_rid()` gives its record id. -Creating a record takes three steps: make the object, set its properties, save it. `set()` and `save()` return the record, so they chain. `save()` is a write, so it needs a transaction, as every write does (see xref:how-to/transactions.adoc[Transactions]). The record has its record id after `save()`. `record.delete()` removes a record, also inside a transaction. +Creating a record takes three steps: make the object, set its properties, save it. `set()` and `save()` return the record, so they chain. `save()` is a write: outside a transaction it commits on its own, as every write does, and inside one it joins the transaction (see xref:how-to/transactions.adoc[Transactions]). The record has its record id after `save()`. `record.delete()` removes a record, in a transaction or alone. [source,python] ---- diff --git a/docs/modules/ROOT/pages/quickstart.adoc b/docs/modules/ROOT/pages/quickstart.adoc index 9abf1edc..f22b9b8d 100644 --- a/docs/modules/ROOT/pages/quickstart.adoc +++ b/docs/modules/ROOT/pages/quickstart.adoc @@ -1,5 +1,5 @@ = Quickstart -:description: Create a database, insert records in a transaction and query them with SQL, in about five minutes. +:description: Create a database, insert records and query them with SQL, in about five minutes. // Source: bindings docs getting-started/quickstart.md. @@ -32,7 +32,7 @@ The database runs in your Python process. You use SQL for the schema and for CRU Two rules cover most first mistakes: * Use a `with` block. It closes the database when the block ends, also when an exception leaves it. -* *Writes need a transaction.* `INSERT`, `UPDATE` and `DELETE` go inside `with db.transaction():`. Schema statements apply immediately. Reads need no transaction. What a transaction does on an error, and how to roll back by hand, is on xref:how-to/transactions.adoc[Transactions]. +* *Each write commits by itself.* An `INSERT`, `UPDATE` or `DELETE` outside a transaction runs in a transaction of its own and is committed when the statement ends, as in DuckDB or asyncpg. Statements that must succeed or fail together go inside `with db.transaction():`, and so do many writes in a loop, which run much faster in one transaction. What a transaction does on an error, how to roll back by hand and what a single commit costs are on xref:how-to/transactions.adoc[Transactions]. == A complete example @@ -51,20 +51,19 @@ def main(): db.command("sql", "CREATE PROPERTY Person.email STRING") db.command("sql", "CREATE INDEX ON Person (name) NOTUNIQUE") - # Insert data (in a transaction) - with db.transaction(): - for name, age, email in [ - ("Alice", 30, "alice@example.com"), - ("Bob", 25, "bob@example.com"), - ("Charlie", 35, "charlie@example.com"), - ]: - db.command( - "sql", - "INSERT INTO Person SET name = ?, age = ?, email = ?", - name, - age, - email, - ) + # Insert data (each statement commits by itself) + for name, age, email in [ + ("Alice", 30, "alice@example.com"), + ("Bob", 25, "bob@example.com"), + ("Charlie", 35, "charlie@example.com"), + ]: + db.command( + "sql", + "INSERT INTO Person SET name = ?, age = ?, email = ?", + name, + age, + email, + ) print("Inserted 3 records") # Query all (no transaction needed for reads) @@ -105,12 +104,12 @@ The steps in the script are: . `create_database("./quickstart")` creates the directory and opens a database in it. . Four `CREATE` statements define a document type `Person`, three properties and an index on `name`. -. A transaction inserts three records. The `?` marks are positional parameters bound to the values after the statement. +. Three `INSERT` statements add records, and each one commits by itself. The `?` marks are positional parameters bound to the values after the statement. . `db.query` reads them back, with and without a filter, and `count(*)` counts them. == Reopen the database -Open an existing database with `open_database`. The second part of the script shows what happens when a write runs outside a transaction: +Open an existing database with `open_database`. The second part of the script writes outside a transaction, and then turns auto-transaction off to show the strict mode, where such a write raises: [source,python,subs="attributes+"] ---- @@ -121,10 +120,23 @@ with arcadedb.open_database("./quickstart") as db: result = db.query("sql", "SELECT FROM Person") print(f"Found {len(list(result))} records") -# A write outside a transaction raises +# A write outside a transaction commits by itself with arcadedb.open_database("./quickstart") as db: + db.command("sql", "INSERT INTO Person SET name = 'Dora'") + total = db.query("sql", "SELECT count(*) as total FROM Person").first().get("total") + print("Total people:", total) + +# Several writes as one unit: all commit, or none does +with arcadedb.open_database("./quickstart") as db: + with db.transaction(): + db.command("sql", "INSERT INTO Person SET name = 'Eve'") + db.command("sql", "INSERT INTO Person SET name = 'Frank'") + +# Strict mode: a write outside a transaction raises +with arcadedb.open_database("./quickstart") as db: + db.set_auto_transaction(False) try: - db.command("sql", "INSERT INTO Person SET name = 'Dora'") + db.command("sql", "INSERT INTO Person SET name = 'Grace'") except Exception as e: print(type(e).__name__, e, sep=": ") ---- @@ -132,11 +144,14 @@ with arcadedb.open_database("./quickstart") as db: [source,text] ---- Found 3 records +Total people: 4 TransactionError: [transaction_not_begun] No transaction is open: wrap the write in `with db.transaction():`, or call `db.set_auto_transaction(True)` so that each statement commits on its own. Command failed: com.arcadedb.exception.TransactionException: Transaction not begun ---- The error is a `TransactionError`, a subclass of `ArcadeDBError`. It carries a code (`e.code`) and a hint (`e.hint`) that a program can read, and its text ends with the engine's own message. xref:how-to/errors.adoc[Errors: codes, hints and classes] lists them all. +The strict mode is for code that wants the engine to refuse any write that is not in a transaction of its own. `db.set_auto_transaction(False)` turns it on for one open database. It is not stored, so a database that you open again starts with auto-transaction on. + == Server mode When another process or another language needs the same data, start the bundled server. The process that created it keeps direct embedded access, and other processes reach the same databases over the HTTP API on the port that `get_http_port()` returns: diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index c10b8312..950e410d 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -760,11 +760,29 @@ def __init__(self, handle: int, owned_by_server: bool = False): self._vector_meta: dict = {} self._vector_dimensions: dict = {} self._vector_id_properties: dict = {} - self._auto_transaction = False # the engine default; set_auto_transaction() is the only way it changes + self._auto_transaction = False # the engine's own default; _opened() and set_auto_transaction() are the only ways it changes # statements run through command() on this handle: what columnar.Declared keeps the declared property types against (a schema # change made on this handle is one of them); a query, a transaction call or a bulk crossing does not move it self._command_count = 0 + @classmethod + def _opened(cls, handle: int, owned_by_server: bool = False): + """The handle of a database that was just created or opened, with the default of this package: auto-transaction on. + + The engine's own default is off. Every database that the bindings hand out goes through here, so a write outside a + transaction commits on its own, as on the JVM build. ``set_auto_transaction(False)`` brings the strict mode back. + """ + db = cls(handle, owned_by_server) + try: + db.set_auto_transaction(True) + except BaseException: + try: + db.close() + except Exception: # nosec B110 - the first error is the one to raise + pass + raise + return db + # -- lifecycle def __enter__(self): @@ -1723,12 +1741,21 @@ def is_read_your_writes(self) -> bool: return bool(db_set(self, "read_your_writes")["v"]) def set_auto_transaction(self, enabled: bool): + """On by default: each statement outside a transaction runs in a transaction of its own and commits when it ends. + ``set_auto_transaction(False)`` is the strict mode: a write outside a transaction raises ``ArcadeDBError`` + ("Transaction not begun"). The setting is not persisted: a database that you open starts with it on again. + """ self._check_not_closed() from .extras import db_set db_set(self, "auto_transaction", "true" if enabled else "false") self._auto_transaction = bool(enabled) + def is_auto_transaction(self) -> bool: + """Return whether auto-transaction is on (the default): a write outside a transaction commits on its own.""" + self._check_not_closed() + return self._auto_transaction + def _column_values(name, values): """One ``insert_columns`` column as a list of Python values, with the JPype path's refusals (a dtype that does not @@ -1969,7 +1996,7 @@ def __init__(self, path: str, jvm_kwargs: Optional[dict] = None): self._path = os.fspath(path) def create(self) -> NativeDatabase: - return NativeDatabase( + return NativeDatabase._opened( _call("Failed to create database", "arcadedb_n_open", lib.b(self._path), 0)[ "h" ] @@ -1977,7 +2004,7 @@ def create(self) -> NativeDatabase: def open(self, read_only: bool = False) -> NativeDatabase: mode = 2 if read_only else 1 - return NativeDatabase( + return NativeDatabase._opened( _call( "Failed to open database", "arcadedb_n_open", lib.b(self._path), mode )["h"] diff --git a/src/arcadedb/_native/records.py b/src/arcadedb/_native/records.py index 9bb732d3..e7b7ad8d 100644 --- a/src/arcadedb/_native/records.py +++ b/src/arcadedb/_native/records.py @@ -329,8 +329,9 @@ def save(self): A saved record is written back only if the stored record still has the values this object was read with. Otherwise it raises ArcadeDBError ("ConcurrentModificationException" in the message, retryable by ``run_in_transaction``) and writes nothing: read the record again and repeat the change. The check compares values (the engine keeps no version), so a change that was changed back is - not seen. Saving an existing record needs an active transaction, like every write; outside one it raises ArcadeDBError - ("Transaction not begun"). Creating a new record is not checked. + not seen. Outside a transaction a save commits on its own (auto-transaction is on by default); with ``set_auto_transaction(False)`` it + needs an active transaction, like every write, and outside one it raises ArcadeDBError ("Transaction not begun"). Creating a + new record is not checked. """ self._fill() db = self._db @@ -357,9 +358,10 @@ def _save_update(self, db) -> None: when every changed value is one the engine stores exactly as sent (``_stored_as_sent``) the statement returns no row and the values sent are the new copy; otherwise the statement returns the stored row (RETURN AFTER) and that row is. - Like every write (and like the JVM build), it needs an active transaction while auto-transaction is off, the engine default: - outside one it raises ArcadeDBError ("Transaction not begun") before it reads or writes anything. This method opens no - transaction of its own. With auto-transaction on the check cannot refuse, so the state is not asked for (one crossing less). + Like every write (and like the JVM build), it needs an active transaction while auto-transaction is off, the strict mode + (``set_auto_transaction(False)``): outside one it raises ArcadeDBError ("Transaction not begun") before it reads or writes + anything. This method opens no transaction of its own. With auto-transaction on, the default, the check cannot refuse, so the + state is not asked for (one crossing less). The engine's own refusal cannot stand in for the check with it off: the engine runs the before-update callbacks and the validation before it looks for a transaction, and an UPDATE of a record that is gone raises nothing. """ diff --git a/src/arcadedb/_native/server.py b/src/arcadedb/_native/server.py index f8193fe8..25af9f98 100644 --- a/src/arcadedb/_native/server.py +++ b/src/arcadedb/_native/server.py @@ -72,7 +72,7 @@ def __del__(self): def get_database(self, name: str) -> NativeDatabase: if not self._started: raise ArcadeDBError("Server is not started") - return NativeDatabase( + return NativeDatabase._opened( _call( f"Failed to get database '{name}'", "arcadedb_n_server_db", @@ -86,7 +86,7 @@ def get_database(self, name: str) -> NativeDatabase: def create_database(self, name: str) -> NativeDatabase: if not self._started: raise ArcadeDBError("Server is not started") - return NativeDatabase( + return NativeDatabase._opened( _call( f"Failed to create database '{name}'", "arcadedb_n_server_db", diff --git a/src/arcadedb/aio.py b/src/arcadedb/aio.py index 04893a00..d619aa5e 100644 --- a/src/arcadedb/aio.py +++ b/src/arcadedb/aio.py @@ -116,8 +116,8 @@ async def command( """``db.command(language, command, *args)``, with the rows read on the worker: a list of ``dict``, or ``None`` when the engine returns no result set. - An ``INSERT``, ``UPDATE`` or ``DELETE`` needs a transaction, and a transaction cannot span awaits: put writes in - :meth:`run_in_transaction`, or switch on ``db.set_auto_transaction(True)``. Do not send ``BEGIN`` or ``COMMIT`` through this + An ``INSERT``, ``UPDATE`` or ``DELETE`` commits on its own (auto-transaction is on by default), and a transaction cannot span + awaits: put statements that belong together in :meth:`run_in_transaction`. Do not send ``BEGIN`` or ``COMMIT`` through this method: the next call may run on another worker. """ return await self.run(self._command, language, command, *args) diff --git a/src/arcadedb/core.py b/src/arcadedb/core.py index cb599d7f..ceb67d32 100644 --- a/src/arcadedb/core.py +++ b/src/arcadedb/core.py @@ -516,6 +516,18 @@ def __init__(self, java_database: Any): self._async_executors: List[Any] = [] self._functions = FunctionRegistration(self) + @classmethod + def _opened(cls, java_database: Any) -> "Database": + """The handle of a database that was just created or opened, with the default of this package: auto-transaction on. + + The engine's own default is off. Every database that the bindings hand out (``create_database``, ``open_database``, + ``DatabaseFactory`` and the database of an embedded server) goes through here, so a write outside a transaction commits + on its own, as in DuckDB or asyncpg. ``set_auto_transaction(False)`` brings the strict mode back. + """ + db = cls(java_database) + java_database.setAutoTransaction(True) + return db + def __enter__(self) -> "Database": return self @@ -2208,19 +2220,21 @@ def set_auto_transaction(self, enabled: bool) -> None: """ Enable or disable automatic transaction management. - Off by default: a write outside a transaction raises ``ArcadeDBError`` - ("Transaction not begun"), so wrap writes in ``with db.transaction():`` - or call begin() yourself. When enabled, each statement outside a - transaction runs in its own committed transaction. The setting is not - persisted: a reopened database starts with it off again. + On by default: each statement outside a transaction runs in a + transaction of its own and commits when the statement ends. A + transaction that you open with ``begin()`` or ``with db.transaction():`` + is never committed for you. ``set_auto_transaction(False)`` is the + strict mode: a write outside a transaction raises ``ArcadeDBError`` + ("Transaction not begun"), so every write has to sit in a transaction + of yours. The setting is not persisted: a database that you open + starts with it on again. Args: enabled: True to enable auto-transaction, False to disable Example: - >>> db.set_auto_transaction(True) # each bare write commits alone - >>> db.command("sql", "INSERT INTO T SET a = 1") - >>> db.set_auto_transaction(False) # back to the default + >>> db.command("sql", "INSERT INTO T SET a = 1") # commits alone + >>> db.set_auto_transaction(False) # strict mode: writes need a transaction """ self._check_not_closed() try: @@ -2228,6 +2242,14 @@ def set_auto_transaction(self, enabled: bool) -> None: except Exception as e: raise ArcadeDBError(f"Failed to set auto-transaction: {e}") from e + def is_auto_transaction(self) -> bool: + """Return whether auto-transaction is on (the default): a write outside a transaction commits on its own.""" + self._check_not_closed() + try: + return bool(self._java_db.isAutoTransaction()) + except Exception as e: + raise ArcadeDBError(f"Failed to get auto-transaction: {e}") from e + def register_function( self, name: str, @@ -2792,7 +2814,7 @@ def create(self) -> Database: """Create a new database.""" try: java_db = self._java_factory.create() - return Database(java_db) + return Database._opened(java_db) except Exception as e: raise ArcadeDBError(f"Failed to create database: {e}") from e @@ -2814,7 +2836,7 @@ def open(self, read_only: bool = False) -> Database: java_db = self._java_factory.open(mode) else: java_db = self._java_factory.open() - return Database(java_db) + return Database._opened(java_db) except Exception as e: raise ArcadeDBError(f"Failed to open database: {e}") from e diff --git a/src/arcadedb/server.py b/src/arcadedb/server.py index 24cbe918..40e7880c 100644 --- a/src/arcadedb/server.py +++ b/src/arcadedb/server.py @@ -250,7 +250,7 @@ def get_database(self, name: str) -> Database: try: java_db = self._java_server.getDatabase(name) - return Database(java_db) + return Database._opened(java_db) except Exception as e: raise ArcadeDBError(f"Failed to get database '{name}': {e}") from e @@ -274,7 +274,7 @@ def create_database(self, name: str) -> Database: # Use server's getDatabase with createIfNotExists=True # This properly registers the database with the server java_db = self._java_server.getDatabase(name, True, True) - return Database(java_db) + return Database._opened(java_db) except Exception as e: raise ArcadeDBError(f"Failed to create database '{name}': {e}") from e diff --git a/tests/test_auto_transaction_default.py b/tests/test_auto_transaction_default.py new file mode 100644 index 00000000..05d8cf08 --- /dev/null +++ b/tests/test_auto_transaction_default.py @@ -0,0 +1,269 @@ +"""A write outside a transaction commits on its own: the default of both packages, and the strict mode that turns it off. + +The edge cases of flipping the default are pinned one by one: an explicit ``begin()`` must not autocommit, nested blocks, a failed +statement, a script, a query, ``save()`` and ``delete()``, the batch calls, another thread, the embedded server, a read-only +database, and the asyncio facade. The tests use SQL and the record API only, so they run on the JVM build and the native build +alike (ArcadeData/arcadedb-python, the transactions page ``docs/modules/ROOT/pages/how-to/transactions.adoc``). +""" + +import asyncio +import threading + +import pytest + +import arcadedb +from arcadedb import ArcadeDBError +from arcadedb.aio import AsyncDatabase +from tests.conftest import TEST_PASSWORD, free_port + + +@pytest.fixture +def db(temp_db): + temp_db.command("sql", "CREATE DOCUMENT TYPE T") + temp_db.command("sql", "CREATE PROPERTY T.k INTEGER") + temp_db.command("sql", "CREATE INDEX ON T (k) UNIQUE") + return temp_db + + +def _keys(db): + return sorted(r["k"] for r in db.query("sql", "SELECT k FROM T").to_list()) + + +def _insert(db, k): + db.command("sql", "INSERT INTO T SET k = ?", k) + + +def test_a_database_that_was_just_created_has_auto_transaction_on(temp_db): + assert temp_db.is_auto_transaction() is True + + +def test_a_database_that_was_opened_again_has_it_on_whatever_the_last_run_set( + temp_db_path, +): + with arcadedb.create_database(temp_db_path) as db: + db.set_auto_transaction(False) + with arcadedb.open_database(temp_db_path) as db: + assert db.is_auto_transaction() is True + db.command("sql", "CREATE DOCUMENT TYPE T") + db.command("sql", "INSERT INTO T SET k = 1") + assert db.is_transaction_active() is False + assert db.query("sql", "SELECT count(*) AS n FROM T").first().get("n") == 1 + + +def test_a_read_only_database_still_refuses_a_write_and_says_why(temp_db_path): + with arcadedb.create_database(temp_db_path) as db: + db.command("sql", "CREATE DOCUMENT TYPE T") + with arcadedb.open_database(temp_db_path, read_only=True) as db: + with pytest.raises(ArcadeDBError) as caught: + db.command("sql", "INSERT INTO T SET k = 1") + assert "Transaction not begun" not in str(caught.value) + assert db.query("sql", "SELECT count(*) AS n FROM T").first().get("n") == 0 + + +def test_a_bare_write_commits_at_once_and_leaves_no_transaction(db): + _insert(db, 1) + assert db.is_transaction_active() is False + assert _keys(db) == [1] + seen = [] + thread = threading.Thread(target=lambda: seen.append(_keys(db))) + thread.start() + thread.join() + assert seen == [[1]] + + +def test_an_explicit_begin_is_not_committed_for_you(db): + db.begin() + _insert(db, 1) + _insert(db, 2) + assert db.is_transaction_active() is True + db.rollback() + assert _keys(db) == [] + with pytest.raises(RuntimeError, match="stop"): + with db.transaction(): + _insert(db, 3) + raise RuntimeError("stop") + assert _keys(db) == [] + + +def test_nested_blocks_keep_their_rules_and_an_inner_failure_rolls_back_only_the_inner( + db, +): + with db.transaction(): + _insert(db, 10) + try: + with db.transaction(): + _insert(db, 11) + raise ValueError("inner") + except ValueError: + pass + _insert(db, 12) + assert _keys(db) == [10, 12] + + +def test_a_statement_that_fails_in_the_middle_leaves_nothing_of_its_own_rows(db): + _insert(db, 1) + with pytest.raises(ArcadeDBError, match="DuplicatedKeyException"): + db.command("sql", "INSERT INTO T (k) VALUES (20), (21), (20)") + assert db.is_transaction_active() is False + assert _keys(db) == [1] + _insert(db, 22) # the handle is usable at once + assert _keys(db) == [1, 22] + + +def test_a_script_commits_each_statement_alone_unless_it_has_begin_and_commit(db): + with pytest.raises(ArcadeDBError, match="DuplicatedKeyException"): + db.command("sqlscript", "INSERT INTO T SET k = 30; INSERT INTO T SET k = 30;") + assert _keys(db) == [30] # the first statement committed alone + + db.command( + "sqlscript", + "BEGIN; INSERT INTO T SET k = 31; INSERT INTO T SET k = 32; COMMIT;", + ) + assert _keys(db) == [30, 31, 32] + assert db.is_transaction_active() is False + + with pytest.raises(ArcadeDBError, match="DuplicatedKeyException"): + db.command( + "sqlscript", + "BEGIN; INSERT INTO T SET k = 40; INSERT INTO T SET k = 30; COMMIT;", + ) + assert 40 not in _keys(db) # the whole script was undone + assert db.is_transaction_active() is False + + +def test_a_query_opens_no_transaction_and_a_write_through_it_is_refused(db): + db.query("sql", "SELECT FROM T").to_list() + assert db.is_transaction_active() is False + with pytest.raises(ArcadeDBError): + db.query("sql", "INSERT INTO T SET k = 99").to_list() + assert _keys(db) == [] + + +def test_a_commit_with_nothing_open_still_raises_and_a_rollback_does_not(db): + with pytest.raises(ArcadeDBError, match="Transaction not begun"): + db.commit() + db.rollback() + + +def test_save_and_delete_of_a_record_commit_on_their_own(db): + db.command("sql", "CREATE VERTEX TYPE V") + db.command("sql", "CREATE EDGE TYPE E") + first = db.new_vertex("V").set("n", 1).save() + second = db.new_vertex("V").set("n", 2).save() + first.new_edge("E", second).save() + assert db.is_transaction_active() is False + assert db.query("sql", "SELECT count(*) AS n FROM V").first().get("n") == 2 + assert db.query("sql", "SELECT count(*) AS n FROM E").first().get("n") == 1 + + changed = db.lookup_by_rid(first.get_rid()).modify().set("n", 100) + changed.save() + assert db.is_transaction_active() is False + assert db.lookup_by_rid(first.get_rid()).get("n") == 100 + + gone = db.lookup_by_rid(second.get_rid()).modify() + gone.delete() + assert db.query("sql", "SELECT count(*) AS n FROM V").first().get("n") == 1 + + +def test_in_strict_mode_a_save_outside_a_transaction_raises_and_writes_nothing(db): + db.set_auto_transaction(False) + with pytest.raises(ArcadeDBError, match="Transaction not begun"): + db.new_document("T").set("k", 5).save() + assert _keys(db) == [] + with db.transaction(): + db.new_document("T").set("k", 5).save() + assert _keys(db) == [5] + + +def test_insert_many_keeps_its_own_transactions_with_the_default_on_or_off(db): + for auto in (True, False): + db.set_auto_transaction(auto) + base = 1000 * (1 + int(auto)) + count = db.insert_many( + "T", [{"k": base + i} for i in range(1000)], commit_every=250 + ) + assert count == 1000 + assert db.is_transaction_active() is False + assert len([k for k in _keys(db) if base <= k < base + 1000]) == 1000 + + +def test_insert_many_inside_a_transaction_of_yours_joins_it(db): + db.begin() + db.insert_many("T", [{"k": 2000 + i} for i in range(10)]) + assert db.is_transaction_active() is True + db.rollback() + assert _keys(db) == [] + + +def test_graph_batch_keeps_its_own_transactions_and_still_refuses_yours(db): + db.command("sql", "CREATE VERTEX TYPE City") + with db.graph_batch(parallel_flush=False) as batch: + batch.create_vertices("City", 500) + assert db.is_transaction_active() is False + assert db.query("sql", "SELECT count(*) AS n FROM City").first().get("n") == 500 + with db.graph_batch(parallel_flush=False) as batch: + db.begin() + try: + with pytest.raises(ArcadeDBError): + batch.create_vertices("City", 2) + assert db.is_transaction_active() is True + finally: + db.rollback() + + +def test_a_thread_without_a_transaction_commits_alone_while_another_has_one_open(db): + db.begin() + _insert(db, 3000) + outcome = [] + + def worker(): + try: + _insert(db, 3001) + outcome.append("ok") + except Exception as error: # noqa: BLE001 + outcome.append(repr(error)) + + thread = threading.Thread(target=worker) + thread.start() + thread.join() + db.rollback() + assert outcome == ["ok"] + assert _keys(db) == [ + 3001 + ] # the worker's row is its own commit; mine was rolled back + + +def test_run_in_transaction_still_runs_the_function_in_one_transaction(db): + def work(): + _insert(db, 1) + _insert(db, 2) + assert db.is_transaction_active() is True + return "done" + + assert db.run_in_transaction(work) == "done" + assert _keys(db) == [1, 2] + + +def test_the_asyncio_facade_commits_a_bare_command(db): + async def main(): + async with AsyncDatabase(db) as adb: + await adb.command("sql", "INSERT INTO T SET k = 7") + rows = await adb.query("sql", "SELECT k FROM T") + return [r["k"] for r in rows] + + assert asyncio.run(main()) == [7] + + +def test_the_database_of_an_embedded_server_has_it_on_too(temp_server_root): + with arcadedb.create_server( + root_path=temp_server_root, + root_password=TEST_PASSWORD, + config={"http_port": free_port()}, + ) as server: + db = server.create_database("autotx") + assert db.is_auto_transaction() is True + db.command("sql", "CREATE DOCUMENT TYPE T") + db.command("sql", "INSERT INTO T SET k = 1") + assert db.query("sql", "SELECT count(*) AS n FROM T").first().get("n") == 1 + again = server.get_database("autotx") + assert again.is_auto_transaction() is True diff --git a/tests/test_graph_api.py b/tests/test_graph_api.py index 2f6a8bf5..92d344c3 100644 --- a/tests/test_graph_api.py +++ b/tests/test_graph_api.py @@ -608,9 +608,12 @@ def test_save_refuses_a_stale_record_from_a_query_result(temp_db_path): assert _stored_ab(db) == (10, 2) -def test_save_of_an_existing_record_outside_a_transaction_is_refused(temp_db_path): - """Both builds: save() is a write, so it needs an active transaction (auto-transaction is off by default) and opens none of its own.""" +def test_save_of_an_existing_record_outside_a_transaction_is_refused_in_strict_mode( + temp_db_path, +): + """Both builds: in strict mode (auto-transaction off) save() is a write that needs an active transaction, and it opens none of its own.""" with arcadedb.create_database(temp_db_path) as db: + db.set_auto_transaction(False) rid = _create_doc_ab(db) mutable = db.lookup_by_rid(rid).modify() diff --git a/tests/test_graph_batch.py b/tests/test_graph_batch.py index b5d14283..1165d749 100644 --- a/tests/test_graph_batch.py +++ b/tests/test_graph_batch.py @@ -482,6 +482,9 @@ def test_graph_batch_create_vertices_failure_rolls_back(temp_db_path, bulk): any transaction was accepted and silently lost at close (#121).""" with arcadedb.create_database(temp_db_path) as db: _unique_person_db(db) + db.set_auto_transaction( + False + ) # a write outside a transaction raises: the proof that none was left open # a NaN is not JSON-safe, so it routes to the property-matrix path (a datetime # crosses inside the JSON as a tagged value since the graph batches carry it) extra = {} if bulk else {"seen": float("nan")} @@ -499,6 +502,12 @@ def test_graph_batch_create_vertices_failure_rolls_back(temp_db_path, bulk): db.command("sql", "INSERT INTO Note SET text = 'outside a transaction'") assert db.count_type("Person") == 1 + # with auto-transaction on (the default) the same write commits on its own + db.set_auto_transaction(True) + db.command("sql", "INSERT INTO Note SET text = 'outside a transaction'") + assert db.is_transaction_active() is False + assert db.count_type("Note") == 1 + def test_graph_batch_create_vertices_keeps_the_callers_transaction(temp_db_path): """The rollback is for a transaction create_vertices opened itself: one the diff --git a/tests/test_native_one_row_crossings.py b/tests/test_native_one_row_crossings.py index d24cde4e..d29314f9 100644 --- a/tests/test_native_one_row_crossings.py +++ b/tests/test_native_one_row_crossings.py @@ -174,7 +174,8 @@ def _saved(db, **values): return str(doc.get_identity()) -def test_updating_a_saved_record_is_three_crossings(db, crossings): +def test_updating_a_saved_record_in_strict_mode_is_three_crossings(db, crossings): + db.set_auto_transaction(False) rid = _saved(db, a=1, name="x") with db.transaction(): record = db.lookup_by_rid(rid).modify() @@ -186,7 +187,10 @@ def test_updating_a_saved_record_is_three_crossings(db, crossings): assert db.lookup_by_rid(rid).get("a") == 2 -def test_an_update_that_reads_its_row_back_is_three_crossings(db, crossings): +def test_an_update_that_reads_its_row_back_in_strict_mode_is_three_crossings( + db, crossings +): + db.set_auto_transaction(False) rid = _saved(db, a=1) with db.transaction(): record = db.lookup_by_rid(rid).modify() @@ -315,7 +319,10 @@ def test_a_stale_record_is_still_refused_before_anything_is_written(db): assert (stored.get("a"), stored.get("b")) == (1, 9) # nothing of mine was written -def test_an_update_outside_a_transaction_still_raises_before_reading(db, crossings): +def test_an_update_outside_a_transaction_in_strict_mode_raises_before_reading( + db, crossings +): + db.set_auto_transaction(False) rid = _saved(db, a=1) record = db.lookup_by_rid(rid).modify() record.set("a", 2) @@ -352,6 +359,7 @@ def test_a_before_create_veto_on_a_new_record_writes_nothing_and_raises_nothing( def test_a_before_update_veto_writes_nothing_and_the_next_save_is_no_conflict( db, crossings ): + db.set_auto_transaction(False) # the crossings below are those of the strict mode rid = _saved(db, name="a") veto = db.on("before_update", lambda r: r.get("name") != "frozen", "D") vetoes = extras.veto_count() @@ -371,6 +379,7 @@ def test_a_before_update_veto_writes_nothing_and_the_next_save_is_no_conflict( def test_a_before_update_veto_on_an_update_that_reads_its_row_back(db, crossings): + db.set_auto_transaction(False) # the crossings below are those of the strict mode rid = _saved(db, name="a") veto = db.on("before_update", lambda r: r.get("extra") != "x", "D") vetoes = extras.veto_count() diff --git a/tests/test_python_callbacks.py b/tests/test_python_callbacks.py index d3e167b8..80ba603f 100644 --- a/tests/test_python_callbacks.py +++ b/tests/test_python_callbacks.py @@ -626,9 +626,19 @@ def explode(record): veto.remove() assert _names(db) == ["y"] - # without a transaction the engine refuses, as an ArcadeDBError + # a bare save commits on its own, so the callback of the bare write fails it and nothing is written + handle = db.on("before_create", explode, "Person") + with pytest.raises(arcadedb.ArcadeDBError, match="before_create.*no today"): + db.new_document("Person").set("name", "w").save() + handle.remove() + assert _names(db) == ["y"] + assert db.is_transaction_active() is False + + # in strict mode, without a transaction the engine refuses, as an ArcadeDBError + db.set_auto_transaction(False) with pytest.raises(arcadedb.ArcadeDBError): db.new_document("Person").set("name", "w").save() + db.set_auto_transaction(True) def test_event_registration_errors(db): diff --git a/tests/test_transactions_behavior.py b/tests/test_transactions_behavior.py index ff7bfa00..b460946d 100644 --- a/tests/test_transactions_behavior.py +++ b/tests/test_transactions_behavior.py @@ -79,7 +79,19 @@ def test_begin_then_rollback_or_commit(db): assert _names(db) == ["alice"] -def test_a_write_commit_or_rollback_outside_a_transaction(db): +def test_a_commit_outside_a_transaction_raises_and_a_rollback_does_not(db): + # the same with auto-transaction on (the default) and off + for auto in (True, False): + db.set_auto_transaction(auto) + with pytest.raises(ArcadeDBError, match="Transaction not begun"): + db.commit() + db.rollback() + assert db.is_transaction_active() is False + db.set_auto_transaction(True) + + +def test_in_strict_mode_a_write_outside_a_transaction_raises_and_writes_nothing(db): + db.set_auto_transaction(False) with pytest.raises(ArcadeDBError, match="Transaction not begun"): _insert(db, "alice") assert _names(db) == [] @@ -163,16 +175,20 @@ def test_an_exception_in_a_nested_block_rolls_back_only_that_block(db): assert _names(db) == ["outer"] -def test_set_auto_transaction_commits_each_bare_write_alone(db): - db.set_auto_transaction(True) +def test_auto_transaction_is_on_by_default_and_commits_each_bare_write_alone(db): + assert db.is_auto_transaction() is True + _insert(db, "alice") + assert db.is_transaction_active() is False + assert _names(db) == ["alice"] + db.set_auto_transaction(False) try: - _insert(db, "alice") - assert db.is_transaction_active() is False - assert _names(db) == ["alice"] + assert db.is_auto_transaction() is False + with pytest.raises(ArcadeDBError, match="Transaction not begun"): + _insert(db, "bob") finally: - db.set_auto_transaction(False) - with pytest.raises(ArcadeDBError, match="Transaction not begun"): - _insert(db, "bob") + db.set_auto_transaction(True) + assert db.is_auto_transaction() is True + assert _names(db) == ["alice"] def test_run_in_transaction_returns_the_value_and_has_these_defaults(db): diff --git a/tests/test_values_and_records_behavior.py b/tests/test_values_and_records_behavior.py index 282f7090..08900202 100644 --- a/tests/test_values_and_records_behavior.py +++ b/tests/test_values_and_records_behavior.py @@ -326,8 +326,9 @@ def test_new_document_set_and_save_chain_and_return_the_same_object(temp_db): } -def test_save_is_a_write_and_needs_a_transaction(temp_db): +def test_save_is_a_write_and_in_strict_mode_needs_a_transaction(temp_db): temp_db.command("sql", "CREATE DOCUMENT TYPE Task") + temp_db.set_auto_transaction(False) task = temp_db.new_document("Task").set("title", "x") with pytest.raises(ArcadeDBError, match="Transaction not begun"): task.save() From 81bb9cf7c8c8a9900b9995e33b9dd1cbecec5a23 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Wed, 25 Nov 2026 02:33:11 +0900 Subject: [PATCH 2/2] Test: two writers with a bare save(), the stale one is refused with auto-transaction on (#478) The stale-record check of save() is a value comparison (native) or a version check (JVM) and does not depend on a transaction, so a bare save() by writer B commits alone and writer A, who read the record earlier, must still get ConcurrentModificationException and write nothing. The test runs on both builds; the window between the check and the write of a bare native save() is not closed by auto-transaction and stays documented in concurrency.adoc. --- tests/test_auto_transaction_default.py | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/test_auto_transaction_default.py b/tests/test_auto_transaction_default.py index 05d8cf08..fc1ac9c8 100644 --- a/tests/test_auto_transaction_default.py +++ b/tests/test_auto_transaction_default.py @@ -233,6 +233,48 @@ def worker(): ] # the worker's row is its own commit; mine was rolled back +def test_two_writers_with_a_bare_save_the_stale_one_is_refused_with_the_default_on(db): + """The stale-record check of ``save()`` does not need a transaction: with auto-transaction on, writer B's bare ``save()`` + commits on its own, and writer A, who read the record before that, is refused and writes nothing (both builds). + """ + rid = db.new_document("T").set("k", 5000).set("v", 1).save().get_rid() + + def stored(): + return db.query("sql", "SELECT v FROM T WHERE k = 5000").first().get("v") + + stale = db.lookup_by_rid(rid).modify() # writer A reads the record + outcome = [] + + def writer_b(): + try: + other = db.lookup_by_rid( + rid + ).modify() # writer B reads, changes and saves, with no transaction of its own + other.set("v", 2).save() + outcome.append(db.is_transaction_active()) + except Exception as error: # noqa: BLE001 + outcome.append(repr(error)) + + thread = threading.Thread(target=writer_b) + thread.start() + thread.join() + assert outcome == [ + False + ] # B's save committed by itself and left no transaction open + assert stored() == 2 + + with pytest.raises(ArcadeDBError, match="ConcurrentModificationException"): + stale.set( + "v", 3 + ).save() # A's bare save writes over a change it never read: refused + assert db.is_transaction_active() is False + assert stored() == 2 # nothing of the refused save is stored + + fresh = db.lookup_by_rid(rid).modify() # a fresh read saves, bare + fresh.set("v", 3).save() + assert stored() == 3 + + def test_run_in_transaction_still_runs_the_function_in_one_transaction(db): def work(): _insert(db, 1)