relate-error 1.5.0

Typed engine errors and error classification for the Relate graph database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! The condition-token vocabulary: the class names the engine embeds in a
//! still-stringly payload, the one canonical scan that recovers them
//! (ADR-0502 §2), and the documented GQLSTATUS each carries. Split out of
//! `classification` so the vocabulary and its codes stay one module apart
//! from the error-classification table that reads them.

/// The GQL general error code: the code of a caller-facing class without a
/// class-specific GQLSTATUS.
pub const GQLSTATUS_GENERAL: &str = "42000";

/// The GQLSTATUS of a rejected statement (the `SyntaxError` class).
pub const GQLSTATUS_SYNTAX: &str = "42N06";

/// The GQLSTATUS of a registered procedure or function call that failed
/// its own signature — live's `Neo.ClientError.Procedure.ProcedureCallFailed`
/// reports 42001 (probed 2026-11-20 on Neo4j 2026.10.1).
pub(crate) const GQLSTATUS_PROCEDURE_CALL: &str = "42001";

/// The GQLSTATUS of an absent query parameter (ADR-0308).
pub(crate) const GQLSTATUS_PARAMETER_MISSING: &str = "42N02";

/// The GQLSTATUS of a type failure.
pub(crate) const GQLSTATUS_TYPE: &str = "22G03";

/// The GQLSTATUS of an unknown database (ADR-0116 §9).
pub const GQLSTATUS_DATABASE_NOT_FOUND: &str = "42N00";

/// The GQLSTATUS of an unsupported administration command (ADR-0116 §9).
pub(crate) const GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND: &str = "51N27";

/// The GQLSTATUS of a write against the read-only `system_ontologies`
/// namespace (ADR-0116 §9).
pub(crate) const GQLSTATUS_WRITE_ON_READ_ONLY: &str = "42N18";

/// The GQLSTATUS of a write in READ access mode (ADR-0742): Neo4j's
/// access-rule-violation class, the same documented code the absent-
/// parameter condition carries. Read only by this module's class rows;
/// widening only when another module projects from it.
const GQLSTATUS_ACCESS_MODE: &str = "42N02";

// The two Neo4j status codes the coded-exception rows carry — kept here
// beside the vocabulary that decides them (the class rows below), with
// the crate's public `pub use` in `lib.rs` naming this module; the
// remaining status codes, whose rows live in `classification`'s variant
// table, stay there.

/// The `code` of a well-formed reference to something that does not exist
/// (`EntityNotFound:` token): what Neo4j 2026.10.1 sends for
/// `db.nameFromElementId` over an element id naming an unknown database.
pub const ENTITY_NOT_FOUND_CODE: &str = "Neo.ClientError.Statement.EntityNotFound";

/// The `code` of a write, read-write or schema statement run under a
/// connection armed READ access mode (ADR-0742): the code drivers branch
/// on when a read transaction (`execute_read`, a READ session) carries a
/// write — refused before any work is done.
pub const ACCESS_MODE_CODE: &str = "Neo.ClientError.Statement.AccessMode";

/// The GQLSTATUS of an engine-internal failure.
pub(crate) const GQLSTATUS_INTERNAL: &str = "50N42";

// The documented GQLSTATUS of the schema/DDL condition tokens (Neo4j's
// GQLSTATUS table, read 2026-11-12; live-probed on 2026.10.1). A token
// names one failure kind, so the code follows the condition, never the
// raise site.

/// A constraint created over data that violates it.
pub(crate) const GQLSTATUS_CONSTRAINT_CREATION_FAILED: &str = "50N11";

/// A failed `DROP CONSTRAINT` — an absent name or a dependent constraint
/// that only its graph type may manage.
const GQLSTATUS_CONSTRAINT_DROP_FAILED: &str = "50N12";

/// An equivalent constraint already exists.
const GQLSTATUS_CONSTRAINT_EQUIVALENT: &str = "22N65";

/// A conflicting constraint already exists.
const GQLSTATUS_CONSTRAINT_CONFLICTING: &str = "22N66";

/// A constraint with the same name already exists.
const GQLSTATUS_CONSTRAINT_DUPLICATED_NAME: &str = "22N67";

/// An equivalent index already exists.
const GQLSTATUS_INDEX_EQUIVALENT: &str = "22N70";

/// An index with the same name already exists.
const GQLSTATUS_INDEX_DUPLICATED_NAME: &str = "22N71";

/// The index a query names does not exist.
const GQLSTATUS_INDEX_NOT_FOUND: &str = "22N69";

/// A SEARCH over an index created inside the current transaction: the
/// index is populating until the transaction commits.
const GQLSTATUS_INDEX_STILL_POPULATING: &str = "51N63";

/// A constraint's graph-type dependence is incompatible with an existing
/// constraint.
const GQLSTATUS_INCOMPATIBLE_GRAPH_TYPE_DEPENDENCE: &str = "22NB2";

/// An administration command that needs the system database.
const GQLSTATUS_NOT_SYSTEM_DATABASE: &str = "51N28";

/// A statement execution failure (live's `Statement.ExecutionFailed`); the
/// element-id format rejections carry it.
const GQLSTATUS_EXECUTION_FAILED: &str = "50N00";

/// Generates [`NestedErrorClass`], its [`NestedErrorClass::ALL`] roster
/// and its [`as_str`](NestedErrorClass::as_str) spelling from the one
/// variant list, so a new variant cannot miss the roster or the spelling.
macro_rules! nested_error_classes {
    ($($(#[$meta:meta])* $variant:ident,)+) => {
        /// The closed vocabulary of that scan: one variant per class name the
        /// engine's CE formatters (`relate_core::ce_messages`,
        /// ADR-0116 §9/ADR-0117 §6) and the legacy constraint classes embed. The
        /// token parsing stays at the scan's one boundary; every consumer matches
        /// the typed variant.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum NestedErrorClass {
            $($(#[$meta])* $variant,)+
        }

        impl NestedErrorClass {
            /// Every class the scan recognizes, in enum order — the one
            /// list the scan's exact-match half and the round-trip test
            /// derive from; generated from the variant list, so it cannot
            /// drift from the enum.
            pub(crate) const ALL: &'static [NestedErrorClass] =
                &[$(NestedErrorClass::$variant,)+];

            /// The one string spelling of the class — the `<Class>:` token
            /// the engine embeds and the bindings report. Generated from
            /// the variant name, so the spelling is single-sourced.
            ///
            /// ```
            /// use relate_error::{nested_error_class, NestedErrorClass};
            ///
            /// assert_eq!(
            ///     NestedErrorClass::ConstraintVerificationFailed.as_str(),
            ///     "ConstraintVerificationFailed"
            /// );
            /// assert_eq!(
            ///     nested_error_class("ArgumentError: bad options"),
            ///     Some(NestedErrorClass::ArgumentError)
            /// );
            /// assert_eq!(NestedErrorClass::ArgumentError.as_str(), "ArgumentError");
            /// ```
            pub fn as_str(self) -> &'static str {
                match self {
                    $(NestedErrorClass::$variant => stringify!($variant),)+
                }
            }
        }
    };
}

nested_error_classes! {
    /// The legacy constraint family (`ConstraintValidationFailed:` /
    /// `ConstraintVerificationFailed:` tokens, anywhere in the payload).
    ConstraintVerificationFailed,
    /// A DDL argument-value rejection (`ArgumentError:`).
    ArgumentError,
    /// A well-formed reference to something absent (`EntityNotFound:`):
    /// live's `EntityNotFound` class, GQLSTATUS `42001`.
    EntityNotFound,
    /// A registered procedure's own failure (`ProcedureError:`).
    ProcedureError,
    /// A rejected statement (`SyntaxError:`).
    SyntaxError,
    /// A semantic rejection (`SemanticError:`).
    SemanticError,
    /// An unsupported administration command (ADR-0116 §9).
    UnsupportedAdministrationCommand,
    /// A write against the read-only `system_ontologies` namespace
    /// (ADR-0116 §9).
    WriteOnReadOnlyAccessDatabase,
    /// A write in READ access mode (ADR-0742).
    AccessMode,
    /// An unknown database (`DatabaseNotFound:`).
    DatabaseNotFound,
    /// A transaction-state failure (`TransactionError:`).
    TransactionError,
    // The schema/DDL condition tokens. They name a failure kind whose
    // documented GQLSTATUS differs from its openCypher class; unlike the
    // eleven class tokens above they are not part of the bindings' class
    // vocabulary (see [`Self::binding_class`]).
    /// A constraint with the same name already exists (`22N67`).
    ConstraintAlreadyExists,
    /// An equivalent constraint already exists (`22N65`).
    EquivalentConstraintAlreadyExists,
    /// A conflicting constraint already exists (`22N66`).
    ConstraintConflict,
    /// A `DROP CONSTRAINT` whose name does not exist (`50N12`).
    ConstraintNotFound,
    /// A `DROP CONSTRAINT` of a dependent constraint (`50N12`).
    DependentConstraintManagedIndividually,
    /// An index with the same name already exists (`22N71`).
    DuplicatedIndexName,
    /// An index with the same name already exists (`22N71`).
    IndexAlreadyExists,
    /// An equivalent index already exists (`22N70`).
    EquivalentSchemaRuleAlreadyExists,
    /// A constraint's graph-type dependence is incompatible (`22NB2`).
    IncompatibleGraphTypeDependence,
    /// The index a query names does not exist (`22N69`).
    IndexDoesNotExist,
    /// A SEARCH over an index created inside the current transaction
    /// (`51N63`): the index is populating until the transaction commits
    /// (ADR-0678).
    IndexStillPopulating,
    /// An administration command that needs the system database (`51N28`).
    SystemDatabaseRequired,
    /// An element id whose format cannot be resolved (`50N00`).
    ElementIdUnexpectedFormat,
}

/// One nested class's wire-code row — the one per-class table every
/// projection over the vocabulary reads (ADR-0742's fold). A new variant
/// forces its row here, so both code columns and the binding vocabulary
/// are decided in this module alone.
enum ClassRow {
    /// A binding-class token: the bindings report the class's own name;
    /// the `Semantic`/`Execution` family's default code; the given
    /// GQLSTATUS.
    Token(&'static str),
    /// A coded binding-class token: like [`ClassRow::Token`], but the
    /// class carries its own Neo4j status code instead of the family
    /// default.
    Coded {
        own_code: &'static str,
        gql_status: &'static str,
    },
    /// A schema/DDL **condition token**: no binding class of its own (the
    /// bindings keep the class they had before the condition had a
    /// token), no own code, the condition's documented GQLSTATUS.
    Condition(&'static str),
}

impl ClassRow {
    /// The row's GQLSTATUS — one projection, shared by every row shape.
    fn gql_status(&self) -> &'static str {
        match self {
            ClassRow::Token(gql_status) | ClassRow::Condition(gql_status) => gql_status,
            ClassRow::Coded { gql_status, .. } => gql_status,
        }
    }
}

impl NestedErrorClass {
    /// The one per-class row: [`Self::binding_class`],
    /// [`nested_own_code`] and [`stringly_gql_status`] all project from
    /// it, never a second table over the same vocabulary.
    fn row(self) -> ClassRow {
        use NestedErrorClass::*;
        match self {
            // The binding-class tokens.
            ConstraintVerificationFailed => ClassRow::Token(GQLSTATUS_GENERAL),
            ArgumentError => ClassRow::Token(GQLSTATUS_GENERAL),
            EntityNotFound => ClassRow::Coded {
                own_code: ENTITY_NOT_FOUND_CODE,
                gql_status: GQLSTATUS_PROCEDURE_CALL,
            },
            ProcedureError => ClassRow::Token(GQLSTATUS_GENERAL),
            SyntaxError => ClassRow::Token(GQLSTATUS_SYNTAX),
            SemanticError => ClassRow::Token(GQLSTATUS_GENERAL),
            UnsupportedAdministrationCommand => {
                ClassRow::Token(GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND)
            }
            WriteOnReadOnlyAccessDatabase => ClassRow::Token(GQLSTATUS_WRITE_ON_READ_ONLY),
            AccessMode => ClassRow::Coded {
                own_code: ACCESS_MODE_CODE,
                gql_status: GQLSTATUS_ACCESS_MODE,
            },
            DatabaseNotFound => ClassRow::Token(GQLSTATUS_DATABASE_NOT_FOUND),
            TransactionError => ClassRow::Token(GQLSTATUS_GENERAL),
            // The schema/DDL condition tokens, each with its documented
            // GQLSTATUS.
            ConstraintAlreadyExists => ClassRow::Condition(GQLSTATUS_CONSTRAINT_DUPLICATED_NAME),
            EquivalentConstraintAlreadyExists => {
                ClassRow::Condition(GQLSTATUS_CONSTRAINT_EQUIVALENT)
            }
            ConstraintConflict => ClassRow::Condition(GQLSTATUS_CONSTRAINT_CONFLICTING),
            ConstraintNotFound | DependentConstraintManagedIndividually => {
                ClassRow::Condition(GQLSTATUS_CONSTRAINT_DROP_FAILED)
            }
            DuplicatedIndexName | IndexAlreadyExists => {
                ClassRow::Condition(GQLSTATUS_INDEX_DUPLICATED_NAME)
            }
            EquivalentSchemaRuleAlreadyExists => ClassRow::Condition(GQLSTATUS_INDEX_EQUIVALENT),
            IncompatibleGraphTypeDependence => {
                ClassRow::Condition(GQLSTATUS_INCOMPATIBLE_GRAPH_TYPE_DEPENDENCE)
            }
            IndexDoesNotExist => ClassRow::Condition(GQLSTATUS_INDEX_NOT_FOUND),
            IndexStillPopulating => ClassRow::Condition(GQLSTATUS_INDEX_STILL_POPULATING),
            SystemDatabaseRequired => ClassRow::Condition(GQLSTATUS_NOT_SYSTEM_DATABASE),
            ElementIdUnexpectedFormat => ClassRow::Condition(GQLSTATUS_EXECUTION_FAILED),
        }
    }

    /// The openCypher class the language bindings report for this token, or
    /// `None` for a schema/DDL condition token — those are classified for
    /// their GQLSTATUS while the bindings keep the class they had before
    /// the condition had a token (a `Syntax` payload's `SyntaxError`, a
    /// `Semantic`/`Execution` payload's `SemanticError`).
    pub fn binding_class(self) -> Option<&'static str> {
        match self.row() {
            ClassRow::Token(_) | ClassRow::Coded { .. } => Some(self.as_str()),
            ClassRow::Condition(_) => None,
        }
    }
}

/// The one canonical scan (AGENTS.md: one canonical helper per policy) of
/// a still-stringly payload's nested class, consulted by both consumers of
/// the nested-class fact: [`error_info`]'s GQLSTATUS for these payloads,
/// and the language bindings' `binding_error_metadata`. A string that
/// merely resembles a typed class's token does not adopt that class — the
/// recognized names are the ones [`NestedErrorClass`] closes over.
pub fn nested_error_class(payload: &str) -> Option<NestedErrorClass> {
    // A leading name token: a `<Class>:` prefix, or the whole payload when
    // the engine raised the bare token (`Error::semantic("DuplicatedIndexName")`).
    // The names are distinct and the historical match was exact equality,
    // so this lookup over [`NestedErrorClass::ALL`] is behavior-identical to
    // the exact-match arms it replaces — and a new variant joins the scan by
    // joining ALL.
    let name = payload
        .split_once(':')
        .map_or(payload, |(name, _)| name)
        .trim();
    let leading = NestedErrorClass::ALL
        .iter()
        .copied()
        .find(|class| class.as_str() == name);
    if leading.is_some() {
        return leading;
    }
    // The one documented alias: the legacy constraint class was spelled
    // `ConstraintValidationFailed:` and can appear anywhere in the payload,
    // not only as the leading token, so the leading-name lookup above
    // cannot carry it.
    if payload.contains("ConstraintValidationFailed:")
        || payload.contains("ConstraintVerificationFailed:")
    {
        return Some(NestedErrorClass::ConstraintVerificationFailed);
    }
    None
}

/// The GQLSTATUS of a still-stringly payload: a recognized nested class
/// carries its own code (the engine-documented ones of ADR-0116 §9, the
/// syntax class's own code, the GQL general code for every other nested
/// class), and a payload with no nested class carries `own` — its
/// variant's code. The exact split HTTP's error envelope (ADR-0232) has
/// always made over the same scan. Both projections read the one scan the
/// arm makes.
pub(crate) fn stringly_gql_status(
    nested: Option<NestedErrorClass>,
    own: &'static str,
) -> &'static str {
    match nested {
        None => own,
        Some(nested) => nested.row().gql_status(),
    }
}

/// The Neo4j status code a nested class carries instead of the
/// `Semantic`/`Execution` family's `SemanticError` default (ADR-0502 §2):
/// the coded tokens' rows, projected from the one per-class table beside
/// the vocabulary; `None` for every class that keeps the family default.
pub(crate) fn nested_own_code(nested: NestedErrorClass) -> Option<&'static str> {
    match nested.row() {
        ClassRow::Coded { own_code, .. } => Some(own_code),
        ClassRow::Token(_) | ClassRow::Condition(_) => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The binding class vocabulary does not move: a condition token reports
    /// no class of its own, so the calling variant's fallback stays.
    #[test]
    fn condition_tokens_keep_the_binding_class_vocabulary() {
        assert_eq!(
            NestedErrorClass::ArgumentError.binding_class(),
            Some("ArgumentError")
        );
        assert_eq!(
            NestedErrorClass::ConstraintAlreadyExists.binding_class(),
            None
        );
        assert_eq!(NestedErrorClass::IndexDoesNotExist.binding_class(), None);
    }

    /// The canonical nested-class scan: the names the engine embeds are
    /// recovered, lookalikes are not, and every recovered class renders
    /// the token it was scanned from.
    #[test]
    fn nested_error_class_recovers_the_embedded_names() {
        assert_eq!(
            nested_error_class("ArgumentError: x"),
            Some(NestedErrorClass::ArgumentError)
        );
        assert_eq!(
            nested_error_class("outer context: ConstraintVerificationFailed: duplicate key"),
            Some(NestedErrorClass::ConstraintVerificationFailed)
        );
        assert_eq!(
            nested_error_class("outer: ConstraintValidationFailed: bad"),
            Some(NestedErrorClass::ConstraintVerificationFailed)
        );
        assert_eq!(nested_error_class("no class here"), None);
        assert_eq!(nested_error_class("nested ParameterMissing: p"), None);
        assert_eq!(nested_error_class(""), None);
    }

    /// The closed vocabulary: every class in [`NestedErrorClass::ALL`] is
    /// recovered from its own rendered token, so the enum, the scan and
    /// the wire spelling cannot drift.
    #[test]
    fn every_nested_class_renders_its_embedded_token() {
        for &class in NestedErrorClass::ALL {
            let token = class.as_str();
            let scanned = nested_error_class(&format!("{token}: x"))
                .unwrap_or_else(|| panic!("token {token} not recognized by the scan"));
            assert_eq!(scanned.as_str(), token);
        }
    }
}