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