Skip to main content

relate_error/
nested_class.rs

1//! The condition-token vocabulary: the class names the engine embeds in a
2//! still-stringly payload, the one canonical scan that recovers them
3//! (ADR-0502 §2), and the documented GQLSTATUS each carries. Split out of
4//! `classification` so the vocabulary and its codes stay one module apart
5//! from the error-classification table that reads them.
6
7/// The GQL general error code: the code of a caller-facing class without a
8/// class-specific GQLSTATUS.
9pub const GQLSTATUS_GENERAL: &str = "42000";
10
11/// The GQLSTATUS of a rejected statement (the `SyntaxError` class).
12pub const GQLSTATUS_SYNTAX: &str = "42N06";
13
14/// The GQLSTATUS of a registered procedure or function call that failed
15/// its own signature — live's `Neo.ClientError.Procedure.ProcedureCallFailed`
16/// reports 42001 (probed 2026-11-20 on Neo4j 2026.10.1).
17pub(crate) const GQLSTATUS_PROCEDURE_CALL: &str = "42001";
18
19/// The GQLSTATUS of an absent query parameter (ADR-0308).
20pub(crate) const GQLSTATUS_PARAMETER_MISSING: &str = "42N02";
21
22/// The GQLSTATUS of a type failure.
23pub(crate) const GQLSTATUS_TYPE: &str = "22G03";
24
25/// The GQLSTATUS of an unknown database (ADR-0116 §9).
26pub const GQLSTATUS_DATABASE_NOT_FOUND: &str = "42N00";
27
28/// The GQLSTATUS of an unsupported administration command (ADR-0116 §9).
29pub(crate) const GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND: &str = "51N27";
30
31/// The GQLSTATUS of a write against the read-only `system_ontologies`
32/// namespace (ADR-0116 §9).
33pub(crate) const GQLSTATUS_WRITE_ON_READ_ONLY: &str = "42N18";
34
35/// The GQLSTATUS of an engine-internal failure.
36pub(crate) const GQLSTATUS_INTERNAL: &str = "50N42";
37
38// The documented GQLSTATUS of the schema/DDL condition tokens (Neo4j's
39// GQLSTATUS table, read 2026-11-12; live-probed on 2026.10.1). A token
40// names one failure kind, so the code follows the condition, never the
41// raise site.
42
43/// A constraint created over data that violates it.
44pub(crate) const GQLSTATUS_CONSTRAINT_CREATION_FAILED: &str = "50N11";
45
46/// A failed `DROP CONSTRAINT` — an absent name or a dependent constraint
47/// that only its graph type may manage.
48const GQLSTATUS_CONSTRAINT_DROP_FAILED: &str = "50N12";
49
50/// An equivalent constraint already exists.
51const GQLSTATUS_CONSTRAINT_EQUIVALENT: &str = "22N65";
52
53/// A conflicting constraint already exists.
54const GQLSTATUS_CONSTRAINT_CONFLICTING: &str = "22N66";
55
56/// A constraint with the same name already exists.
57const GQLSTATUS_CONSTRAINT_DUPLICATED_NAME: &str = "22N67";
58
59/// An equivalent index already exists.
60const GQLSTATUS_INDEX_EQUIVALENT: &str = "22N70";
61
62/// An index with the same name already exists.
63const GQLSTATUS_INDEX_DUPLICATED_NAME: &str = "22N71";
64
65/// The index a query names does not exist.
66const GQLSTATUS_INDEX_NOT_FOUND: &str = "22N69";
67
68/// A SEARCH over an index created inside the current transaction: the
69/// index is populating until the transaction commits.
70const GQLSTATUS_INDEX_STILL_POPULATING: &str = "51N63";
71
72/// A constraint's graph-type dependence is incompatible with an existing
73/// constraint.
74const GQLSTATUS_INCOMPATIBLE_GRAPH_TYPE_DEPENDENCE: &str = "22NB2";
75
76/// An administration command that needs the system database.
77const GQLSTATUS_NOT_SYSTEM_DATABASE: &str = "51N28";
78
79/// A statement execution failure (live's `Statement.ExecutionFailed`); the
80/// element-id format rejections carry it.
81const GQLSTATUS_EXECUTION_FAILED: &str = "50N00";
82
83/// Generates [`NestedErrorClass`], its [`NestedErrorClass::ALL`] roster
84/// and its [`as_str`](NestedErrorClass::as_str) spelling from the one
85/// variant list, so a new variant cannot miss the roster or the spelling.
86macro_rules! nested_error_classes {
87    ($($(#[$meta:meta])* $variant:ident,)+) => {
88        /// The closed vocabulary of that scan: one variant per class name the
89        /// engine's CE formatters (`relate_core::ce_messages`,
90        /// ADR-0116 §9/ADR-0117 §6) and the legacy constraint classes embed. The
91        /// token parsing stays at the scan's one boundary; every consumer matches
92        /// the typed variant.
93        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
94        pub enum NestedErrorClass {
95            $($(#[$meta])* $variant,)+
96        }
97
98        impl NestedErrorClass {
99            /// Every class the scan recognizes, in enum order — the one
100            /// list the scan's exact-match half and the round-trip test
101            /// derive from; generated from the variant list, so it cannot
102            /// drift from the enum.
103            pub(crate) const ALL: &'static [NestedErrorClass] =
104                &[$(NestedErrorClass::$variant,)+];
105
106            /// The one string spelling of the class — the `<Class>:` token
107            /// the engine embeds and the bindings report. Generated from
108            /// the variant name, so the spelling is single-sourced.
109            ///
110            /// ```
111            /// use relate_error::{nested_error_class, NestedErrorClass};
112            ///
113            /// assert_eq!(
114            ///     NestedErrorClass::ConstraintVerificationFailed.as_str(),
115            ///     "ConstraintVerificationFailed"
116            /// );
117            /// assert_eq!(
118            ///     nested_error_class("ArgumentError: bad options"),
119            ///     Some(NestedErrorClass::ArgumentError)
120            /// );
121            /// assert_eq!(NestedErrorClass::ArgumentError.as_str(), "ArgumentError");
122            /// ```
123            pub fn as_str(self) -> &'static str {
124                match self {
125                    $(NestedErrorClass::$variant => stringify!($variant),)+
126                }
127            }
128        }
129    };
130}
131
132nested_error_classes! {
133    /// The legacy constraint family (`ConstraintValidationFailed:` /
134    /// `ConstraintVerificationFailed:` tokens, anywhere in the payload).
135    ConstraintVerificationFailed,
136    /// A DDL argument-value rejection (`ArgumentError:`).
137    ArgumentError,
138    /// A well-formed reference to something absent (`EntityNotFound:`):
139    /// live's `EntityNotFound` class, GQLSTATUS `42001`.
140    EntityNotFound,
141    /// A registered procedure's own failure (`ProcedureError:`).
142    ProcedureError,
143    /// A rejected statement (`SyntaxError:`).
144    SyntaxError,
145    /// A semantic rejection (`SemanticError:`).
146    SemanticError,
147    /// An unsupported administration command (ADR-0116 §9).
148    UnsupportedAdministrationCommand,
149    /// A write against the read-only `system_ontologies` namespace
150    /// (ADR-0116 §9).
151    WriteOnReadOnlyAccessDatabase,
152    /// An unknown database (`DatabaseNotFound:`).
153    DatabaseNotFound,
154    /// A transaction-state failure (`TransactionError:`).
155    TransactionError,
156    // The schema/DDL condition tokens. They name a failure kind whose
157    // documented GQLSTATUS differs from its openCypher class; unlike the
158    // ten class tokens above they are not part of the bindings' class
159    // vocabulary (see [`Self::binding_class`]).
160    /// A constraint with the same name already exists (`22N67`).
161    ConstraintAlreadyExists,
162    /// An equivalent constraint already exists (`22N65`).
163    EquivalentConstraintAlreadyExists,
164    /// A conflicting constraint already exists (`22N66`).
165    ConstraintConflict,
166    /// A `DROP CONSTRAINT` whose name does not exist (`50N12`).
167    ConstraintNotFound,
168    /// A `DROP CONSTRAINT` of a dependent constraint (`50N12`).
169    DependentConstraintManagedIndividually,
170    /// An index with the same name already exists (`22N71`).
171    DuplicatedIndexName,
172    /// An index with the same name already exists (`22N71`).
173    IndexAlreadyExists,
174    /// An equivalent index already exists (`22N70`).
175    EquivalentSchemaRuleAlreadyExists,
176    /// A constraint's graph-type dependence is incompatible (`22NB2`).
177    IncompatibleGraphTypeDependence,
178    /// The index a query names does not exist (`22N69`).
179    IndexDoesNotExist,
180    /// A SEARCH over an index created inside the current transaction
181    /// (`51N63`): the index is populating until the transaction commits
182    /// (ADR-0678).
183    IndexStillPopulating,
184    /// An administration command that needs the system database (`51N28`).
185    SystemDatabaseRequired,
186    /// An element id whose format cannot be resolved (`50N00`).
187    ElementIdUnexpectedFormat,
188}
189
190impl NestedErrorClass {
191    /// The openCypher class the language bindings report for this token, or
192    /// `None` for a schema/DDL condition token — those are classified for
193    /// their GQLSTATUS while the bindings keep the class they had before
194    /// the condition had a token (a `Syntax` payload's `SyntaxError`, a
195    /// `Semantic`/`Execution` payload's `SemanticError`).
196    pub fn binding_class(self) -> Option<&'static str> {
197        match self {
198            NestedErrorClass::ConstraintVerificationFailed
199            | NestedErrorClass::ArgumentError
200            | NestedErrorClass::EntityNotFound
201            | NestedErrorClass::ProcedureError
202            | NestedErrorClass::SyntaxError
203            | NestedErrorClass::SemanticError
204            | NestedErrorClass::UnsupportedAdministrationCommand
205            | NestedErrorClass::WriteOnReadOnlyAccessDatabase
206            | NestedErrorClass::DatabaseNotFound
207            | NestedErrorClass::TransactionError => Some(self.as_str()),
208            NestedErrorClass::ConstraintAlreadyExists
209            | NestedErrorClass::EquivalentConstraintAlreadyExists
210            | NestedErrorClass::ConstraintConflict
211            | NestedErrorClass::ConstraintNotFound
212            | NestedErrorClass::DependentConstraintManagedIndividually
213            | NestedErrorClass::DuplicatedIndexName
214            | NestedErrorClass::IndexAlreadyExists
215            | NestedErrorClass::EquivalentSchemaRuleAlreadyExists
216            | NestedErrorClass::IncompatibleGraphTypeDependence
217            | NestedErrorClass::IndexDoesNotExist
218            | NestedErrorClass::IndexStillPopulating
219            | NestedErrorClass::SystemDatabaseRequired
220            | NestedErrorClass::ElementIdUnexpectedFormat => None,
221        }
222    }
223}
224
225/// The one canonical scan (AGENTS.md: one canonical helper per policy) of
226/// a still-stringly payload's nested class, consulted by both consumers of
227/// the nested-class fact: [`error_info`]'s GQLSTATUS for these payloads,
228/// and the language bindings' `binding_error_metadata`. A string that
229/// merely resembles a typed class's token does not adopt that class — the
230/// recognized names are the ones [`NestedErrorClass`] closes over.
231pub fn nested_error_class(payload: &str) -> Option<NestedErrorClass> {
232    // A leading name token: a `<Class>:` prefix, or the whole payload when
233    // the engine raised the bare token (`Error::semantic("DuplicatedIndexName")`).
234    // The names are distinct and the historical match was exact equality,
235    // so this lookup over [`NestedErrorClass::ALL`] is behavior-identical to
236    // the exact-match arms it replaces — and a new variant joins the scan by
237    // joining ALL.
238    let name = payload
239        .split_once(':')
240        .map_or(payload, |(name, _)| name)
241        .trim();
242    let leading = NestedErrorClass::ALL
243        .iter()
244        .copied()
245        .find(|class| class.as_str() == name);
246    if leading.is_some() {
247        return leading;
248    }
249    // The one documented alias: the legacy constraint class was spelled
250    // `ConstraintValidationFailed:` and can appear anywhere in the payload,
251    // not only as the leading token, so the leading-name lookup above
252    // cannot carry it.
253    if payload.contains("ConstraintValidationFailed:")
254        || payload.contains("ConstraintVerificationFailed:")
255    {
256        return Some(NestedErrorClass::ConstraintVerificationFailed);
257    }
258    None
259}
260
261/// The GQLSTATUS of a still-stringly payload: a recognized nested class
262/// carries its own code (the engine-documented ones of ADR-0116 §9, the
263/// syntax class's own code, the GQL general code for every other nested
264/// class), and a payload with no nested class carries `own` — its
265/// variant's code. The exact split HTTP's error envelope (ADR-0232) has
266/// always made over the same scan. Both projections read the one scan the
267/// arm makes.
268pub(crate) fn stringly_gql_status(
269    nested: Option<NestedErrorClass>,
270    own: &'static str,
271) -> &'static str {
272    match nested {
273        None => own,
274        Some(NestedErrorClass::DatabaseNotFound) => GQLSTATUS_DATABASE_NOT_FOUND,
275        Some(NestedErrorClass::UnsupportedAdministrationCommand) => {
276            GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND
277        }
278        Some(NestedErrorClass::WriteOnReadOnlyAccessDatabase) => GQLSTATUS_WRITE_ON_READ_ONLY,
279        Some(NestedErrorClass::SyntaxError) => GQLSTATUS_SYNTAX,
280        // The schema/DDL condition tokens carry their documented code.
281        Some(NestedErrorClass::ConstraintAlreadyExists) => GQLSTATUS_CONSTRAINT_DUPLICATED_NAME,
282        Some(NestedErrorClass::EquivalentConstraintAlreadyExists) => {
283            GQLSTATUS_CONSTRAINT_EQUIVALENT
284        }
285        Some(NestedErrorClass::ConstraintConflict) => GQLSTATUS_CONSTRAINT_CONFLICTING,
286        Some(
287            NestedErrorClass::ConstraintNotFound
288            | NestedErrorClass::DependentConstraintManagedIndividually,
289        ) => GQLSTATUS_CONSTRAINT_DROP_FAILED,
290        Some(NestedErrorClass::DuplicatedIndexName | NestedErrorClass::IndexAlreadyExists) => {
291            GQLSTATUS_INDEX_DUPLICATED_NAME
292        }
293        Some(NestedErrorClass::EquivalentSchemaRuleAlreadyExists) => GQLSTATUS_INDEX_EQUIVALENT,
294        Some(NestedErrorClass::IndexDoesNotExist) => GQLSTATUS_INDEX_NOT_FOUND,
295        Some(NestedErrorClass::IndexStillPopulating) => GQLSTATUS_INDEX_STILL_POPULATING,
296        Some(NestedErrorClass::IncompatibleGraphTypeDependence) => {
297            GQLSTATUS_INCOMPATIBLE_GRAPH_TYPE_DEPENDENCE
298        }
299        Some(NestedErrorClass::SystemDatabaseRequired) => GQLSTATUS_NOT_SYSTEM_DATABASE,
300        Some(NestedErrorClass::ElementIdUnexpectedFormat) => GQLSTATUS_EXECUTION_FAILED,
301        Some(NestedErrorClass::EntityNotFound) => GQLSTATUS_PROCEDURE_CALL,
302        // The recognized nested classes without a class-specific GQLSTATUS
303        // carry the general code, never the variant's own — named, not
304        // wildcarded, so a future variant forces its own decision here.
305        Some(
306            NestedErrorClass::ConstraintVerificationFailed
307            | NestedErrorClass::ArgumentError
308            | NestedErrorClass::ProcedureError
309            | NestedErrorClass::SemanticError
310            | NestedErrorClass::TransactionError,
311        ) => GQLSTATUS_GENERAL,
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    /// The binding class vocabulary does not move: a condition token reports
320    /// no class of its own, so the calling variant's fallback stays.
321    #[test]
322    fn condition_tokens_keep_the_binding_class_vocabulary() {
323        assert_eq!(
324            NestedErrorClass::ArgumentError.binding_class(),
325            Some("ArgumentError")
326        );
327        assert_eq!(
328            NestedErrorClass::ConstraintAlreadyExists.binding_class(),
329            None
330        );
331        assert_eq!(NestedErrorClass::IndexDoesNotExist.binding_class(), None);
332    }
333
334    /// The canonical nested-class scan: the names the engine embeds are
335    /// recovered, lookalikes are not, and every recovered class renders
336    /// the token it was scanned from.
337    #[test]
338    fn nested_error_class_recovers_the_embedded_names() {
339        assert_eq!(
340            nested_error_class("ArgumentError: x"),
341            Some(NestedErrorClass::ArgumentError)
342        );
343        assert_eq!(
344            nested_error_class("outer context: ConstraintVerificationFailed: duplicate key"),
345            Some(NestedErrorClass::ConstraintVerificationFailed)
346        );
347        assert_eq!(
348            nested_error_class("outer: ConstraintValidationFailed: bad"),
349            Some(NestedErrorClass::ConstraintVerificationFailed)
350        );
351        assert_eq!(nested_error_class("no class here"), None);
352        assert_eq!(nested_error_class("nested ParameterMissing: p"), None);
353        assert_eq!(nested_error_class(""), None);
354    }
355
356    /// The closed vocabulary: every class in [`NestedErrorClass::ALL`] is
357    /// recovered from its own rendered token, so the enum, the scan and
358    /// the wire spelling cannot drift.
359    #[test]
360    fn every_nested_class_renders_its_embedded_token() {
361        for &class in NestedErrorClass::ALL {
362            let token = class.as_str();
363            let scanned = nested_error_class(&format!("{token}: x"))
364                .unwrap_or_else(|| panic!("token {token} not recognized by the scan"));
365            assert_eq!(scanned.as_str(), token);
366        }
367    }
368}