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