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