Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
34 changes: 27 additions & 7 deletions docs/modules/ROOT/pages/how-to/databases-and-queries.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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 <<open-or-create>>.
* `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 <<locking,Locking>>. 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.
Expand Down
2 changes: 1 addition & 1 deletion docs/modules/ROOT/pages/quickstart.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 2 additions & 0 deletions src/arcadedb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
create_database,
database_exists,
open_database,
open_or_create_database,
)

# Import exceptions
Expand Down Expand Up @@ -131,6 +132,7 @@
"jar_fingerprint",
"create_database",
"open_database",
"open_or_create_database",
"database_exists",
# Result classes
"ResultSet",
Expand Down
5 changes: 5 additions & 0 deletions src/arcadedb/_native/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
48 changes: 48 additions & 0 deletions src/arcadedb/_open_or_create.py
Original file line number Diff line number Diff line change
@@ -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()
60 changes: 60 additions & 0 deletions src/arcadedb/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading