relate_error/lib.rs
1//! Typed engine errors for Relate.
2//!
3//! This crate hosts [`EngineError`], the typed error channel that replaces the
4//! engine's historical `Result<_, String>`, and — since ADR-0502 §2 — the
5//! engine's one classification of a query-engine error, [`error_info`]: the
6//! Neo4j status code, the GQLSTATUS, the compile/runtime/internal stage
7//! (ADR-0319) and the drivers' transient test, single-sourced here so every
8//! surface (Bolt, HTTP, the CLI classifier, Python, the C ABI) is a thin
9//! derivation, never a second table. It depends on `relate-parser`
10//! (for [`ParseError`]) and `relate-core` (for the query-engine
11//! [`Error`](relate_core::Error) that [`error_info`] classifies, and for
12//! the shared error-kind vocabulary, which ADR-0502 moved down to core and
13//! this crate re-exports).
14//! See `docs/adr/0003-tck-named-error-kinds.md` and
15//! `docs/adr/0502-typed-c-abi-v2.md`.
16//!
17//! # The prime invariant
18//!
19//! `Display` output is preserved verbatim against the pre-refactor stringly
20//! errors: a parse-time failure renders exactly as `ParseError`'s
21//! `"parse error: …"`, a storage failure exactly as `StorageError`'s message,
22//! and a semantic/runtime failure exactly as the historical `"Kind: message"`
23//! shape. Changing an error *message* is not a breaking change; changing a
24//! *kind* is (per ADR 0003).
25
26use std::fmt;
27
28mod classification;
29mod nested_class;
30mod storage;
31
32pub use classification::{
33 client_message, error_info, log_internal_original, ErrorInfo, ErrorStage, ARGUMENT_ERROR_CODE,
34 ARGUMENT_VALUE_ERROR_CODE, ARITHMETIC_ERROR_CODE, CONSTRAINT_VALIDATION_FAILED_CODE,
35 DATABASE_NOT_FOUND_CODE, INTERNAL_ERROR_INFO, INTERNAL_MESSAGE, MEMORY_POOL_OUT_OF_MEMORY_CODE,
36 OUTDATED_CODE, PARAMETER_MISSING_CODE, PROCEDURE_CALL_FAILED_CODE, PROCEDURE_NOT_FOUND_CODE,
37 SEMANTIC_ERROR_CODE, SYNTAX_ERROR_CODE, TRANSACTION_OUT_OF_MEMORY_CODE,
38 TRANSACTION_TIMED_OUT_CLIENT_CONFIGURATION_CODE, TRANSACTION_TIMED_OUT_CODE, TYPE_ERROR_CODE,
39 UNKNOWN_ERROR_CODE,
40};
41pub use nested_class::{
42 nested_error_class, NestedErrorClass, ACCESS_MODE_CODE, ENTITY_NOT_FOUND_CODE,
43 GQLSTATUS_DATABASE_NOT_FOUND, GQLSTATUS_GENERAL, GQLSTATUS_SYNTAX,
44};
45pub use relate_core::{
46 duplicate_variable_detail, undefined_variable_detail, unknown_function_detail, ErrorKind,
47 TckErrorClass,
48};
49pub use relate_parser::ParseError;
50pub use storage::StorageError;
51
52/// The two `COUNT { … }` statement-shape UNION rule message bodies (CIP-66),
53/// single-sourced because two layers raise them byte-identically after
54/// [`ErrorKind::DifferentColumnsInUnion`]'s name: the front's validate
55/// battery (`validate_count_subquery_union_shapes`, rejecting before
56/// lowering) and the executor's per-row defense-in-depth scan
57/// (`eval_count_query`, for callers that bypass validation). The rendered
58/// text is pinned contract (ADR-0003's message immutability rule).
59pub const COUNT_UNION_MIX_MESSAGE: &str = "cannot mix explicit and omitted RETURN";
60pub const COUNT_UNION_OMITTED_MESSAGE: &str = "omitted RETURN requires UNION ALL";
61
62/// The typed engine error channel. Per ADR 0003 it has four variants:
63///
64/// - [`EngineError::Syntax`] wraps a parser [`ParseError`] verbatim.
65/// - [`EngineError::Semantic`] is a validation-time failure carrying an
66/// [`ErrorKind`] and message.
67/// - [`EngineError::Runtime`] is a row-evaluation-time failure carrying an
68/// [`ErrorKind`] and message.
69/// - [`EngineError::Storage`] wraps a [`StorageError`] verbatim.
70///
71/// `Display` reproduces the pre-refactor strings byte-for-byte (see the crate
72/// docs). `kind()` returns the finest TCK-aligned name; `tck_class()` returns
73/// the coarser TCK class.
74#[derive(Debug, Clone, PartialEq)]
75pub enum EngineError {
76 /// A parse-time failure. Renders as `ParseError`'s `"parse error: …"`.
77 Syntax(ParseError),
78 /// A semantic (validation-time) failure.
79 Semantic { kind: ErrorKind, message: String },
80 /// A runtime (row-evaluation-time) failure.
81 Runtime { kind: ErrorKind, message: String },
82 /// A storage-layer failure. Renders as `StorageError`'s message.
83 Storage(StorageError),
84}
85
86impl EngineError {
87 /// A reference to a name the scope does not bind.
88 pub fn undefined_variable(name: &str) -> Self {
89 Self::semantic(
90 ErrorKind::UndefinedVariable,
91 undefined_variable_detail(name),
92 )
93 }
94
95 /// A binding that redeclares a name its scope already binds.
96 pub fn duplicate_variable(name: &str) -> Self {
97 Self::semantic(
98 ErrorKind::VariableAlreadyBound,
99 duplicate_variable_detail(name),
100 )
101 }
102
103 /// Construct a semantic error.
104 pub fn semantic(kind: ErrorKind, message: impl Into<String>) -> Self {
105 EngineError::Semantic {
106 kind,
107 message: message.into(),
108 }
109 }
110
111 /// Construct a runtime error.
112 pub fn runtime(kind: ErrorKind, message: impl Into<String>) -> Self {
113 EngineError::Runtime {
114 kind,
115 message: message.into(),
116 }
117 }
118
119 /// The finest TCK-aligned [`ErrorKind`] for this error.
120 ///
121 /// A parse failure is a `SyntaxError` *class*, but if its [`ParseError`]
122 /// carries a [`detail`](ParseError::detail) tag (e.g. `"IntegerOverflow"`),
123 /// that finer kind is surfaced here so the TCK harness can match the
124 /// TCK's `<Detail>` slot. The tag is never rendered, so `Display` is
125 /// unaffected.
126 pub fn kind(&self) -> ErrorKind {
127 match self {
128 // A parse failure with no finer `detail` tag is the openCypher TCK's
129 // generic `UnexpectedSyntax` detail: the corpus has no
130 // scenario pinning a bare `SyntaxError` *detail*, while it has 17
131 // pinning `UnexpectedSyntax` for exactly these generic
132 // "expected/unexpected token" parse errors (Literals7/8, Literals2
133 // symbol case, …). Both kinds share the `SyntaxError` TCK *class*, so
134 // class-only assertions are unaffected. A tagged parse error still
135 // surfaces its finer kind (IntegerOverflow, InvalidNumberLiteral, …).
136 EngineError::Syntax(e) => e
137 .detail
138 .and_then(ErrorKind::from_name)
139 .unwrap_or(ErrorKind::UnexpectedSyntax),
140 EngineError::Semantic { kind, .. } | EngineError::Runtime { kind, .. } => *kind,
141 EngineError::Storage(e) => storage_kind(e),
142 }
143 }
144
145 /// The openCypher TCK error *class* for this error.
146 pub fn tck_class(&self) -> TckErrorClass {
147 self.kind().tck_class()
148 }
149}
150
151/// Maps a [`StorageError`] to the finest [`ErrorKind`] for reporting. `Display`
152/// still delegates to `StorageError` itself, so this only affects
153/// `kind()`/`tck_class()`, never the rendered message.
154fn storage_kind(e: &StorageError) -> ErrorKind {
155 match e {
156 StorageError::NodeNotFound(_) | StorageError::RelationshipNotFound(_) => {
157 ErrorKind::EntityNotFound
158 }
159 // Deleting a still-connected node without `DETACH` carries the finer
160 // `DeleteConnectedNode` detail (TCK clauses/delete/Delete1 scenario 7);
161 // a genuine constraint violation keeps `ConstraintViolation`. Both are
162 // the `ConstraintVerificationFailed` TCK class.
163 StorageError::NodeHasRelationships(_) => ErrorKind::DeleteConnectedNode,
164 StorageError::ConstraintViolation(_) => ErrorKind::ConstraintViolation,
165 StorageError::IndexAlreadyExists(_)
166 | StorageError::IndexNotFound(_)
167 | StorageError::ConstraintAlreadyExists(_)
168 | StorageError::ConstraintNotFound(_) => ErrorKind::SchemaError,
169 StorageError::TransactionsUnsupported
170 | StorageError::TransactionAlreadyActive
171 | StorageError::NoActiveTransaction
172 // A `Conflict` today is the flush-during-transaction guard, which is a
173 // transaction-state conflict.
174 | StorageError::Conflict(_) => ErrorKind::TransactionError,
175 // Filesystem I/O, on-disk corruption, a database already locked by
176 // another process, and a write rejected against a read-only snapshot
177 // (a historical MVCC checkout) are all database-level operational
178 // failures.
179 StorageError::Io { .. }
180 | StorageError::Corruption(_)
181 | StorageError::Locked(_)
182 | StorageError::ReadOnly(_) => ErrorKind::DatabaseError,
183 StorageError::PersistenceOutcomeIndeterminate(_) | StorageError::Other(_) => {
184 ErrorKind::Uncategorized
185 }
186 }
187}
188
189impl fmt::Display for EngineError {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 match self {
192 EngineError::Syntax(e) => write!(f, "{e}"),
193 EngineError::Storage(e) => write!(f, "{e}"),
194 EngineError::Semantic { kind, message } | EngineError::Runtime { kind, message } => {
195 if *kind == ErrorKind::Uncategorized {
196 // Escape hatch: reproduce the raw legacy string verbatim.
197 f.write_str(message)
198 } else {
199 write!(f, "{}: {}", kind.as_str(), message)
200 }
201 }
202 }
203 }
204}
205
206impl std::error::Error for EngineError {
207 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
208 match self {
209 EngineError::Syntax(e) => Some(e),
210 EngineError::Storage(e) => Some(e),
211 EngineError::Semantic { .. } | EngineError::Runtime { .. } => None,
212 }
213 }
214}
215
216impl From<ParseError> for EngineError {
217 fn from(e: ParseError) -> Self {
218 EngineError::Syntax(e)
219 }
220}
221
222impl From<StorageError> for EngineError {
223 fn from(e: StorageError) -> Self {
224 EngineError::Storage(e)
225 }
226}
227
228#[cfg(test)]
229mod tests;