diff --git a/README.md b/README.md index cbfc5be..bd3ffeb 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ with arcadedb.create_database("./mydb") as db: 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. 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. ## What is included diff --git a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc index cdab91a..4753e8e 100644 --- a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc +++ b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc @@ -37,13 +37,8 @@ with arcadedb.open_database("./mydb") as db: for user in db.query("sql", "SELECT FROM User"): print(user.get("name")) -# Open an existing database or create it -path = "./myapp" -if arcadedb.database_exists(path): - db = arcadedb.open_database(path) -else: - db = arcadedb.create_database(path) -with db: +# Open an existing database or create it, in one call +with arcadedb.open_or_create_database("./myapp") as db: print("Transaction active:", db.is_transaction_active()) with db.transaction(): print("Transaction active:", db.is_transaction_active()) @@ -72,16 +67,41 @@ Notes on the script: * `create_database(path)` creates the directory and opens the database for reading and writing. It raises `ArcadeDBError` if the path already holds a database, as the third output line shows. * `open_database(path)` opens an existing database. `database_exists(path)` tells the two cases apart. +* `open_or_create_database(path)` opens the database when it exists and creates it when it does not, so a script that keeps its data in one database runs the same way the first time and every time after. See <>. * `with` closes the database when the block ends, also when an exception leaves it. On close, active transactions roll back. You can call `db.close()` yourself, inside `try`/`finally`, but the context manager is the recommended way. * `db.drop()` deletes all files of the database. It cannot be undone. * `db.is_transaction_active()` is `True` only inside `with db.transaction():` (or between `begin()` and `commit()` or `rollback()`). The other ways to end a transaction, and what an error does to it, are on xref:how-to/transactions.adoc[Transactions]. +[#open-or-create] +=== Open or create + +`open_or_create_database(path)` is `open_database(path)` when `database_exists(path)` is true and `create_database(path)` when it is not. It takes the same `jvm_kwargs` and `read_only` arguments, returns the open database, and works in both packages. `DatabaseFactory(path).open_or_create()` is the same call on a factory. `create_database` and `open_database` are unchanged: the first still raises on a path that holds a database and the second on a path that holds none. + +[source,python,subs="attributes+"] +---- +{import-stmt} + +with arcadedb.open_or_create_database("./memory") as db: + db.command("sql", "CREATE DOCUMENT TYPE Note IF NOT EXISTS") + with db.transaction(): + db.command("sql", "INSERT INTO Note SET text = ?", "remember this") + print(db.query("sql", "SELECT count(*) AS n FROM Note").first().get("n")) +---- + +Run it twice: the first run creates the database and prints `1`, the second opens it and prints `2`. What it does in the cases that are not the plain first or later run: + +* `read_only=True` never creates. A path that holds no database raises `ArcadeDBError`, with the same message as `open_database`, and nothing is written. +* The path is a directory that holds no database (empty, or with other files in it): a database is created inside it and the other files stay untouched, as with `create_database`. The path is a file: it raises `ArcadeDBError` ("Not a directory") and changes nothing. +* Another process holds the database open: it raises `ArcadeDBError` with the engine's "locked by another process" message and does not wait. See <>. The same process cannot hold one path twice either (the engine says "already in use"): keep the first handle and share it between threads. +* Two processes call it on the same new path at the same moment: one creates the database. The other finds that the database exists now and opens it, so it never fails with "already exists" or "does not exist". It raises the "locked by another process" error while the first process keeps the database open, and works once that one closes it. + === Read-only open `open_database(path, read_only=True)` opens an existing database for reading only; `DatabaseFactory(path).open(read_only=True)` does the same. Queries, counts and record reads work as usual and `db.is_read_only()` is `True`. Every write raises `ArcadeDBError` with "read only" in the message: an `INSERT`, a schema change such as `CREATE DOCUMENT TYPE`, or `save()` on a record. Reads inside `with db.transaction():` work too; on ArcadeDB 26.11.1 and later the commit or rollback of such a transaction returns, while earlier engines raise the same read-only error there. Use it when a process only reads a finished database, so that a stray write fails instead of changing the data. It is a safety setting, not a speed setting: no measurement here shows reads getting faster. +[#locking] === Locking The open database holds an operating-system lock on `database.lck` in its directory. A second process cannot open the same directory while the first holds it; open it in one process and share the handle between that process's threads. diff --git a/docs/modules/ROOT/pages/quickstart.adoc b/docs/modules/ROOT/pages/quickstart.adoc index a5e32c0..bc041cf 100644 --- a/docs/modules/ROOT/pages/quickstart.adoc +++ b/docs/modules/ROOT/pages/quickstart.adoc @@ -99,7 +99,7 @@ People over 25: Total people: 3 ---- -`create_database` raises if the path already holds a database, so run the script in an empty directory or delete `./quickstart` before you run it again. +`create_database` raises if the path already holds a database, so run the script in an empty directory or delete `./quickstart` before you run it again. A script that runs more than once can call `open_or_create_database(path)` instead: it opens the database when it exists and creates it when it does not (see xref:how-to/databases-and-queries.adoc#open-or-create[Open or create]). The steps in the script are: diff --git a/src/arcadedb/__init__.py b/src/arcadedb/__init__.py index 86e1208..b9ebe78 100644 --- a/src/arcadedb/__init__.py +++ b/src/arcadedb/__init__.py @@ -51,6 +51,7 @@ create_database, database_exists, open_database, + open_or_create_database, ) # Import exceptions @@ -131,6 +132,7 @@ "jar_fingerprint", "create_database", "open_database", + "open_or_create_database", "database_exists", # Result classes "ResultSet", diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 7141000..279c614 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -10,6 +10,7 @@ from typing import Any, Dict, Iterator, List, Optional from .. import _columnar +from .._open_or_create import open_or_create from .._params import refuse_surplus_positionals from ..exceptions import ArcadeDBError from ..transactions import TransactionContext @@ -1980,3 +1981,7 @@ def exists(self) -> bool: lib.b(self._path), 3, )["exists"] + + def open_or_create(self, read_only: bool = False) -> NativeDatabase: + """Open the database when it exists and create it when it does not (``arcadedb.open_or_create_database``).""" + return open_or_create(self, read_only=read_only) diff --git a/src/arcadedb/_open_or_create.py b/src/arcadedb/_open_or_create.py new file mode 100644 index 0000000..781f5ec --- /dev/null +++ b/src/arcadedb/_open_or_create.py @@ -0,0 +1,48 @@ +"""Open a database when it exists and create it when it does not: the one routine behind +``arcadedb.open_or_create_database`` and ``DatabaseFactory.open_or_create``, for both builds. + +``factory`` is a ``DatabaseFactory`` (the JVM build) or a ``NativeDatabaseFactory`` (the native build): both have ``exists()``, +``create()`` and ``open(read_only=)`` and raise ``ArcadeDBError``. The rules are the ones on the page "Databases and queries". +""" + +from __future__ import annotations + +import threading +import time + +from .exceptions import ArcadeDBError + +# One lock for the process, so two threads that open or create the same path do not both see "missing" and both create. +_LOCK = threading.Lock() + +# After a create that failed, how long to wait for another process to finish creating the same database, and how often to look. +_LOST_RACE_WAIT_S = 0.25 +_LOST_RACE_STEP_S = 0.01 + + +def open_or_create(factory, read_only: bool = False): + """Open the database of ``factory`` when it exists, create it when it does not, and return the open database. + + ``read_only=True`` never creates: there is nothing to open read-only in a path that holds no database, so a missing database + raises the same ``ArcadeDBError`` as ``open_database``. + + Two processes that call this on the same new path at the same time: one of them creates the database, the other one's create + fails, it sees that the database exists now and opens it. The engine allows one process per database, so that open raises the + engine's "locked by another process" ``ArcadeDBError`` for as long as the first process keeps the database open. + """ + with _LOCK: + if read_only: + return factory.open(read_only=True) + if factory.exists(): + return factory.open() + try: + return factory.create() + except ArcadeDBError: + # The database may have appeared between exists() and create() (another process won): then open it. + # Any other failure (a path that is a file, no permission) is still missing a database: raise the create error. + deadline = time.monotonic() + _LOST_RACE_WAIT_S + while not factory.exists(): + if time.monotonic() >= deadline: + raise + time.sleep(_LOST_RACE_STEP_S) + return factory.open() diff --git a/src/arcadedb/core.py b/src/arcadedb/core.py index 13625cb..618dd1f 100644 --- a/src/arcadedb/core.py +++ b/src/arcadedb/core.py @@ -19,6 +19,7 @@ import jpype from ._logging import get_logger +from ._open_or_create import open_or_create as _open_or_create from ._params import refuse_surplus_positionals from .callbacks import ( EventHandle, @@ -2808,6 +2809,13 @@ def exists(self) -> bool: except Exception as e: raise ArcadeDBError(f"Failed to check if database exists: {e}") from e + def open_or_create(self, read_only: bool = False) -> Database: + """Open the database when it exists and create it when it does not. + + See :func:`open_or_create_database` for the rules. + """ + return _open_or_create(self, read_only=read_only) + # Convenience functions def create_database( @@ -2856,6 +2864,58 @@ def open_database( return factory.open(read_only=read_only) +def open_or_create_database( + path: str, + jvm_kwargs: Optional[dict] = None, + read_only: bool = False, +) -> Database: + """Open the database at the given path, or create it when there is none, and return it. + + One call that works on the first run and on every later run, so a script + that keeps its data in one database can start with it and be run again. + It is ``open_database(path)`` when ``database_exists(path)`` and + ``create_database(path)`` when not; ``create_database`` and + ``open_database`` are unchanged. + + Args: + path: Database path + jvm_kwargs: Optional JVM args passed to start_jvm() (ignored with a + warning by the native package, which has no JVM) + read_only: Open the database read-only. It never creates: a path that + holds no database raises ``ArcadeDBError``, as ``open_database`` + does. + + Raises: + ArcadeDBError: when the database cannot be opened or created. Three + cases: + + * The path exists and is not a database. A directory without a + database (an empty one, or one that holds other files) gets a + new database inside it and its other files stay untouched, as + with ``create_database``. A path that is a file raises + ``ArcadeDBError`` ("Not a directory") and nothing is changed. + * Another process holds the database open. The engine allows one + process per database, so the call raises ``ArcadeDBError`` with + the engine's "locked by another process" message and does not + wait. The same process cannot open a path twice either: close + the first handle, or share it between threads. + * Two processes call it on the same new path at once. One creates + the database. The other one's create fails, it finds the + database and opens it, so it never raises "already exists"; it + raises the "locked" error of the case above for as long as the + first process keeps the database open. + + Example: + >>> with arcadedb.open_or_create_database("./memory") as db: + ... db.command("sql", "CREATE DOCUMENT TYPE Note IF NOT EXISTS") + """ + factory = DatabaseFactory( + path, + jvm_kwargs=jvm_kwargs, + ) + return factory.open_or_create(read_only=read_only) + + def database_exists(path: str) -> bool: """Check if a database exists at the given path.""" factory = DatabaseFactory(path) diff --git a/tests/test_open_or_create.py b/tests/test_open_or_create.py new file mode 100644 index 0000000..b70f571 --- /dev/null +++ b/tests/test_open_or_create.py @@ -0,0 +1,222 @@ +"""open_or_create_database: one call that opens a database when it exists and creates it when it does not. + +The same file runs on both builds (arcadedb-jvm and the native arcadedb). The issue is ArcadeData/arcadedb-python#474: a script that +keeps its data in one database could not run twice, because create_database fails on the second run and open_database on the first. +""" + +import os +import subprocess # nosec B404 +import sys +import textwrap +import time + +import pytest + +import arcadedb +from arcadedb.exceptions import ArcadeDBError + +ACCEPTED_RACE_OUTCOMES = ("OK", "LOCKED") + + +def test_first_run_creates_second_run_opens(tmp_path): + path = str(tmp_path / "memory") + assert not arcadedb.database_exists(path) + + with arcadedb.open_or_create_database(path) as db: + db.command("sql", "CREATE DOCUMENT TYPE Note") + with db.transaction(): + db.command("sql", "INSERT INTO Note SET text = ?", "first run") + assert arcadedb.database_exists(path) + + # the second run: the same call, the data of the first run is there, and the type is not created again + with arcadedb.open_or_create_database(path) as db: + db.command("sql", "CREATE DOCUMENT TYPE Note IF NOT EXISTS") + with db.transaction(): + db.command("sql", "INSERT INTO Note SET text = ?", "second run") + texts = sorted(r.get("text") for r in db.query("sql", "SELECT FROM Note")) + assert texts == ["first run", "second run"] + + # a third call after the second closed it + with arcadedb.open_or_create_database(path) as db: + assert db.query("sql", "SELECT count(*) AS n FROM Note").first().get("n") == 2 + + +def test_the_existing_calls_keep_their_errors(tmp_path): + path = str(tmp_path / "db") + with pytest.raises(ArcadeDBError, match="does not exist"): + arcadedb.open_database(path) + arcadedb.open_or_create_database(path).close() + with pytest.raises(ArcadeDBError, match="already exists"): + arcadedb.create_database(path) + arcadedb.open_database(path).close() + + +def test_factory_method_does_the_same(tmp_path): + path = str(tmp_path / "db") + factory = arcadedb.DatabaseFactory(path) + assert not factory.exists() + factory.open_or_create().close() + assert factory.exists() + db = factory.open_or_create() + try: + assert db.is_open() + assert not db.is_read_only() + finally: + db.close() + + +def test_read_only_opens_an_existing_database(tmp_path): + path = str(tmp_path / "db") + with arcadedb.open_or_create_database(path) as db: + db.command("sql", "CREATE DOCUMENT TYPE Note") + with arcadedb.open_or_create_database(path, read_only=True) as db: + assert db.is_read_only() + assert db.query("sql", "SELECT count(*) AS n FROM Note").first().get("n") == 0 + with pytest.raises(ArcadeDBError): + db.command("sql", "CREATE DOCUMENT TYPE Other") + + +def test_read_only_never_creates(tmp_path): + path = str(tmp_path / "missing") + with pytest.raises(ArcadeDBError, match="does not exist"): + arcadedb.open_or_create_database(path, read_only=True) + assert not os.path.exists(path) + assert not arcadedb.database_exists(path) + + +def test_a_path_that_is_a_file_raises_and_changes_nothing(tmp_path): + path = tmp_path / "afile" + path.write_text("not a database") + with pytest.raises(ArcadeDBError): + arcadedb.open_or_create_database(str(path)) + assert path.read_text() == "not a database" + assert path.is_file() + + +def test_a_directory_without_a_database_gets_one_and_keeps_its_files(tmp_path): + folder = tmp_path / "notes" + folder.mkdir() + (folder / "readme.txt").write_text("mine") + assert not arcadedb.database_exists(str(folder)) + with arcadedb.open_or_create_database(str(folder)) as db: + db.command("sql", "CREATE DOCUMENT TYPE Note") + assert arcadedb.database_exists(str(folder)) + assert (folder / "readme.txt").read_text() == "mine" + with arcadedb.open_or_create_database(str(folder)) as db: + assert db.query("sql", "SELECT count(*) AS n FROM Note").first().get("n") == 0 + + +def test_the_same_process_cannot_hold_a_path_twice(tmp_path): + path = str(tmp_path / "db") + with arcadedb.open_or_create_database(path): + with pytest.raises(ArcadeDBError, match="already in use"): + arcadedb.open_or_create_database(path) + arcadedb.open_or_create_database(path).close() + + +def test_jvm_kwargs_are_accepted_like_open_database(tmp_path): + # the JVM is usually started by an earlier test with other settings: an empty dict starts nothing new and conflicts with nothing + path = str(tmp_path / "db") + arcadedb.open_or_create_database(path, jvm_kwargs={}).close() + arcadedb.open_or_create_database(path, jvm_kwargs={}, read_only=True).close() + + +def _child(code, *args): + return subprocess.Popen( # nosec B603 + [sys.executable, "-c", textwrap.dedent(code), *args], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + + +def _wait_for_file(path, timeout=120): + deadline = time.monotonic() + timeout + while not os.path.exists(path): + if time.monotonic() > deadline: + raise AssertionError(f"timed out waiting for {path}") + time.sleep(0.02) + + +HOLDER = """ + import os, sys, time + import arcadedb + path, ready, stop = sys.argv[1:4] + db = arcadedb.open_or_create_database(path) + open(ready, "w").close() + deadline = time.monotonic() + 120 + while not os.path.exists(stop) and time.monotonic() < deadline: + time.sleep(0.02) + db.close() +""" + + +def test_locked_by_another_process_raises_the_engine_error_and_does_not_wait(tmp_path): + path = str(tmp_path / "db") + ready, stop = str(tmp_path / "ready"), str(tmp_path / "stop") + holder = _child(HOLDER, path, ready, stop) + try: + _wait_for_file(ready) + started = time.monotonic() + with pytest.raises(ArcadeDBError, match="locked by another process"): + arcadedb.open_or_create_database(path) + # a hang detector, not a latency bound: the call returns the engine's error, it does not wait for the holder + assert time.monotonic() - started < 60 + finally: + open(stop, "w").close() + out, err = holder.communicate(timeout=120) + assert holder.returncode == 0, err + # the holder let go: the call works again, and the database it created is intact + with arcadedb.open_or_create_database(path) as db: + assert db.is_open() + + +RACER = """ + import os, sys, time + import arcadedb + path, ready, go = sys.argv[1:4] + arcadedb.database_exists(os.path.join(os.path.dirname(path), "warm-up")) # start the engine before the signal + open(ready, "w").close() + deadline = time.monotonic() + 120 + while not os.path.exists(go) and time.monotonic() < deadline: + time.sleep(0.001) + try: + arcadedb.open_or_create_database(path).close() + print("RESULT OK") + except arcadedb.ArcadeDBError as exc: + print("RESULT", "LOCKED" if "locked by another process" in str(exc) else "ERROR", exc) +""" + + +@pytest.mark.parametrize("round_number", range(3)) +def test_two_processes_racing_on_a_new_path(tmp_path, round_number): + """Both processes call the function at the same moment on a path that holds no database. + + Neither may fail with "already exists" or "does not exist". The only other outcome is the engine's lock error, when one process + still holds the database as the other one looks (the engine allows one process per database). At least one process gets the + database, and the directory it made opens afterwards. + """ + path = str(tmp_path / "db") + go = str(tmp_path / "go") + readies = [str(tmp_path / f"ready{i}") for i in range(2)] + children = [_child(RACER, path, r, go) for r in readies] + try: + for r in readies: + _wait_for_file(r) + open(go, "w").close() + outputs = [c.communicate(timeout=120) for c in children] + finally: + for c in children: + if c.poll() is None: + c.kill() + outcomes = [] + for child, (out, err) in zip(children, outputs): + assert child.returncode == 0, err + line = [ln for ln in out.splitlines() if ln.startswith("RESULT")][-1] + outcomes.append(line) + kinds = [ln.split()[1] for ln in outcomes] + assert all(k in ACCEPTED_RACE_OUTCOMES for k in kinds), outcomes + assert "OK" in kinds, outcomes + assert arcadedb.database_exists(path) + with arcadedb.open_or_create_database(path) as db: + assert db.is_open()