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