diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index 0598725..1997ba2 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -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] 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..c0ae9c0 100644 --- a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc +++ b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc @@ -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 @@ -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. diff --git a/docs/modules/ROOT/pages/how-to/errors.adoc b/docs/modules/ROOT/pages/how-to/errors.adoc new file mode 100644 index 0000000..fd75f2c --- /dev/null +++ b/docs/modules/ROOT/pages/how-to/errors.adoc @@ -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. diff --git a/docs/modules/ROOT/pages/how-to/import-export.adoc b/docs/modules/ROOT/pages/how-to/import-export.adoc index ac3eaf8..bd61a46 100644 --- a/docs/modules/ROOT/pages/how-to/import-export.adoc +++ b/docs/modules/ROOT/pages/how-to/import-export.adoc @@ -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: @@ -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()) ---- diff --git a/docs/modules/ROOT/pages/quickstart.adoc b/docs/modules/ROOT/pages/quickstart.adoc index a5e32c0..3a17a68 100644 --- a/docs/modules/ROOT/pages/quickstart.adoc +++ b/docs/modules/ROOT/pages/quickstart.adoc @@ -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: diff --git a/src/arcadedb/__init__.py b/src/arcadedb/__init__.py index 86e1208..41561ec 100644 --- a/src/arcadedb/__init__.py +++ b/src/arcadedb/__init__.py @@ -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 @@ -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", diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 7141000..99ea5d8 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -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( @@ -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) diff --git a/src/arcadedb/_native/extras.py b/src/arcadedb/_native/extras.py index d23b14d..ad07007 100644 --- a/src/arcadedb/_native/extras.py +++ b/src/arcadedb/_native/extras.py @@ -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 diff --git a/src/arcadedb/exceptions.py b/src/arcadedb/exceptions.py index 6133ec4..d36697d 100644 --- a/src/arcadedb/exceptions.py +++ b/src/arcadedb/exceptions.py @@ -2,8 +2,16 @@ ArcadeDB Python Bindings - Exception Classes All custom exceptions for the ArcadeDB Python bindings. + +Every failure is an ``ArcadeDBError``. The error also carries ``code`` (a short stable name of the cause), ``hint`` (one sentence on +what to do next), ``cause`` (the Java exception class) and ``to_dict()``, and a subclass for the causes a program is likely to +branch on. The table that decides all of it is ``_RULES`` at the end of this module. """ +import re +import sys +from typing import NamedTuple, Optional, Tuple + def _java_root_cause(exc): """The innermost cause of a Java exception, or None. @@ -116,15 +124,127 @@ class names missed every subclass that was not listed, which is how a return None, 0 +def _java_chain_of(exc): + """``((Java class name, message or None), ...)`` of the Java exceptions behind ``exc``, outermost first. + + ``exc`` is the exception being handled when an error is built. A Java exception gives its own ``getCause()`` chain, an + ``ArcadeDBError`` the chain it was built from (a wrapper that re-raises it keeps the classification), anything else nothing. + """ + if exc is None: + return () + if isinstance(exc, ArcadeDBError): + return exc._chain + chain = [] + try: + for java_exc in _java_exceptions(exc): + message = java_exc.getMessage() + chain.append( + ( + str(java_exc.getClass().getName()), + None if message is None else str(message), + ) + ) + except Exception: # nosec B110 - building an error must never fail + pass + return tuple(chain) + + class ArcadeDBError(Exception): """Base exception for ArcadeDB errors. When raised from a Java exception, ``str()`` also names the Java root cause: the engine often wraps the reason (for example "is locked by another process") in a generic outer exception. + + What a program or a model reads to repair its statement or call: + + * ``code``: a short stable name of the cause (``"duplicate_key"``, + ``"record_not_found"``, ``"transaction_not_begun"``, ...), or + ``"unknown"`` for a failure that the table of codes does not know. + * ``hint``: one sentence on what to do next, or None for ``"unknown"``. + * ``cause``: the name of the Java exception class that decided the code + (the root cause of the Java chain for ``"unknown"``), or None when no + Java exception is involved. + * ``to_dict()``: those three, the class name and the message. + + ``str()`` of a classified error is ``[code] hint`` followed by the text + that ``str()`` had before (the Java class and message stay at its end). + An unknown error prints exactly that older text. + + ``ArcadeDBError(text)`` picks the subclass itself, from the Java + exception being handled (or, with none, from the class names and the + wording in ``text``), so ``except DuplicateKeyError`` works for every + raise site. Both builds give the same class and code for the same + failure. """ - def __str__(self): + code = "unknown" + hint = None + cause = None + _chain = () + _args = None + + def __new__(cls, *args, **kwargs): + normalized = None + if cls is ArcadeDBError: + text = str(args[0]) if args else "" + try: + handled = sys.exc_info()[1] + if isinstance(handled, ArcadeDBError) and handled.hint: + # a wrapper that prints the error it caught ("Failed to X: {e}") gets its text without the head, + # which the new error adds itself + shown = str(handled) + if shown in text: + text = text.replace(shown, handled._text()) + args = (text,) + args[1:] + normalized = args + chain = _java_chain_of(handled) + rule, cause = _classify(text, chain) + except Exception: # nosec B110 - building an error must never fail + chain, rule, cause = (), None, None + target = ArcadeDBError if rule is None else rule.cls + else: + chain, cause = (), None + rule = _RULE_OF_CODE.get(cls.code) + target = cls + self = super().__new__(target, *args, **kwargs) + self._decorate(rule, cause, chain) + self._args = normalized + return self + + def __init__(self, *args, **kwargs): + # the call that built the error passes its own arguments again; a wrapper's text without the head replaces them + super().__init__(*(self._args if self._args is not None else args), **kwargs) + + def _decorate(self, rule, cause, chain): + self._chain = chain + if rule is not None: + self.code = rule.code + self.hint = rule.hint + self.cause = cause + + @classmethod + def _classified(cls, text, chain): + """The error for ``text`` and a Java chain that arrived as data (the native build's reply).""" + chain = tuple((str(name), message) for name, message in chain) + rule, cause = _classify(text, chain) + target = ArcadeDBError if rule is None else rule.cls + exc = Exception.__new__(target, text) + Exception.__init__(exc, text) + exc._decorate(rule, cause, chain) + return exc + + def to_dict(self): + """``{"type", "code", "hint", "cause", "message"}``: the class name, the three attributes and the text without the head.""" + return { + "type": type(self).__name__, + "code": self.code, + "hint": self.hint, + "cause": self.cause, + "message": self._text(), + } + + def _text(self): text = super().__str__() chain = getattr(self, "java_chain", None) if chain and len(chain) > 1: @@ -146,3 +266,303 @@ def __str__(self): except Exception: # nosec B110 - never let str() of an error fail pass return text + + def __str__(self): + text = self._text() + if self.hint is None: + return text + return f"[{self.code}] {self.hint} {text}" + + +class DuplicateKeyError(ArcadeDBError): + """A unique index already holds the key (``duplicate_key``).""" + + code = "duplicate_key" + + +class RecordNotFoundError(ArcadeDBError): + """No record has the RID (``record_not_found``).""" + + code = "record_not_found" + + +class TransactionError(ArcadeDBError): + """A transaction call was made in the wrong state (``transaction_not_begun``).""" + + code = "transaction_not_begun" + + +class DatabaseExistsError(ArcadeDBError): + """``create_database`` found a database at the path (``database_exists``).""" + + code = "database_exists" + + +class DatabaseNotFoundError(ArcadeDBError): + """``open_database`` found no database at the path (``database_not_found``).""" + + code = "database_not_found" + + +class DatabaseLockedError(ArcadeDBError): + """Another process has the database open (``database_locked``).""" + + code = "database_locked" + + +class DatabaseClosedError(ArcadeDBError): + """The call needs an open database and this one was closed (``database_closed``).""" + + code = "database_closed" + + +class QuerySyntaxError(ArcadeDBError): + """The statement does not parse (``syntax_error``).""" + + code = "syntax_error" + + +class QueryTimeoutError(ArcadeDBError): + """The statement ran past its TIMEOUT clause (``timeout``).""" + + code = "timeout" + + +class ConflictError(ArcadeDBError): + """Another transaction changed the same data first, so a retry can succeed (``conflict``).""" + + code = "conflict" + + +class SchemaError(ArcadeDBError): + """A type, property or index is missing, exists already, or refuses the change (``type_not_found``, ``already_exists``, ``schema``).""" + + code = "schema" + + +class ValidationError(ArcadeDBError): + """A record broke a property constraint or a value has the wrong type (``validation``, ``type_mismatch``).""" + + code = "validation" + + +class _Rule(NamedTuple): + """One row of the table of codes. + + A rule matches when one of its ``java`` class names is in the Java chain of the error (``java`` empty: any chain) and its + ``message`` pattern is found in the text of the error or in a message of the chain (``message`` None: any text). The first + rule that matches decides, so a row with a general condition comes after the rows with a narrower one. + """ + + code: str + cls: type + hint: str + java: Tuple[str, ...] = () + message: Optional["re.Pattern"] = None + + +_E = "com.arcadedb.exception." + +_HINT_RECORD_NOT_FOUND = ( + "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)." +) +_HINT_DATABASE_CLOSED = ( + "The database was closed: open it again with `open_database(path)`, and read what you need from a " + "result before you close the database." +) +_HINT_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`." +) +_HINT_SCHEMA = ( + "The schema does not allow this change: read the message, and compare it with the current " + "schema (`SELECT FROM schema:types`)." +) + +# The table that decides the class, the code and the hint of every error. The Java names and the texts are the ones the engine +# produces, collected by running both builds (tests/test_error_codes_table.py holds a literal for every row). A row with a +# ``message`` and no ``java`` is for a failure that the Python layer raises itself or that one build words differently. +_RULES = ( + _Rule( + "duplicate_key", + DuplicateKeyError, + "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).", + java=(_E + "DuplicatedKeyException",), + ), + _Rule( + "record_not_found", + RecordNotFoundError, + _HINT_RECORD_NOT_FOUND, + java=(_E + "RecordNotFoundException", _E + "VertexNotFoundException"), + ), + _Rule( + "transaction_not_begun", + TransactionError, + "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.", + java=(_E + "TransactionException",), + message=re.compile(r"Transaction not begun"), + ), + _Rule( + "database_locked", + DatabaseLockedError, + "Another process has this database open: close it there first, because only one process can " + "open a database at a time.", + java=("com.arcadedb.utility.LockException",), + ), + _Rule( + "database_exists", + DatabaseExistsError, + "A database already exists at this path: open it with `open_database(path)`, or choose another path.", + java=(_E + "DatabaseOperationException",), + message=re.compile(r"already exists"), + ), + _Rule( + "database_not_found", + DatabaseNotFoundError, + "No database exists at this path: check the path, or create one with `create_database(path)`.", + java=(_E + "DatabaseNotFoundException",), + ), + _Rule( + "database_closed", + DatabaseClosedError, + _HINT_DATABASE_CLOSED, + java=(_E + "DatabaseIsClosedException",), + ), + _Rule( + "database_read_only", + ArcadeDBError, + "The database was opened with `read_only=True`: open it again without that argument to write.", + java=(_E + "DatabaseIsReadOnlyException",), + ), + _Rule( + "syntax_error", + QuerySyntaxError, + "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.", + java=(_E + "CommandSQLParsingException", _E + "CommandParsingException"), + ), + _Rule( + "timeout", + QueryTimeoutError, + "The statement ran past its TIMEOUT clause: add a filter, a LIMIT or an index so that it " + "finishes sooner, or raise the timeout.", + java=(_E + "TimeoutException", _E + "PartialResultTimeoutException"), + ), + _Rule( + "conflict", + ConflictError, + "Another transaction changed the same data first: run the whole transaction again, for example " + "with `db.run_in_transaction(fn)`, which retries it.", + java=( + _E + "ConcurrentModificationException", + _E + "LockTimeoutException", + _E + "NeedRetryException", + ), + ), + _Rule( + "type_not_found", + SchemaError, + _HINT_TYPE_NOT_FOUND, + java=(_E + "SchemaException",), + message=re.compile(r"Type with name '[^']*' was not found"), + ), + _Rule( + "already_exists", + SchemaError, + "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.", + java=(_E + "AlreadyExistsException", _E + "TypeAlreadyExistsException"), + ), + _Rule( + "schema", + SchemaError, + _HINT_SCHEMA, + java=(_E + "SchemaException",), + ), + _Rule( + "type_mismatch", + ValidationError, + "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).", + java=("java.lang.IllegalArgumentException", _E + "TypeMismatchException"), + message=re.compile(r"Cannot convert type"), + ), + _Rule( + "validation", + ValidationError, + "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.", + java=(_E + "ValidationException",), + ), + _Rule( + "query_not_idempotent", + ArcadeDBError, + "`db.query` runs reads only: send a statement that changes data with `db.command`.", + java=(_E + "QueryNotIdempotentException",), + ), + _Rule( + "missing_parameter", + ArcadeDBError, + "The statement has a parameter that was not passed: give a value for each `?` in order, or " + "pass a dict that holds every `:name`.", + java=(_E + "CommandParameterMissingException",), + ), + # Rows that match a text only come last: a statement that a syntax error echoes can hold any words, so a class decides first. + _Rule( + "record_not_found", + RecordNotFoundError, + _HINT_RECORD_NOT_FOUND, + message=re.compile(r"\brecord not found\b"), + ), + _Rule( + "database_closed", + DatabaseClosedError, + _HINT_DATABASE_CLOSED, + message=re.compile(r"^Database is closed"), + ), + _Rule( + "type_not_found", + SchemaError, + _HINT_TYPE_NOT_FOUND, + message=re.compile(r"\bType '[^']*' does not exist|\bthe type does not exist"), + ), + _Rule( + "schema", + SchemaError, + _HINT_SCHEMA, + message=re.compile(r"Property '[^']*' not found on class|Index not found: "), + ), +) + +_RULE_OF_CODE = {} +for _rule in _RULES: + _RULE_OF_CODE.setdefault(_rule.code, _rule) +del _rule + +# A Java class name inside a text, for an error that has no Java chain (the Python layer words some errors like the JVM build: +# "Failed to save record: com.arcadedb.exception.TransactionException: Transaction not begun") +_CLASS_IN_TEXT = re.compile( + r"\b((?:com|org|java)\.(?:[A-Za-z0-9_$]+\.)*[A-Za-z0-9_$]*(?:Exception|Error))\b" +) + + +def _classify(text, chain=()): + """``(rule, cause)`` for an error with this ``text`` and Java ``chain``: the first matching row, or ``(None, root cause)``.""" + names = [name for name, _ in chain] or _CLASS_IN_TEXT.findall(text) + messages = [message for _, message in chain if message] + messages.append(text) + for rule in _RULES: + hit = None + if rule.java: + hit = next((name for name in names if name in rule.java), None) + if hit is None: + continue + if rule.message is not None and not any( + rule.message.search(message) for message in messages + ): + continue + return rule, hit or (names[-1] if names else None) + return None, (names[-1] if names else None) diff --git a/tests/test_docs_errors_page.py b/tests/test_docs_errors_page.py new file mode 100644 index 0000000..53bd793 --- /dev/null +++ b/tests/test_docs_errors_page.py @@ -0,0 +1,60 @@ +"""Every Python block of the Antora page ``docs/modules/ROOT/pages/how-to/errors.adoc`` runs, and prints what the page says. + +Same pattern as ``test_docs_vectors_page.py``: the blocks are chained on purpose, they run in the order of the page, in one +namespace, against one fresh temporary database that the namespace holds as ``db``. A block that is followed by a +``[source,text]`` block must print exactly that text. What each code of the table claims is pinned on its own in +``test_error_codes_parity.py``. The test uses no Java object, so it runs on the JVM build and the native build alike. +""" + +import contextlib +import io +import re +from pathlib import Path + +PAGE = ( + Path(__file__).resolve().parents[1] + / "docs" + / "modules" + / "ROOT" + / "pages" + / "how-to" + / "errors.adoc" +) + +# a Python listing, then (optionally, directly after it) the text listing with its output +BLOCK_RE = re.compile( + r"\[source,python[^\]\n]*\]\n----\n(?P.*?)\n----\n" + r"(?:\n\[source,text\]\n----\n(?P.*?)\n----\n)?", + re.DOTALL, +) + + +def _blocks(): + text = PAGE.read_text(encoding="utf-8") + found = [(m.group("code"), m.group("out")) for m in BLOCK_RE.finditer(text)] + # no Python listing may escape the extraction (a different spelling of the block header would run nowhere) + assert text.count("[source,python") == len(found) + return found + + +def test_the_page_has_its_blocks(): + blocks = _blocks() + assert len(blocks) == 3 + assert sum(1 for _, out in blocks if out is not None) == 3 + + +def test_every_block_runs_in_order_and_prints_what_the_page_says(temp_db): + namespace = {"db": temp_db, "__name__": "errors_page"} + for number, (code, expected) in enumerate(_blocks(), start=1): + captured = io.StringIO() + compiled = compile(code, f"errors.adoc python block {number}", "exec") + with contextlib.redirect_stdout(captured): + exec(compiled, namespace) # nosec B102 - the page of this repository + if expected is not None: + assert ( + captured.getvalue().strip() == expected.strip() + ), f"block {number} printed other text than the page shows:\n{code}" + else: + assert ( + captured.getvalue() == "" + ), f"block {number} prints, the page shows no output" diff --git a/tests/test_error_codes_parity.py b/tests/test_error_codes_parity.py new file mode 100644 index 0000000..548fb32 --- /dev/null +++ b/tests/test_error_codes_parity.py @@ -0,0 +1,579 @@ +"""Live failures give the same class and code on both builds (ArcadeData/arcadedb-python#475). + +Same pattern as ``test_cross_wheel_golden.py``: there is no branch on ``arcadedb.__backend__`` here, and the literals below are +asserted on ``arcadedb`` (native) and on ``arcadedb-jvm`` alike, so a literal that holds on both IS the parity check. Each scenario +makes the engine fail the way an agent's statement fails and checks the class, the ``code``, the ``cause`` and the text of the +error. A ``cause`` of ``None`` in the table means that it is not compared: the two builds word those failures differently (the +native build's engine reports ``CommandExecutionException`` where the JVM build's reports ``SchemaException``, and the Python +layer of the native build raises the missing record itself), and the class and the code are the same all the same. +""" + +import json +import subprocess # nosec B404 - test-controlled child process +import sys +import threading + +import pytest + +import arcadedb +from arcadedb import ArcadeDBError + +E = "com.arcadedb.exception." + + +def _db(tmp_path, name="db"): + """A database with a document type T (unique ``id``), a vertex type V and an edge type E. Writes use ``db.transaction()``.""" + db = arcadedb.create_database(str(tmp_path / name)) + db.command("sql", "CREATE DOCUMENT TYPE T") + db.command("sql", "CREATE PROPERTY T.id INTEGER") + db.command("sql", "CREATE INDEX ON T (id) UNIQUE") + db.command("sql", "CREATE VERTEX TYPE V") + db.command("sql", "CREATE EDGE TYPE E") + return db + + +def _insert(db, value=1): + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = ?", value) + + +# ------------------------------------------------------------------------------------------------------ the scenarios +# Each one takes the temporary directory, runs with a database that it closes itself, and must raise. + + +def open_missing(tmp_path): + arcadedb.open_database(str(tmp_path / "missing")) + + +def create_existing(tmp_path): + arcadedb.create_database(str(tmp_path / "db")).close() + arcadedb.create_database(str(tmp_path / "db")) + + +def read_only_write(tmp_path): + db = _db(tmp_path) + db.close() + with arcadedb.open_database(str(tmp_path / "db"), read_only=True) as ro: + with ro.transaction(): + ro.command("sql", "INSERT INTO T SET id = 1") + + +def on_a_database(action): + def scenario(tmp_path): + with _db(tmp_path) as db: + action(db) + + scenario.__name__ = action.__name__ + return scenario + + +def sql_syntax_query(db): + db.query("sql", "SELEC FROM T").to_list() + + +def sql_syntax_command(db): + db.command("sql", "SELEC FROM T") + + +def cypher_syntax(db): + db.query("opencypher", "MATC (n) RETURN n").to_list() + + +def duplicate_in_transaction(db): + _insert(db) + _insert(db) + + +def duplicate_in_one_transaction(db): + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 1") + db.command("sql", "INSERT INTO T SET id = 1") + + +def duplicate_with_auto_transaction(db): + db.set_auto_transaction(True) + db.command("sql", "INSERT INTO T SET id = 1") + db.command("sql", "INSERT INTO T SET id = 1") + + +def duplicate_in_insert_many(db): + db.insert_many("T", [{"id": 1}, {"id": 1}]) + + +def duplicate_in_save(db): + _insert(db) + with db.transaction(): + document = db.new_document("T") + document.set("id", 1) + document.save() + + +def lookup_missing_rid(db): + db.lookup_by_rid("#9:9") + + +def lookup_deleted_record(db): + _insert(db) + rid = db.query("sql", "SELECT FROM T").first().get_rid() + with db.transaction(): + db.command("sql", "DELETE FROM T") + db.lookup_by_rid(rid) + + +def edge_between_missing_records(db): + with db.transaction(): + db.command("sql", "CREATE EDGE E FROM #9:9 TO #9:8") + + +def write_in_strict_mode(db): + db.set_auto_transaction(False) + db.command("sql", "INSERT INTO T SET id = 1") + + +def save_in_strict_mode(db): + db.set_auto_transaction(False) + document = db.new_document("T") + document.set("id", 1) + document.save() + + +def commit_with_nothing_open(db): + db.commit() + + +def query_after_close(db): + db.close() + db.query("sql", "SELECT FROM T") + + +def command_after_close(db): + db.close() + db.command("sql", "CREATE DOCUMENT TYPE Q") + + +def timeout_of_a_query(db): + db.insert_many("T", [{"id": i + 10} for i in range(200_000)]) + db.query( + "sql", "SELECT count(*) FROM T WHERE (id * id) % 7 = 3 TIMEOUT 1 EXCEPTION" + ).to_list() + + +def timeout_of_a_command(db): + db.insert_many("T", [{"id": i + 10} for i in range(200_000)]) + with db.transaction(): + db.command("sql", "UPDATE T SET k = id + 1 TIMEOUT 1 EXCEPTION") + + +def conflict_of_two_transactions(db): + _insert(db) + errors = [] + barrier = threading.Barrier(2, timeout=60) + + def slow_writer(): + try: + with db.transaction(): + db.command("sql", "UPDATE T SET k = 2 WHERE id = 1") + barrier.wait() # the other writer commits now + barrier.wait() + except BaseException as e: # noqa: BLE001 - handed to the main thread + errors.append(e) + + thread = threading.Thread(target=slow_writer) + thread.start() + barrier.wait() + try: + with db.transaction(): + db.command("sql", "UPDATE T SET k = 3 WHERE id = 1") + finally: + barrier.wait() + thread.join(timeout=60) + if errors: + raise errors[0] + + +def unknown_type_in_query(db): + db.query("sql", "SELECT FROM Nope").to_list() + + +def unknown_type_in_insert(db): + with db.transaction(): + db.command("sql", "INSERT INTO Nope SET a = 1") + + +def drop_unknown_type(db): + db.command("sql", "DROP TYPE Nope") + + +def create_a_type_twice(db): + db.command("sql", "CREATE DOCUMENT TYPE T") + + +def create_a_property_twice(db): + db.command("sql", "CREATE PROPERTY T.id INTEGER") + + +def create_an_index_twice(db): + db.command("sql", "CREATE INDEX ON T (id) UNIQUE") + + +def index_on_a_missing_property(db): + db.command("sql", "CREATE INDEX ON T (nothere) NOTUNIQUE") + + +def drop_a_missing_property(db): + db.command("sql", "DROP PROPERTY T.nope") + + +def drop_a_missing_index(db): + db.command("sql", "DROP INDEX `nope[x]`") + + +def mandatory_property_missing(db): + db.command("sql", "CREATE PROPERTY T.m STRING (mandatory true)") + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 1") + + +def not_null_property_null(db): + db.command("sql", "CREATE PROPERTY T.m STRING (notnull true)") + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 1, m = null") + + +def property_above_max(db): + db.command("sql", "CREATE PROPERTY T.k INTEGER (max 5)") + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 1, k = 50") + + +def readonly_property_changed(db): + db.command("sql", "CREATE PROPERTY T.r STRING (readonly true)") + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 1, r = 'a'") + with db.transaction(): + db.command("sql", "UPDATE T SET r = 'b'") + + +def text_for_an_integer(db): + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 'abc'") + + +def write_through_query(db): + db.query("sql", "INSERT INTO T SET id = 1") + + +def parameter_not_passed(db): + db.query("sql", "SELECT FROM T WHERE id = :x", {}).to_list() + + +def unknown_query_language(db): + db.query("nolang", "SELECT FROM T") + + +def unknown_property_type(db): + db.command("sql", "CREATE PROPERTY T.z FOOBAR") + + +def division_by_zero(db): + db.query("sql", "SELECT 1/0 AS x").to_list() + + +def unknown_function(db): + db.query("sql", "SELECT nosuchfn(1) AS x").to_list() + + +# (scenario, expected class name, expected code, expected cause; None: the cause is not compared, see the docstring) +SCENARIOS = [ + ( + open_missing, + "DatabaseNotFoundError", + "database_not_found", + E + "DatabaseNotFoundException", + ), + ( + create_existing, + "DatabaseExistsError", + "database_exists", + E + "DatabaseOperationException", + ), + ( + read_only_write, + "ArcadeDBError", + "database_read_only", + E + "DatabaseIsReadOnlyException", + ), + ( + on_a_database(sql_syntax_query), + "QuerySyntaxError", + "syntax_error", + E + "CommandSQLParsingException", + ), + ( + on_a_database(sql_syntax_command), + "QuerySyntaxError", + "syntax_error", + E + "CommandSQLParsingException", + ), + ( + on_a_database(cypher_syntax), + "QuerySyntaxError", + "syntax_error", + E + "CommandParsingException", + ), + ( + on_a_database(duplicate_in_transaction), + "DuplicateKeyError", + "duplicate_key", + E + "DuplicatedKeyException", + ), + ( + on_a_database(duplicate_in_one_transaction), + "DuplicateKeyError", + "duplicate_key", + E + "DuplicatedKeyException", + ), + ( + on_a_database(duplicate_with_auto_transaction), + "DuplicateKeyError", + "duplicate_key", + E + "DuplicatedKeyException", + ), + ( + on_a_database(duplicate_in_insert_many), + "DuplicateKeyError", + "duplicate_key", + E + "DuplicatedKeyException", + ), + ( + on_a_database(duplicate_in_save), + "DuplicateKeyError", + "duplicate_key", + E + "DuplicatedKeyException", + ), + ( + on_a_database(lookup_missing_rid), + "RecordNotFoundError", + "record_not_found", + None, + ), + ( + on_a_database(lookup_deleted_record), + "RecordNotFoundError", + "record_not_found", + None, + ), + ( + on_a_database(edge_between_missing_records), + "RecordNotFoundError", + "record_not_found", + E + "RecordNotFoundException", + ), + ( + on_a_database(write_in_strict_mode), + "TransactionError", + "transaction_not_begun", + E + "TransactionException", + ), + ( + on_a_database(save_in_strict_mode), + "TransactionError", + "transaction_not_begun", + E + "TransactionException", + ), + ( + on_a_database(commit_with_nothing_open), + "TransactionError", + "transaction_not_begun", + E + "TransactionException", + ), + (on_a_database(query_after_close), "DatabaseClosedError", "database_closed", None), + ( + on_a_database(command_after_close), + "DatabaseClosedError", + "database_closed", + None, + ), + ( + on_a_database(timeout_of_a_query), + "QueryTimeoutError", + "timeout", + E + "TimeoutException", + ), + ( + on_a_database(timeout_of_a_command), + "QueryTimeoutError", + "timeout", + E + "TimeoutException", + ), + ( + on_a_database(conflict_of_two_transactions), + "ConflictError", + "conflict", + E + "ConcurrentModificationException", + ), + ( + on_a_database(unknown_type_in_query), + "SchemaError", + "type_not_found", + E + "SchemaException", + ), + ( + on_a_database(unknown_type_in_insert), + "SchemaError", + "type_not_found", + E + "SchemaException", + ), + ( + on_a_database(drop_unknown_type), + "SchemaError", + "type_not_found", + E + "SchemaException", + ), + ( + on_a_database(create_a_type_twice), + "SchemaError", + "already_exists", + E + "AlreadyExistsException", + ), + ( + on_a_database(create_a_property_twice), + "SchemaError", + "already_exists", + E + "AlreadyExistsException", + ), + ( + on_a_database(create_an_index_twice), + "SchemaError", + "already_exists", + E + "AlreadyExistsException", + ), + ( + on_a_database(index_on_a_missing_property), + "SchemaError", + "schema", + E + "SchemaException", + ), + (on_a_database(drop_a_missing_property), "SchemaError", "schema", None), + (on_a_database(drop_a_missing_index), "SchemaError", "schema", None), + ( + on_a_database(mandatory_property_missing), + "ValidationError", + "validation", + E + "ValidationException", + ), + ( + on_a_database(not_null_property_null), + "ValidationError", + "validation", + E + "ValidationException", + ), + ( + on_a_database(property_above_max), + "ValidationError", + "validation", + E + "ValidationException", + ), + ( + on_a_database(readonly_property_changed), + "ValidationError", + "validation", + E + "ValidationException", + ), + ( + on_a_database(text_for_an_integer), + "ValidationError", + "type_mismatch", + "java.lang.IllegalArgumentException", + ), + ( + on_a_database(write_through_query), + "ArcadeDBError", + "query_not_idempotent", + E + "QueryNotIdempotentException", + ), + ( + on_a_database(parameter_not_passed), + "ArcadeDBError", + "missing_parameter", + E + "CommandParameterMissingException", + ), + # failures that the table does not know stay ArcadeDBError with the code unknown, with the same text as before + ( + on_a_database(unknown_query_language), + "ArcadeDBError", + "unknown", + "java.lang.IllegalArgumentException", + ), + ( + on_a_database(unknown_property_type), + "ArcadeDBError", + "unknown", + "java.lang.IllegalArgumentException", + ), + ( + on_a_database(division_by_zero), + "ArcadeDBError", + "unknown", + E + "ArithmeticErrorException", + ), + (on_a_database(unknown_function), "ArcadeDBError", "unknown", None), +] + + +@pytest.mark.parametrize("row", SCENARIOS, ids=[row[0].__name__ for row in SCENARIOS]) +def test_a_failure_has_the_same_class_code_and_cause_on_both_builds(tmp_path, row): + scenario, class_name, code, cause = row + with pytest.raises(ArcadeDBError) as caught: + scenario(tmp_path) + error = caught.value + assert (type(error).__name__, error.code) == (class_name, code) + if cause is not None: + assert error.cause == cause + assert cause in str(error) # the Java text stays in the message + if code == "unknown": + assert error.hint is None + assert not str(error).startswith("[") + else: + assert error.hint + assert str(error).startswith(f"[{code}] {error.hint} ") + data = error.to_dict() + assert json.loads(json.dumps(data)) == data + assert data["code"] == code and data["type"] == class_name + + +def test_every_code_of_the_table_but_the_lock_is_reached_by_a_live_failure_here(): + """A row of the table that no scenario reaches would be checked by a literal only: this lists what is left.""" + from arcadedb import exceptions + + live = {row[2] for row in SCENARIOS} | {"database_locked"} + assert {rule.code for rule in exceptions._RULES} <= live + + +# ---------------------------------------------------------------------------------------- a second process holds the lock + +CHILD = """ +import sys +import arcadedb + +try: + arcadedb.open_database(sys.argv[1]) +except arcadedb.ArcadeDBError as e: + print(type(e).__name__, e.code, e.cause) +""" + + +def test_a_database_that_another_process_has_open_is_locked(tmp_path): + with arcadedb.create_database(str(tmp_path / "db")): + done = subprocess.run( # nosec B603 - fixed argv, no shell, test-owned + [sys.executable, "-c", CHILD, str(tmp_path / "db")], + capture_output=True, + text=True, + timeout=300, + check=False, + ) + assert done.stdout.split() == [ + "DatabaseLockedError", + "database_locked", + "com.arcadedb.utility.LockException", + ], (done.stdout, done.stderr[-500:]) diff --git a/tests/test_error_codes_table.py b/tests/test_error_codes_table.py new file mode 100644 index 0000000..1f8e86e --- /dev/null +++ b/tests/test_error_codes_table.py @@ -0,0 +1,575 @@ +"""The table of error codes (ArcadeData/arcadedb-python#475): one literal per row, run on both builds. + +``arcadedb.exceptions._RULES`` decides the class, the ``code``, the ``hint`` and the ``cause`` of an ``ArcadeDBError``. Each literal +below is an error text, with the Java chain behind it, that the engine produces (collected by running both builds, see +``test_error_codes_parity.py`` for the live failures). ``test_every_row_of_the_table_has_a_literal`` fails when a row is added +without one. No database is opened here, so the file runs on the JVM build and the native build alike. +""" + +import copy +import pickle # nosec B403 - a round trip of an object this test built +import re +from pathlib import Path + +import pytest + +import arcadedb +from arcadedb import exceptions +from arcadedb.exceptions import ArcadeDBError, _classify + +E = "com.arcadedb.exception." + +# (id, text of the error, Java chain (outermost first), expected class, expected code, expected cause) +CASES = [ + ( + "duplicate_key", + "Command failed: com.arcadedb.exception.DuplicatedKeyException: Duplicated key [1] found on index 'T[id]' already assigned to record #1:0", + [ + ( + E + "DuplicatedKeyException", + "Duplicated key [1] found on index 'T[id]' already assigned to record #1:0", + ) + ], + "DuplicateKeyError", + "duplicate_key", + E + "DuplicatedKeyException", + ), + ( + "record_not_found_class", + "Failed to lookup RID '#9:9': com.arcadedb.exception.RecordNotFoundException: Record #9:9 not found", + [(E + "RecordNotFoundException", "Record #9:9 not found")], + "RecordNotFoundError", + "record_not_found", + E + "RecordNotFoundException", + ), + ( + "record_not_found_vertex", + "Command failed: com.arcadedb.exception.VertexNotFoundException: Vertex #9:9 not found", + [(E + "VertexNotFoundException", "Vertex #9:9 not found")], + "RecordNotFoundError", + "record_not_found", + E + "VertexNotFoundException", + ), + ( + "record_not_found_text", + "Failed to lookup RID '#9:9': record not found", + [], + "RecordNotFoundError", + "record_not_found", + None, + ), + ( + "transaction_not_begun", + "Command failed: com.arcadedb.exception.TransactionException: Transaction not begun", + [(E + "TransactionException", "Transaction not begun")], + "TransactionError", + "transaction_not_begun", + E + "TransactionException", + ), + ( + "transaction_not_begun_text", + "Failed to save record: com.arcadedb.exception.TransactionException: Transaction not begun (wrap the write in `with db.transaction():` or call begin() first)", + [], + "TransactionError", + "transaction_not_begun", + E + "TransactionException", + ), + ( + "database_locked", + "Failed to open database: com.arcadedb.exception.DatabaseOperationException: Error on creating new database instance", + [ + ( + E + "DatabaseOperationException", + "Error on creating new database instance", + ), + ( + "com.arcadedb.utility.LockException", + "Database 'db19' is locked by another process (path=/tmp/db19)", + ), + ], + "DatabaseLockedError", + "database_locked", + "com.arcadedb.utility.LockException", + ), + ( + "database_exists", + "Failed to create database: com.arcadedb.exception.DatabaseOperationException: Database '/tmp/db7' already exists", + [(E + "DatabaseOperationException", "Database '/tmp/db7' already exists")], + "DatabaseExistsError", + "database_exists", + E + "DatabaseOperationException", + ), + ( + "database_not_found", + "Failed to open database: com.arcadedb.exception.DatabaseNotFoundException: Database '/tmp/db21' does not exist", + [(E + "DatabaseNotFoundException", "Database '/tmp/db21' does not exist")], + "DatabaseNotFoundError", + "database_not_found", + E + "DatabaseNotFoundException", + ), + ( + "database_closed_class", + "Command failed: com.arcadedb.exception.DatabaseIsClosedException: Database 'db' is closed", + [(E + "DatabaseIsClosedException", "Database 'db' is closed")], + "DatabaseClosedError", + "database_closed", + E + "DatabaseIsClosedException", + ), + ( + "database_closed_text", + "Database is closed", + [], + "DatabaseClosedError", + "database_closed", + None, + ), + ( + "database_read_only", + "Command failed: com.arcadedb.exception.DatabaseIsReadOnlyException: Cannot execute command on a read only database", + [ + ( + E + "DatabaseIsReadOnlyException", + "Cannot execute command on a read only database", + ) + ], + "ArcadeDBError", + "database_read_only", + E + "DatabaseIsReadOnlyException", + ), + ( + "syntax_error_sql", + "Query failed: com.arcadedb.exception.CommandSQLParsingException: SQL syntax error at line 1, column 0: no viable alternative at input 'SELEC'", + [ + ( + E + "CommandSQLParsingException", + "SQL syntax error at line 1, column 0: no viable alternative at input 'SELEC'", + ) + ], + "QuerySyntaxError", + "syntax_error", + E + "CommandSQLParsingException", + ), + ( + "syntax_error_cypher", + "Query failed: com.arcadedb.exception.CommandParsingException: Syntax error at line 1:0 - mismatched input 'MATC', expected: an expression", + [ + ( + E + "CommandParsingException", + "Syntax error at line 1:0 - mismatched input 'MATC', expected: an expression", + ), + ("org.antlr.v4.runtime.InputMismatchException", None), + ], + "QuerySyntaxError", + "syntax_error", + E + "CommandParsingException", + ), + ( + "timeout", + "Query failed: com.arcadedb.exception.TimeoutException: the command exceeded the TIMEOUT clause of 1ms", + [(E + "TimeoutException", "the command exceeded the TIMEOUT clause of 1ms")], + "QueryTimeoutError", + "timeout", + E + "TimeoutException", + ), + ( + "timeout_partial", + "Query failed: com.arcadedb.exception.PartialResultTimeoutException: partial result", + [(E + "PartialResultTimeoutException", "partial result")], + "QueryTimeoutError", + "timeout", + E + "PartialResultTimeoutException", + ), + ( + "conflict", + "Failed to commit transaction: com.arcadedb.exception.ConcurrentModificationException: Slot rebase not possible on page PageId(db6/1/0) slot 0 (concurrent change to the same record). Please retry the operation", + [ + ( + E + "ConcurrentModificationException", + "Slot rebase not possible on page PageId(db6/1/0) slot 0 (concurrent change to the same record). Please retry the operation", + ) + ], + "ConflictError", + "conflict", + E + "ConcurrentModificationException", + ), + ( + "conflict_lock_timeout", + "Command failed: com.arcadedb.exception.LockTimeoutException: Timeout on locking resource", + [(E + "LockTimeoutException", "Timeout on locking resource")], + "ConflictError", + "conflict", + E + "LockTimeoutException", + ), + ( + "conflict_need_retry", + "Command failed: com.arcadedb.exception.NeedRetryException: retry", + [(E + "NeedRetryException", "retry")], + "ConflictError", + "conflict", + E + "NeedRetryException", + ), + ( + "type_not_found_class", + "Query failed: com.arcadedb.exception.SchemaException: Type with name 'Nope' was not found", + [(E + "SchemaException", "Type with name 'Nope' was not found")], + "SchemaError", + "type_not_found", + E + "SchemaException", + ), + ( + "type_not_found_text", + "Cannot load into 'Nope': the type does not exist (create it first)", + [], + "SchemaError", + "type_not_found", + None, + ), + ( + "already_exists", + "Command failed: com.arcadedb.exception.AlreadyExistsException: Type T already exists", + [(E + "AlreadyExistsException", "Type T already exists")], + "SchemaError", + "already_exists", + E + "AlreadyExistsException", + ), + ( + "already_exists_type", + "Command failed: com.arcadedb.exception.TypeAlreadyExistsException: Cannot create type 'T' because already exists", + [ + ( + E + "TypeAlreadyExistsException", + "Cannot create type 'T' because already exists", + ) + ], + "SchemaError", + "already_exists", + E + "TypeAlreadyExistsException", + ), + ( + "schema_class", + "Command failed: com.arcadedb.exception.SchemaException: Cannot create the index on type 'T.nothere' because the property does not exist", + [ + ( + E + "SchemaException", + "Cannot create the index on type 'T.nothere' because the property does not exist", + ) + ], + "SchemaError", + "schema", + E + "SchemaException", + ), + ( + "schema_text_native_property", + "Command failed: com.arcadedb.exception.CommandExecutionException: Property 'nope' not found on class T", + [(E + "CommandExecutionException", "Property 'nope' not found on class T")], + "SchemaError", + "schema", + E + "CommandExecutionException", + ), + ( + "schema_text_native_index", + "Command failed: com.arcadedb.exception.CommandExecutionException: Index not found: nope[x]", + [(E + "CommandExecutionException", "Index not found: nope[x]")], + "SchemaError", + "schema", + E + "CommandExecutionException", + ), + ( + "type_mismatch", + "Command failed: java.lang.IllegalArgumentException: Cannot convert type 'class java.lang.String' to 'INTEGER' found in property 'id' (caused by java.lang.NumberFormatException)", + [ + ( + "java.lang.IllegalArgumentException", + "Cannot convert type 'class java.lang.String' to 'INTEGER' found in property 'id'", + ), + ("java.lang.NumberFormatException", 'For input string: "abc"'), + ], + "ValidationError", + "type_mismatch", + "java.lang.IllegalArgumentException", + ), + ( + "validation", + "Command failed: com.arcadedb.exception.ValidationException: The property 'T.m' is mandatory, but not found on record: @T[id=1]", + [ + ( + E + "ValidationException", + "The property 'T.m' is mandatory, but not found on record: @T[id=1]", + ) + ], + "ValidationError", + "validation", + E + "ValidationException", + ), + ( + "query_not_idempotent", + "Query failed: com.arcadedb.exception.QueryNotIdempotentException: Query 'INSERT INTO T SET id = 1' is not idempotent", + [ + ( + E + "QueryNotIdempotentException", + "Query 'INSERT INTO T SET id = 1' is not idempotent", + ) + ], + "ArcadeDBError", + "query_not_idempotent", + E + "QueryNotIdempotentException", + ), + ( + "missing_parameter", + "Query failed: com.arcadedb.exception.CommandParameterMissingException: Expected parameter(s): x", + [(E + "CommandParameterMissingException", "Expected parameter(s): x")], + "ArcadeDBError", + "missing_parameter", + E + "CommandParameterMissingException", + ), +] + + +def _ids(cases): + return [case[0] for case in cases] + + +@pytest.mark.parametrize("case", CASES, ids=_ids(CASES)) +def test_a_row_decides_class_code_and_cause(case): + _, text, chain, class_name, code, cause = case + rule, found = _classify(text, tuple(chain)) + assert rule is not None + assert (rule.cls.__name__, rule.code, found) == (class_name, code, cause) + + +@pytest.mark.parametrize("case", CASES, ids=_ids(CASES)) +def test_the_same_failure_with_and_without_the_chain_gives_the_same_class_and_code( + case, +): + """The JVM build hands the chain of the Java exception, the native build the chain of the reply, a text-only error neither.""" + _, text, chain, class_name, code, _ = case + from_chain = ArcadeDBError._classified(text, chain) + assert (type(from_chain).__name__, from_chain.code) == (class_name, code) + if ( + len(chain) <= 1 + ): # a text names the outer class only; the inner ones come with the chain + from_text = ArcadeDBError(text) + assert (type(from_text).__name__, from_text.code) == (class_name, code) + + +def test_every_row_of_the_table_has_a_literal(): + """A new row needs a literal above; a row that an earlier row hides is found here too.""" + hit = set() + for _, text, chain, _, _, _ in CASES: + rule, _ = _classify(text, tuple(chain)) + hit.add(id(rule)) + missing = [rule.code for rule in exceptions._RULES if id(rule) not in hit] + assert not missing, f"rows without a literal that reaches them: {missing}" + + +def test_a_row_names_a_class_of_this_module_and_a_hint_of_one_sentence(): + for rule in exceptions._RULES: + assert issubclass(rule.cls, ArcadeDBError) + assert re.fullmatch(r"[a-z]+(_[a-z]+)*", rule.code) + assert rule.hint.endswith(".") and "\n" not in rule.hint + assert rule.java or rule.message is not None, rule.code + assert chr(0x2014) not in rule.hint + + +def test_the_class_of_a_code_is_the_same_in_every_row_of_that_code(): + seen = {} + for rule in exceptions._RULES: + assert seen.setdefault(rule.code, (rule.cls, rule.hint)) == ( + rule.cls, + rule.hint, + ) + + +def test_a_failure_the_table_does_not_know_is_an_arcadedb_error_with_code_unknown(): + error = ArcadeDBError("Something odd happened") + assert type(error) is ArcadeDBError + assert (error.code, error.hint, error.cause) == ("unknown", None, None) + assert str(error) == "Something odd happened" + other = ArcadeDBError._classified( + "Command failed: com.arcadedb.exception.CommandExecutionException: boom", + [(E + "CommandExecutionException", "boom"), ("java.io.IOException", "disk")], + ) + assert type(other) is ArcadeDBError and other.code == "unknown" + assert other.cause == "java.io.IOException" + assert ( + str(other) + == "Command failed: com.arcadedb.exception.CommandExecutionException: boom" + ) + + +def test_a_transaction_exception_with_another_message_is_unknown(): + error = ArcadeDBError._classified( + "Command failed: com.arcadedb.exception.TransactionException: something else", + [(E + "TransactionException", "something else")], + ) + assert (type(error), error.code) == (ArcadeDBError, "unknown") + + +def test_no_arguments_and_a_non_text_argument_are_accepted(): + assert ArcadeDBError().code == "unknown" + assert ArcadeDBError(12).code == "unknown" + assert str(ArcadeDBError()) == "" + + +def test_str_keeps_the_old_text_as_its_tail_after_the_code_and_the_hint(): + text = "Command failed: com.arcadedb.exception.DuplicatedKeyException: Duplicated key [1] found on index 'T[id]' already assigned to record #1:0" + error = ArcadeDBError(text) + shown = str(error) + assert shown.startswith("[duplicate_key] " + error.hint + " ") + assert shown.endswith(text) + assert error.args == (text,) + assert not isinstance(error, (KeyError, ValueError)) + + +def test_the_old_caused_by_suffix_stays_in_the_tail(): + error = ArcadeDBError._classified( + "Failed to open database: x", [(E + "DatabaseOperationException", "outer")] + ) + error.java_chain = [ + (E + "DatabaseOperationException", "outer"), + ("com.arcadedb.utility.LockException", "locked"), + ] + assert str(error).endswith( + "Failed to open database: x (caused by com.arcadedb.utility.LockException: locked)" + ) + + +def test_to_dict_has_the_five_keys_and_is_plain_data(): + error = ArcadeDBError._classified( + "Command failed: com.arcadedb.exception.TransactionException: Transaction not begun", + [(E + "TransactionException", "Transaction not begun")], + ) + data = error.to_dict() + assert list(data) == ["type", "code", "hint", "cause", "message"] + assert data["type"] == "TransactionError" + assert data["code"] == "transaction_not_begun" + assert data["cause"] == E + "TransactionException" + assert ( + data["message"] + == "Command failed: com.arcadedb.exception.TransactionException: Transaction not begun" + ) + assert data["hint"] == error.hint + unknown = ArcadeDBError("odd").to_dict() + assert unknown == { + "type": "ArcadeDBError", + "code": "unknown", + "hint": None, + "cause": None, + "message": "odd", + } + + +def test_the_hint_for_a_missing_transaction_is_true_with_auto_transaction_on_and_off(): + hint = ArcadeDBError._classified( + "Command failed: com.arcadedb.exception.TransactionException: Transaction not begun", + [(E + "TransactionException", "Transaction not begun")], + ).hint + assert "with db.transaction():" in hint and "db.set_auto_transaction(True)" in hint + + +def test_a_subclass_built_by_hand_carries_its_code_and_hint(): + error = exceptions.DuplicateKeyError("my own text") + assert error.code == "duplicate_key" + assert error.hint == exceptions._RULE_OF_CODE["duplicate_key"].hint + assert str(error) == f"[duplicate_key] {error.hint} my own text" + assert isinstance(error, ArcadeDBError) + + +def test_the_subclasses_are_public_and_under_the_base_class(): + names = [ + "ConflictError", + "DatabaseClosedError", + "DatabaseExistsError", + "DatabaseLockedError", + "DatabaseNotFoundError", + "DuplicateKeyError", + "QuerySyntaxError", + "QueryTimeoutError", + "RecordNotFoundError", + "SchemaError", + "TransactionError", + "ValidationError", + ] + for name in names: + assert name in arcadedb.__all__ + assert issubclass(getattr(arcadedb, name), arcadedb.ArcadeDBError) + assert getattr(arcadedb, name) is getattr(exceptions, name) + + +def test_a_raise_site_picks_the_subclass_from_the_text_inside_an_except_block(): + try: + try: + raise ValueError("not a Java exception") + except ValueError as e: + raise ArcadeDBError( + "Command failed: com.arcadedb.exception.DuplicatedKeyException: Duplicated key [1]" + ) from e + except exceptions.DuplicateKeyError as error: + assert error.code == "duplicate_key" + assert error.__cause__.args == ("not a Java exception",) + + +def test_a_wrapper_around_a_classified_error_keeps_the_class_and_does_not_repeat_the_head(): + text = "Command failed: com.arcadedb.exception.DuplicatedKeyException: Duplicated key [1]" + try: + try: + raise ArcadeDBError(text) + except ArcadeDBError as e: + raise ArcadeDBError(f"Failed to commit transaction: {e}") from e + except exceptions.DuplicateKeyError as outer: + shown = str(outer) + assert shown.count("[duplicate_key]") == 1 + assert shown.endswith("Failed to commit transaction: " + text) + assert outer.args == ("Failed to commit transaction: " + text,) + + +def test_a_statement_that_a_syntax_error_echoes_does_not_decide_the_code(): + text = "Query failed: com.arcadedb.exception.CommandSQLParsingException: SQL syntax error at line 1: SELECT 'record not found' FROM" + error = ArcadeDBError._classified( + text, + [ + ( + E + "CommandSQLParsingException", + "SQL syntax error at line 1: SELECT 'record not found' FROM", + ) + ], + ) + assert error.code == "syntax_error" + + +def test_pickle_and_copy_keep_the_class_and_the_attributes(): + error = ArcadeDBError._classified( + "Failed to create database: com.arcadedb.exception.DatabaseOperationException: Database 'x' already exists", + [(E + "DatabaseOperationException", "Database 'x' already exists")], + ) + for clone in ( + pickle.loads(pickle.dumps(error)), # nosec B301 - same + copy.copy(error), + copy.deepcopy(error), + ): + assert type(clone) is exceptions.DatabaseExistsError + assert (clone.code, clone.hint, clone.cause) == ( + error.code, + error.hint, + error.cause, + ) + assert str(clone) == str(error) + + +def test_the_docs_page_lists_every_code_class_and_hint_of_the_table(): + page = ( + Path(__file__).resolve().parent.parent + / "docs" + / "modules" + / "ROOT" + / "pages" + / "how-to" + / "errors.adoc" + ) + if not page.is_file(): + pytest.fail("docs/modules/ROOT/pages/how-to/errors.adoc is missing") + text = page.read_text(encoding="utf-8") + for rule in exceptions._RULES: + assert f"`{rule.code}`" in text, rule.code + assert f"`{rule.cls.__name__}`" in text, rule.cls.__name__ + assert rule.hint in text, rule.code diff --git a/tests/test_native_tx_crossings.py b/tests/test_native_tx_crossings.py index 78a1635..d3b1dee 100644 --- a/tests/test_native_tx_crossings.py +++ b/tests/test_native_tx_crossings.py @@ -428,9 +428,10 @@ def test_a_commit_without_begin_raises_the_engines_error_unchanged(db): native = caught.value.native assert native["ok"] is False assert native["cls"] and "Transaction not begun" in native["error"] - assert ( - str(caught.value) - == f"Failed to commit transaction: {native['cls']}: {native['error']}" + # the engine's text is the tail of the message; the code and the hint come before it (#475) + assert caught.value.code == "transaction_not_begun" + assert str(caught.value).endswith( + f"Failed to commit transaction: {native['cls']}: {native['error']}" ) assert caught.value.java_chain == native["chain"] assert caught.value.java_chain[0] == [native["cls"], native["error"]]