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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* How-to
** xref:how-to/databases-and-queries.adoc[Databases and queries]
** xref:how-to/transactions.adoc[Transactions]
** xref:how-to/errors.adoc[Errors: codes, hints and classes]
** xref:how-to/values-and-records.adoc[Values and records]
** xref:how-to/concurrency.adoc[Concurrency, processes and crashes]
** xref:how-to/asyncio.adoc[asyncio: AsyncDatabase]
Expand Down
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/how-to/databases-and-queries.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ print("Exists after drop:", arcadedb.database_exists("./myapp"))
----
Created at: ./mydb
Exists: True
ArcadeDBError: Failed to create database: com.arcadedb.exception.DatabaseOperationException: Database './mydb' already exists
DatabaseExistsError: [database_exists] A database already exists at this path: open it with `open_database(path)`, or choose another path. Failed to create database: com.arcadedb.exception.DatabaseOperationException: Database './mydb' already exists
Name: mydb
Alice
Transaction active: False
Expand All @@ -70,7 +70,7 @@ Exists after drop: False

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.
* `create_database(path)` creates the directory and opens the database for reading and writing. It raises `DatabaseExistsError` (a subclass of `ArcadeDBError`, with the code `database_exists`) if the path already holds a database, as the third output line shows. The codes of all errors are on xref:how-to/errors.adoc[Errors: codes, hints and classes].
* `open_database(path)` opens an existing database. `database_exists(path)` tells the two cases apart.
* `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.
Expand Down
192 changes: 192 additions & 0 deletions docs/modules/ROOT/pages/how-to/errors.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
= Errors: codes, hints and classes
:description: Every failure is an ArcadeDBError with a code, a hint and the Java exception class, a subclass for the common causes, and the table of all of them, so that a program or a model can repair its own statement.

// Sources: src/arcadedb/exceptions.py (the table _RULES decides every row below), tests/test_error_codes_table.py (a literal for each row) and tests/test_error_codes_parity.py (the live failures, on both packages).

Every failed call raises `ArcadeDBError`. The error carries what a program needs to repair the call, so it does not have to search the message text:

* `e.code` is a short, stable name of the cause, for example `duplicate_key`. A failure that the table below does not know has the code `unknown`.
* `e.hint` is one sentence that tells what to do next. It is `None` for `unknown`.
* `e.cause` is the name of the Java exception class that decided the code, for example `com.arcadedb.exception.DuplicatedKeyException`. It is `None` when no Java exception is involved.
* `e.to_dict()` returns `type` (the class name), `code`, `hint`, `cause` and `message` (the text without the code and the hint) as plain data, for a log or for the next prompt of a model.

The common causes have a subclass of `ArcadeDBError`, so `except DuplicateKeyError` works and every `except ArcadeDBError` in existing code still catches everything. The engine does not give an error code of its own, so the code names are the ones of the bindings. They are the same in both packages: the same failure gives the same class and code in `arcadedb` (native) and in `arcadedb-jvm`.

== Repair a call from its error

The blocks on this page run one after the other against one empty database, and a test in the repository runs them that way (`tests/test_docs_errors_page.py`). Every block assumes that `db` is an open database.

[source,python]
----
from arcadedb import ArcadeDBError, DuplicateKeyError

db.command("sql", "CREATE DOCUMENT TYPE Memory")
db.command("sql", "CREATE PROPERTY Memory.key STRING")
db.command("sql", "CREATE INDEX ON Memory (key) UNIQUE")
with db.transaction():
db.command("sql", "INSERT INTO Memory SET key = 'a'")

try:
with db.transaction():
db.command("sql", "INSERT INTO Memory SET key = 'a'")
except DuplicateKeyError as e:
print(e.code)
print(e.hint)
----

[source,text]
----
duplicate_key
A unique index already holds this key: use another value, or update the record that has it (the message names the index and the record).
----

`str(e)` of a classified error is `[code] hint` followed by the text that the error had before, so the Java class and its message stay at the end and code that searches the text still finds them. An error with the code `unknown` prints exactly the older text.

[source,python]
----
try:
db.query("sql", "SELECT FROM Nope")
except ArcadeDBError as e:
print(type(e).__name__, e.code, e.cause)
print(e)
----

[source,text]
----
SchemaError type_not_found com.arcadedb.exception.SchemaException
[type_not_found] No type has this name: check the spelling against `SELECT name FROM schema:types`, or create the type first with `CREATE DOCUMENT TYPE`, `CREATE VERTEX TYPE` or `CREATE EDGE TYPE`. Query failed: com.arcadedb.exception.SchemaException: Type with name 'Nope' was not found
----

A program that runs statements for a model returns the error as data, and the model reads the code and the hint:

[source,python]
----
def run(statement):
try:
return {"ok": True, "rows": db.command("sql", statement).to_list()}
except ArcadeDBError as e:
return {"ok": False, "error": e.to_dict()}


reply = run("SELEC FROM Memory")
print(reply["ok"], reply["error"]["type"], reply["error"]["code"])
print(sorted(reply["error"]))
----

[source,text]
----
False QuerySyntaxError syntax_error
['cause', 'code', 'hint', 'message', 'type']
----

A code that the table does not know is not an empty answer: `e.code` is `unknown`, `e.cause` names the innermost Java exception when there is one, and the message is the engine's text.

== The codes

One row for each code. A row with more than one engine exception matches any of them. The engine exception is matched by its Java class name. A failure that the Python layer raises itself, or that one package words differently, is matched by its text, after the rows that match a class. The first row that matches decides.

[cols="2,2,3,5"]
|===
| Code | Class | Engine exception | Hint

| `duplicate_key`
| `DuplicateKeyError`
| `DuplicatedKeyException`
| A unique index already holds this key: use another value, or update the record that has it (the message names the index and the record).

| `record_not_found`
| `RecordNotFoundError`
| `RecordNotFoundException`, `VertexNotFoundException`
| No record has this RID: check the RID, or look the record up by a property with a query (it may have been deleted, or it was never committed).

| `transaction_not_begun`
| `TransactionError`
| `TransactionException`
| 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.

| `database_locked`
| `DatabaseLockedError`
| `LockException`
| Another process has this database open: close it there first, because only one process can open a database at a time.

| `database_exists`
| `DatabaseExistsError`
| `DatabaseOperationException`
| A database already exists at this path: open it with `open_database(path)`, or choose another path.

| `database_not_found`
| `DatabaseNotFoundError`
| `DatabaseNotFoundException`
| No database exists at this path: check the path, or create one with `create_database(path)`.

| `database_closed`
| `DatabaseClosedError`
| `DatabaseIsClosedException`
| The database was closed: open it again with `open_database(path)`, and read what you need from a result before you close the database.

| `database_read_only`
| `ArcadeDBError`
| `DatabaseIsReadOnlyException`
| The database was opened with `read_only=True`: open it again without that argument to write.

| `syntax_error`
| `QuerySyntaxError`
| `CommandSQLParsingException`, `CommandParsingException`
| The statement does not parse: fix the token that the message points at (line and column), and check the keywords against the ArcadeDB SQL or openCypher syntax.

| `timeout`
| `QueryTimeoutError`
| `TimeoutException`, `PartialResultTimeoutException`
| The statement ran past its TIMEOUT clause: add a filter, a LIMIT or an index so that it finishes sooner, or raise the timeout.

| `conflict`
| `ConflictError`
| `ConcurrentModificationException`, `LockTimeoutException`, `NeedRetryException`
| Another transaction changed the same data first: run the whole transaction again, for example with `db.run_in_transaction(fn)`, which retries it.

| `type_not_found`
| `SchemaError`
| `SchemaException`
| No type has this name: check the spelling against `SELECT name FROM schema:types`, or create the type first with `CREATE DOCUMENT TYPE`, `CREATE VERTEX TYPE` or `CREATE EDGE TYPE`.

| `already_exists`
| `SchemaError`
| `AlreadyExistsException`, `TypeAlreadyExistsException`
| A type, property or index with this name already exists: choose another name, or add `IF NOT EXISTS` to the CREATE statement of a type or an index.

| `schema`
| `SchemaError`
| `SchemaException`
| The schema does not allow this change: read the message, and compare it with the current schema (`SELECT FROM schema:types`).

| `type_mismatch`
| `ValidationError`
| `IllegalArgumentException`, `TypeMismatchException`
| A value does not fit the type of its property: send a value of the declared type (the message names the property and the type).

| `validation`
| `ValidationError`
| `ValidationException`
| A property constraint (mandatory, not null, min, max, regexp or read-only) refused the record: change the value that the message names, or change the constraint in the schema.

| `query_not_idempotent`
| `ArcadeDBError`
| `QueryNotIdempotentException`
| `db.query` runs reads only: send a statement that changes data with `db.command`.

| `missing_parameter`
| `ArcadeDBError`
| `CommandParameterMissingException`
| The statement has a parameter that was not passed: give a value for each `?` in order, or pass a dict that holds every `:name`.

|===

The causes without a subclass (`database_read_only`, `query_not_idempotent`, `missing_parameter`) raise `ArcadeDBError` itself, with the code set. Branch on `e.code` for them.

== Which error to retry

`ConflictError` is the one that a retry can fix: another transaction changed the same data first. Run the whole transaction again, or let `db.run_in_transaction(fn)` do it, as described on xref:how-to/transactions.adoc[Transactions] and xref:how-to/concurrency.adoc[Concurrency, processes and crashes]. A `DuplicateKeyError` is not a conflict: the same statement fails again until the value changes.

== What differs between the packages

Nothing in `code`, `hint` and the class. The native package also keeps `e.java_chain` (the chain of Java exceptions as `(class, message)` pairs) and `e.native` (the reply of the library), which the JVM package does not have; `e.cause` is the same name on both. Where the two engines word a failure differently, the table has a row for each wording, and a test runs every row against both packages.
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/how-to/import-export.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ PROBE_ONLY 3
[[failed-import]]
== When a row fails

The importer loads the rows of one file of documents in one transaction that it owns, and commits it after the last row. By default (`on_row_error="abort"`) the first row that fails stops the import with an `ArcadeDBError` that starts with "Document import failed", and the transaction is rolled back. No row of that file is left, however many rows were read before the bad one.
The importer loads the rows of one file of documents in one transaction that it owns, and commits it after the last row. By default (`on_row_error="abort"`) the first row that fails stops the import with an `ArcadeDBError` whose message holds "Document import failed" (a `DuplicateKeyError` when the row breaks a unique index, as below), and the transaction is rolled back. No row of that file is left, however many rows were read before the bad one.

A duplicate key shows the rule. The next blocks load a file whose second row repeats the unique key of the first:

Expand All @@ -170,7 +170,7 @@ def skus():
try:
db.import_documents(products, document_type="Product")
except ArcadeDBError as error:
print("failed:", str(error).startswith("Document import failed"))
print("failed:", "Document import failed" in str(error))
print(skus(), db.is_transaction_active())
----

Expand Down
4 changes: 3 additions & 1 deletion docs/modules/ROOT/pages/quickstart.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,11 @@ with arcadedb.open_database("./quickstart") as db:
[source,text]
----
Found 3 records
ArcadeDBError: Command failed: com.arcadedb.exception.TransactionException: Transaction not begun
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.

== 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:
Expand Down
28 changes: 27 additions & 1 deletion src/arcadedb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,21 @@
)

# Import exceptions
from .exceptions import ArcadeDBError # noqa: E402
from .exceptions import ( # noqa: E402
ArcadeDBError,
ConflictError,
DatabaseClosedError,
DatabaseExistsError,
DatabaseLockedError,
DatabaseNotFoundError,
DuplicateKeyError,
QuerySyntaxError,
QueryTimeoutError,
RecordNotFoundError,
SchemaError,
TransactionError,
ValidationError,
)

# Import exporter classes
from .exporter import export_database, export_to_csv # noqa: E402
Expand Down Expand Up @@ -119,6 +133,18 @@
"ENGINE_IMAGE_DIGEST",
# Exceptions
"ArcadeDBError",
"ConflictError",
"DatabaseClosedError",
"DatabaseExistsError",
"DatabaseLockedError",
"DatabaseNotFoundError",
"DuplicateKeyError",
"QuerySyntaxError",
"QueryTimeoutError",
"RecordNotFoundError",
"SchemaError",
"TransactionError",
"ValidationError",
# Core classes
"Database",
"DatabaseFactory",
Expand Down
11 changes: 7 additions & 4 deletions src/arcadedb/_native/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ def _error(prefix: str, reply: dict) -> ArcadeDBError:
"""The ArcadeDBError for a failed reply, worded like the JPype path (``prefix: java.class: message``)."""
chain = reply.get("chain") or []
head = f"{reply.get('cls')}: {reply.get('error')}"
exc = ArcadeDBError(f"{prefix}: {head}" if prefix else head)
# classified from the chain of the reply: the class and the code are the ones the JVM build gives for the same failure
exc = ArcadeDBError._classified(f"{prefix}: {head}" if prefix else head, chain)
exc.native = reply
exc.java_chain = chain
return interrupts.convert(
Expand All @@ -60,11 +61,13 @@ def _error(prefix: str, reply: dict) -> ArcadeDBError:


def _read_error(reply: dict) -> ArcadeDBError:
exc = ArcadeDBError(
f"Reading the result set failed: {reply.get('cls')}: {reply.get('error')}"
chain = reply.get("chain") or []
exc = ArcadeDBError._classified(
f"Reading the result set failed: {reply.get('cls')}: {reply.get('error')}",
chain,
)
exc.native = reply
exc.java_chain = reply.get("chain") or []
exc.java_chain = chain
return interrupts.convert(exc)


Expand Down
5 changes: 3 additions & 2 deletions src/arcadedb/_native/extras.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ def _register(fn: Callable) -> int:

def _error_from(message: dict) -> ArcadeDBError:
reply = message.get("err") or {}
exc = ArcadeDBError(f"{reply.get('cls')}: {reply.get('error')}")
chain = reply.get("chain") or []
exc = ArcadeDBError._classified(f"{reply.get('cls')}: {reply.get('error')}", chain)
exc.native = reply
exc.java_chain = reply.get("chain") or []
exc.java_chain = chain
return exc


Expand Down
Loading
Loading