lora-database 0.16.1

LoraDB — embeddable in-memory graph database with Cypher query support.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! Top-level error type and stable error-code catalog for LoraDB.
//!
//! Internal `lora-database` code still produces `anyhow::Result` because
//! `?`-chaining over many lower-layer error types is convenient. The
//! public boundary, however, surfaces a typed [`LoraError`] so transports
//! and bindings can route on the stable [`LoraErrorCode`] wire string
//! without parsing message text.
//!
//! # Stable contract
//!
//! - [`LoraErrorCode::as_str`] returns the wire string. These strings are
//!   part of the public API and never change between releases.
//! - [`LoraError::message`] returns a user-friendly clause. Wording **may**
//!   change between minor versions to improve clarity — bindings and
//!   integration tests must not match on it.
//! - [`LoraError::category`] returns whether the failure was the caller's
//!   fault (`Client`) or the engine's (`Server`). The HTTP layer uses this
//!   to pick the response status; bindings can use it to tag exceptions.
//!
//! See `docs/design/error-style.md` for the message style guide.

use std::error::Error;
use std::fmt;

use lora_analyzer::SemanticError;
use lora_executor::{ExecutorError, PropertyConversionError};
use lora_parser::ParseError;
use lora_snapshot::SnapshotCodecError;
use lora_store::SnapshotError;
use lora_wal::{WalBufferedCommitError, WalCommitError, WalError};
use thiserror::Error;

use crate::transaction::TransactionError;
use crate::DatabaseNameError;

/// Stable error-code catalog. The wire string returned by [`Self::as_str`]
/// is part of LoraDB's public API. Consumers — bindings, the HTTP layer,
/// integration tests — should match on this rather than on the message
/// text, which is allowed to change between releases.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoraErrorCode {
    // -------- Client errors --------
    /// Cypher syntax could not be parsed.
    Parse,
    /// Cypher analysis (unknown variable, label, function, type mismatch, …).
    Semantic,
    /// A parameter value passed by the caller could not be coerced.
    InvalidParams,
    /// A mutating statement was issued in a read-only context.
    ReadOnlyViolation,
    /// A named entity (database, label, key) does not exist.
    NotFound,
    /// A precondition (e.g. delete-with-relationships) is not satisfied.
    ConstraintViolation,
    /// A vector value failed dimension / coordinate-type validation.
    InvalidVector,
    /// A query exceeded its cooperative deadline.
    Timeout,
    /// A logical database name violates the portable-path rules.
    DatabaseName,
    /// Required parameters are missing or malformed (CLI / config flags).
    Config,
    /// A well-formed request failed database-layer validation.
    Validation,
    /// A uniqueness constraint rejected a duplicate value.
    UniqueConstraint,
    /// A property-existence / NOT NULL constraint rejected missing data.
    NotNullConstraint,
    /// A relationship or dependent record references a missing entity.
    ForeignKeyViolation,
    /// A transaction lifecycle rule was violated.
    TransactionFailure,
    /// The database directory is held by another process or live handle.
    Locked,
    /// A change feed was asked to resume from an LSN the database no
    /// longer retains (or never produced).
    ChangesTruncated,
    /// A change feed subscriber fell further behind than its buffer allows;
    /// resume from the last LSN it processed.
    ChangesLagged,

    // -------- Server errors --------
    /// I/O failure outside the WAL / snapshot boundaries.
    Io,
    /// The database could not open or use its backing connection/handle.
    Connection,
    /// WAL record was truncated, mis-CRC'd, or otherwise unreadable.
    WalCorruption,
    /// The WAL is poisoned and no longer accepts durable writes.
    WalPoisoned,
    /// Snapshot codec failure (bad magic, version, checksum, …).
    SnapshotCodec,
    /// Snapshot encryption / decryption / KDF failure.
    SnapshotCrypto,
    /// Last-resort fallback when the engine cannot classify the failure.
    Internal,
}

/// Whether a [`LoraErrorCode`] represents a caller-visible mistake or an
/// engine-side failure. Used by the HTTP transport to choose between
/// 4xx and 5xx status codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoraErrorCategory {
    Client,
    Server,
}

impl LoraErrorCategory {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Client => "client",
            Self::Server => "server",
        }
    }
}

impl LoraErrorCode {
    /// Stable wire string. Part of the public API — never changes.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Parse => "LORA_PARSE",
            Self::Semantic => "LORA_SEMANTIC",
            Self::InvalidParams => "LORA_INVALID_PARAMS",
            Self::ReadOnlyViolation => "LORA_READ_ONLY",
            Self::NotFound => "LORA_NOT_FOUND",
            Self::ConstraintViolation => "LORA_CONSTRAINT",
            Self::InvalidVector => "LORA_INVALID_VECTOR",
            Self::Timeout => "LORA_TIMEOUT",
            Self::DatabaseName => "LORA_DATABASE_NAME",
            Self::Config => "LORA_CONFIG",
            Self::Validation => "LORA_VALIDATION",
            Self::UniqueConstraint => "LORA_UNIQUE_CONSTRAINT",
            Self::NotNullConstraint => "LORA_NOT_NULL_CONSTRAINT",
            Self::ForeignKeyViolation => "LORA_FOREIGN_KEY",
            Self::TransactionFailure => "LORA_TRANSACTION",
            Self::Locked => "LORA_LOCKED",
            Self::ChangesTruncated => "LORA_CHANGES_TRUNCATED",
            Self::ChangesLagged => "LORA_CHANGES_LAGGED",
            Self::Io => "LORA_IO",
            Self::Connection => "LORA_CONNECTION",
            Self::WalCorruption => "LORA_WAL_CORRUPTION",
            Self::WalPoisoned => "LORA_WAL_POISONED",
            Self::SnapshotCodec => "LORA_SNAPSHOT_CODEC",
            Self::SnapshotCrypto => "LORA_SNAPSHOT_CRYPTO",
            Self::Internal => "LORA_INTERNAL",
        }
    }

    /// Whether this code is the caller's fault or the engine's.
    pub fn category(self) -> LoraErrorCategory {
        match self {
            Self::Parse
            | Self::Semantic
            | Self::InvalidParams
            | Self::ReadOnlyViolation
            | Self::NotFound
            | Self::ConstraintViolation
            | Self::InvalidVector
            | Self::Timeout
            | Self::DatabaseName
            | Self::Config
            | Self::Validation
            | Self::UniqueConstraint
            | Self::NotNullConstraint
            | Self::ForeignKeyViolation
            | Self::TransactionFailure
            | Self::Locked
            | Self::ChangesTruncated
            | Self::ChangesLagged => LoraErrorCategory::Client,
            Self::Io
            | Self::Connection
            | Self::WalCorruption
            | Self::WalPoisoned
            | Self::SnapshotCodec
            | Self::SnapshotCrypto
            | Self::Internal => LoraErrorCategory::Server,
        }
    }
}

impl fmt::Display for LoraErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Public error type at the `lora-database` boundary.
///
/// Construct via [`Self::from_anyhow`] (the typical path — the engine
/// uses `anyhow::Error` internally) or via the `From` impls for any
/// known concrete error type.
pub struct LoraError {
    code: LoraErrorCode,
    message: String,
    source: Option<Box<dyn Error + Send + Sync + 'static>>,
}

#[derive(Debug)]
struct InternalAnyhowSource(String);

impl fmt::Display for InternalAnyhowSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Error for InternalAnyhowSource {}

impl LoraError {
    pub fn new(code: LoraErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            source: None,
        }
    }

    pub fn with_source(
        code: LoraErrorCode,
        message: impl Into<String>,
        source: impl Error + Send + Sync + 'static,
    ) -> Self {
        Self {
            code,
            message: message.into(),
            source: Some(Box::new(source)),
        }
    }

    pub fn code(&self) -> LoraErrorCode {
        self.code
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn category(&self) -> LoraErrorCategory {
        self.code.category()
    }

    /// Message intended for external transports. Client-side errors keep
    /// their precise text; server-side failures return a stable, sanitized
    /// sentence while the original details stay available through
    /// [`Self::message`] for logs and local debugging.
    pub fn public_message(&self) -> String {
        match self.category() {
            LoraErrorCategory::Client => self.message.clone(),
            LoraErrorCategory::Server => match self.code {
                LoraErrorCode::Io => "database storage is temporarily unavailable".to_string(),
                LoraErrorCode::Connection => {
                    "database connection is temporarily unavailable".to_string()
                }
                LoraErrorCode::WalCorruption => {
                    "database write-ahead log is unreadable".to_string()
                }
                LoraErrorCode::WalPoisoned => {
                    "database write-ahead log is unavailable until recovery".to_string()
                }
                LoraErrorCode::SnapshotCodec => "snapshot data could not be decoded".to_string(),
                LoraErrorCode::SnapshotCrypto => {
                    "snapshot encryption could not be processed".to_string()
                }
                LoraErrorCode::Internal => "database operation failed unexpectedly".to_string(),
                // Exhaustive for future-proofing: if a code's category
                // changes, expose the original client-facing text.
                _ => self.message.clone(),
            },
        }
    }

    /// Detailed cause chain for diagnostics. Do not put this in
    /// user-facing response bodies.
    pub fn debug_context(&self) -> String {
        let mut out = self.message.clone();
        let mut source = self.source();
        while let Some(err) = source {
            out.push_str(": ");
            out.push_str(&err.to_string());
            source = err.source();
        }
        out
    }

    /// Convert an `anyhow::Error` from the engine's internal `?`-chains
    /// into a typed `LoraError`. Best-effort: downcasts the chain to any
    /// known concrete error type and picks the matching code; falls back
    /// to [`LoraErrorCode::Internal`] with the original message preserved.
    pub fn from_anyhow(err: anyhow::Error) -> Self {
        let mapped = Self::from_anyhow_ref(&err);
        if mapped.code == LoraErrorCode::Internal {
            Self::with_source(
                LoraErrorCode::Internal,
                "database operation failed unexpectedly",
                InternalAnyhowSource(format!("{err:#}")),
            )
        } else {
            mapped
        }
    }

    /// Borrowed version of [`Self::from_anyhow`]. Useful in binding
    /// layers that hold `&anyhow::Error` from a `Result::Err` capture
    /// and don't want to move the error.
    pub fn from_anyhow_ref(err: &anyhow::Error) -> Self {
        // If the chain already carries a typed `LoraError` (because some
        // intermediate layer wrapped one with `?` or `.into()`), preserve
        // its code rather than re-classifying as `Internal`.
        if let Some(e) = err.downcast_ref::<LoraError>() {
            return Self::new(e.code, e.message.clone());
        }
        if let Some(e) = err.downcast_ref::<ParseError>() {
            return Self::new(LoraErrorCode::Parse, e.to_string());
        }
        if let Some(e) = err.downcast_ref::<SemanticError>() {
            return Self::new(LoraErrorCode::Semantic, e.to_string());
        }
        if let Some(e) = err.downcast_ref::<ExecutorError>() {
            return Self::new(executor_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<PropertyConversionError>() {
            return Self::new(LoraErrorCode::Validation, e.to_string());
        }
        if let Some(e) = err.downcast_ref::<WalError>() {
            return Self::new(wal_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<WalCommitError>() {
            return Self::new(wal_commit_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<WalBufferedCommitError>() {
            return Self::new(wal_buffered_commit_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<SnapshotCodecError>() {
            return Self::new(snapshot_codec_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<SnapshotError>() {
            return Self::new(snapshot_store_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<DatabaseNameError>() {
            return Self::new(LoraErrorCode::DatabaseName, e.to_string());
        }
        if let Some(e) = err.downcast_ref::<TransactionError>() {
            return Self::new(transaction_code(e), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<DatabaseOperationError>() {
            return Self::new(e.code(), e.to_string());
        }
        if let Some(e) = err.downcast_ref::<std::io::Error>() {
            return Self::new(io_code(e), e.to_string());
        }
        if let Some(code) = legacy_message_code(&err.to_string()) {
            return Self::new(code, err.to_string());
        }
        // Fallback: an external `anyhow::Error` we don't recognise. Internal
        // sites all surface typed errors that the downcasts above route
        // precisely, so anything that lands here is from a third-party crate
        // or a legacy `anyhow!("...")` we have not yet converted.
        Self::new(
            LoraErrorCode::Internal,
            "database operation failed unexpectedly",
        )
    }
}

fn executor_code(err: &ExecutorError) -> LoraErrorCode {
    match err {
        ExecutorError::ReadOnlyCreate { .. }
        | ExecutorError::ReadOnlyMerge { .. }
        | ExecutorError::ReadOnlyDelete { .. }
        | ExecutorError::ReadOnlySet { .. }
        | ExecutorError::ReadOnlyRemove { .. }
        | ExecutorError::ReadOnlyForeach { .. } => LoraErrorCode::ReadOnlyViolation,
        ExecutorError::QueryTimeout => LoraErrorCode::Timeout,
        ExecutorError::ConstraintViolation(message) => constraint_message_code(message),
        ExecutorError::DeleteNodeWithRelationships { .. } => LoraErrorCode::ForeignKeyViolation,
        ExecutorError::RelationshipCreateFailed { .. } => LoraErrorCode::ForeignKeyViolation,
        ExecutorError::NodeCreateFailed => LoraErrorCode::Internal,
        ExecutorError::RuntimeError(message) => validation_message_code(message),
        ExecutorError::ExpectedNodeForExpand { .. }
        | ExecutorError::ExpectedPropertyMap { .. }
        | ExecutorError::GroupByNotLowered
        | ExecutorError::AggregateNotLowered
        | ExecutorError::UnsupportedCreateRelationshipRange
        | ExecutorError::MissingRelationshipType
        | ExecutorError::DeleteRelationshipFailed { .. }
        | ExecutorError::InvalidDeleteTarget { .. }
        | ExecutorError::ExpectedNodeForRemoveLabels { .. }
        | ExecutorError::UnboundVariableForRemove { .. }
        | ExecutorError::ExpectedNodeForSetLabels { .. }
        | ExecutorError::UnboundVariableForSet { .. }
        | ExecutorError::InvalidSetTarget { .. }
        | ExecutorError::UnsupportedRemoveTarget
        | ExecutorError::InvalidRemoveTarget { .. }
        | ExecutorError::UnsupportedSetTarget
        | ExecutorError::ExpectedRelationshipForExpand { .. } => LoraErrorCode::Validation,
    }
}

fn constraint_message_code(message: &str) -> LoraErrorCode {
    if message.contains("22N79") || message.contains("22N70") || message.contains("22N71") {
        LoraErrorCode::UniqueConstraint
    } else if message.contains("22N77") {
        LoraErrorCode::NotNullConstraint
    } else if message.contains("42N51") {
        LoraErrorCode::NotFound
    } else if message.contains("22N78") || message.contains("22N90") {
        LoraErrorCode::Validation
    } else {
        LoraErrorCode::ConstraintViolation
    }
}

fn validation_message_code(message: &str) -> LoraErrorCode {
    let lower = message.to_ascii_lowercase();
    if lower.contains("vector") {
        LoraErrorCode::InvalidVector
    } else {
        LoraErrorCode::Validation
    }
}

fn legacy_message_code(message: &str) -> Option<LoraErrorCode> {
    if message.contains("22N")
        || message.contains("42N51")
        || message.contains("50N11")
        || message.contains("constraint")
        || message.contains("CONSTRAINT")
    {
        return Some(constraint_message_code(message));
    }
    None
}

fn wal_code(err: &WalError) -> LoraErrorCode {
    match err {
        WalError::Io(inner) => io_code(inner),
        WalError::AlreadyOpen { .. } => LoraErrorCode::Locked,
        WalError::CrcMismatch { .. }
        | WalError::Truncated { .. }
        | WalError::UnknownKind(_)
        | WalError::BadSegmentHeader(_)
        | WalError::Malformed(_)
        | WalError::Encode(_)
        | WalError::Decode(_) => LoraErrorCode::WalCorruption,
        WalError::Poisoned => LoraErrorCode::WalPoisoned,
    }
}

fn io_code(err: &std::io::Error) -> LoraErrorCode {
    match err.kind() {
        std::io::ErrorKind::ConnectionRefused
        | std::io::ErrorKind::ConnectionReset
        | std::io::ErrorKind::ConnectionAborted
        | std::io::ErrorKind::NotConnected
        | std::io::ErrorKind::AddrInUse
        | std::io::ErrorKind::AddrNotAvailable => LoraErrorCode::Connection,
        std::io::ErrorKind::TimedOut => LoraErrorCode::Timeout,
        _ => LoraErrorCode::Io,
    }
}

fn wal_commit_code(err: &WalCommitError) -> LoraErrorCode {
    match err {
        WalCommitError::Commit(inner) | WalCommitError::Flush(inner) => wal_code(inner),
    }
}

fn wal_buffered_commit_code(err: &WalBufferedCommitError) -> LoraErrorCode {
    match err {
        WalBufferedCommitError::Arm(inner) => wal_code(inner),
        WalBufferedCommitError::Poisoned(_) | WalBufferedCommitError::ReplayPoisoned(_) => {
            LoraErrorCode::WalPoisoned
        }
        WalBufferedCommitError::Commit(inner) => wal_commit_code(inner),
    }
}

fn snapshot_codec_code(err: &SnapshotCodecError) -> LoraErrorCode {
    match err {
        SnapshotCodecError::Io(inner) => io_code(inner),
        SnapshotCodecError::MissingEncryptionKey(_)
        | SnapshotCodecError::MissingPassword(_)
        | SnapshotCodecError::PasswordKdf(_)
        | SnapshotCodecError::Encrypt
        | SnapshotCodecError::Decrypt => LoraErrorCode::SnapshotCrypto,
        SnapshotCodecError::BadMagic
        | SnapshotCodecError::UnsupportedVersion(_)
        | SnapshotCodecError::UnsupportedCompression(_)
        | SnapshotCodecError::ChecksumMismatch
        | SnapshotCodecError::Encode(_)
        | SnapshotCodecError::Decode(_) => LoraErrorCode::SnapshotCodec,
    }
}

fn snapshot_store_code(err: &SnapshotError) -> LoraErrorCode {
    match err {
        SnapshotError::Io(inner) => io_code(inner),
        SnapshotError::Decode(_) | SnapshotError::Encode(_) => LoraErrorCode::SnapshotCodec,
    }
}

fn transaction_code(err: &TransactionError) -> LoraErrorCode {
    match err {
        TransactionError::ReadOnlyMutation
        | TransactionError::ReadOnlyCommit
        | TransactionError::StreamingRequiresReadWrite => LoraErrorCode::ReadOnlyViolation,
        TransactionError::AlreadyClosed
        | TransactionError::CursorActiveCommit
        | TransactionError::CursorActiveStatement => LoraErrorCode::TransactionFailure,
        TransactionError::NoGraphGuard
        | TransactionError::NoStagedGraph
        | TransactionError::Poisoned => LoraErrorCode::TransactionFailure,
    }
}

#[derive(Debug, Clone, Error)]
pub(crate) enum DatabaseOperationError {
    #[error("{0}")]
    InvalidParams(String),
    #[error("{0}")]
    InvalidVector(String),
    #[error("{0}")]
    Validation(String),
    #[error("{0}")]
    NotFound(String),
    #[error("{0}")]
    ConstraintViolation(String),
    #[error("{0}")]
    UniqueConstraint(String),
    #[error("{0}")]
    NotNullConstraint(String),
}

impl DatabaseOperationError {
    pub(crate) fn invalid_params(message: impl Into<String>) -> Self {
        Self::InvalidParams(message.into())
    }

    pub(crate) fn invalid_vector(message: impl Into<String>) -> Self {
        Self::InvalidVector(message.into())
    }

    pub(crate) fn validation(message: impl Into<String>) -> Self {
        Self::Validation(message.into())
    }

    pub(crate) fn not_found(message: impl Into<String>) -> Self {
        Self::NotFound(message.into())
    }

    pub(crate) fn constraint_violation(message: impl Into<String>) -> Self {
        Self::ConstraintViolation(message.into())
    }

    pub(crate) fn unique_constraint(message: impl Into<String>) -> Self {
        Self::UniqueConstraint(message.into())
    }

    pub(crate) fn not_null_constraint(message: impl Into<String>) -> Self {
        Self::NotNullConstraint(message.into())
    }

    pub(crate) fn code(&self) -> LoraErrorCode {
        match self {
            Self::InvalidParams(_) => LoraErrorCode::InvalidParams,
            Self::InvalidVector(_) => LoraErrorCode::InvalidVector,
            Self::Validation(_) => LoraErrorCode::Validation,
            Self::NotFound(_) => LoraErrorCode::NotFound,
            Self::ConstraintViolation(_) => LoraErrorCode::ConstraintViolation,
            Self::UniqueConstraint(_) => LoraErrorCode::UniqueConstraint,
            Self::NotNullConstraint(_) => LoraErrorCode::NotNullConstraint,
        }
    }
}

impl fmt::Debug for LoraError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LoraError")
            .field("code", &self.code)
            .field("message", &self.message)
            .finish()
    }
}

impl fmt::Display for LoraError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl Error for LoraError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

// -------- From impls for direct construction --------

impl From<ParseError> for LoraError {
    fn from(e: ParseError) -> Self {
        let msg = e.to_string();
        Self::with_source(LoraErrorCode::Parse, msg, e)
    }
}

impl From<SemanticError> for LoraError {
    fn from(e: SemanticError) -> Self {
        let msg = e.to_string();
        Self::with_source(LoraErrorCode::Semantic, msg, e)
    }
}

impl From<ExecutorError> for LoraError {
    fn from(e: ExecutorError) -> Self {
        let code = executor_code(&e);
        let msg = e.to_string();
        Self::with_source(code, msg, e)
    }
}

impl From<PropertyConversionError> for LoraError {
    fn from(e: PropertyConversionError) -> Self {
        let msg = e.to_string();
        Self::with_source(LoraErrorCode::Validation, msg, e)
    }
}

impl From<WalError> for LoraError {
    fn from(e: WalError) -> Self {
        let code = wal_code(&e);
        let msg = e.to_string();
        Self::with_source(code, msg, e)
    }
}

impl From<SnapshotCodecError> for LoraError {
    fn from(e: SnapshotCodecError) -> Self {
        let code = snapshot_codec_code(&e);
        let msg = e.to_string();
        Self::with_source(code, msg, e)
    }
}

impl From<SnapshotError> for LoraError {
    fn from(e: SnapshotError) -> Self {
        let code = snapshot_store_code(&e);
        let msg = e.to_string();
        Self::with_source(code, msg, e)
    }
}

impl From<DatabaseNameError> for LoraError {
    fn from(e: DatabaseNameError) -> Self {
        let msg = e.to_string();
        Self::with_source(LoraErrorCode::DatabaseName, msg, e)
    }
}

impl From<TransactionError> for LoraError {
    fn from(e: TransactionError) -> Self {
        let code = transaction_code(&e);
        let msg = e.to_string();
        Self::with_source(code, msg, e)
    }
}

impl From<std::io::Error> for LoraError {
    fn from(e: std::io::Error) -> Self {
        let code = io_code(&e);
        let msg = e.to_string();
        Self::with_source(code, msg, e)
    }
}

impl From<anyhow::Error> for LoraError {
    fn from(e: anyhow::Error) -> Self {
        Self::from_anyhow(e)
    }
}

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

    #[test]
    fn parse_error_is_client_parse() {
        let e = ParseError::new("expected `MATCH`", 0, 5);
        let mapped: LoraError = anyhow::Error::from(e).into();
        assert_eq!(mapped.code(), LoraErrorCode::Parse);
        assert_eq!(mapped.category(), LoraErrorCategory::Client);
        assert!(mapped.message().contains("parse error"));
    }

    #[test]
    fn semantic_error_is_client_semantic() {
        let e = SemanticError::UnknownVariable("n".into());
        let mapped = LoraError::from(e);
        assert_eq!(mapped.code(), LoraErrorCode::Semantic);
        assert_eq!(mapped.message(), "unknown variable `n`");
    }

    #[test]
    fn executor_timeout_is_client_timeout() {
        let mapped = LoraError::from(ExecutorError::QueryTimeout);
        assert_eq!(mapped.code(), LoraErrorCode::Timeout);
    }

    #[test]
    fn wal_io_is_server_io() {
        let inner = std::io::Error::other("disk full");
        let mapped = LoraError::from(WalError::Io(inner));
        assert_eq!(mapped.code(), LoraErrorCode::Io);
        assert_eq!(mapped.category(), LoraErrorCategory::Server);
    }

    #[test]
    fn unknown_anyhow_falls_back_to_internal() {
        let e = anyhow::anyhow!("something else entirely");
        let mapped = LoraError::from_anyhow(e);
        assert_eq!(mapped.code(), LoraErrorCode::Internal);
        assert_eq!(mapped.message(), "database operation failed unexpectedly");
        assert!(mapped.debug_context().contains("something else entirely"));
    }

    #[test]
    fn typed_transaction_error_routes_readonly() {
        let mapped = LoraError::from(TransactionError::ReadOnlyMutation);
        assert_eq!(mapped.code(), LoraErrorCode::ReadOnlyViolation);
        assert_eq!(
            mapped.message(),
            "cannot execute mutating query in read-only transaction"
        );
    }

    #[test]
    fn typed_transaction_error_round_trips_through_anyhow() {
        let any: anyhow::Error = TransactionError::AlreadyClosed.into();
        let mapped = LoraError::from_anyhow(any);
        assert_eq!(mapped.code(), LoraErrorCode::TransactionFailure);
        assert_eq!(mapped.message(), "transaction is already closed");
    }

    #[test]
    fn code_wire_strings_are_stable() {
        // Sanity check: these strings are part of the public API and
        // must not change between releases.
        assert_eq!(LoraErrorCode::Parse.as_str(), "LORA_PARSE");
        assert_eq!(LoraErrorCode::Timeout.as_str(), "LORA_TIMEOUT");
        assert_eq!(LoraErrorCode::WalPoisoned.as_str(), "LORA_WAL_POISONED");
        assert_eq!(
            LoraErrorCode::UniqueConstraint.as_str(),
            "LORA_UNIQUE_CONSTRAINT"
        );
        assert_eq!(
            LoraErrorCode::NotNullConstraint.as_str(),
            "LORA_NOT_NULL_CONSTRAINT"
        );
        assert_eq!(LoraErrorCode::Connection.as_str(), "LORA_CONNECTION");
        assert_eq!(LoraErrorCode::Locked.as_str(), "LORA_LOCKED");
        assert_eq!(
            LoraErrorCode::ChangesTruncated.as_str(),
            "LORA_CHANGES_TRUNCATED"
        );
        assert_eq!(LoraErrorCode::ChangesLagged.as_str(), "LORA_CHANGES_LAGGED");
        assert_eq!(LoraErrorCode::Internal.as_str(), "LORA_INTERNAL");
    }

    #[test]
    fn constraint_messages_route_to_specific_codes() {
        let unique = LoraError::from(ExecutorError::ConstraintViolation(
            "[22N79] property uniqueness constraint violated".into(),
        ));
        assert_eq!(unique.code(), LoraErrorCode::UniqueConstraint);

        let not_null = LoraError::from(ExecutorError::ConstraintViolation(
            "[22N77] property presence verification failed".into(),
        ));
        assert_eq!(not_null.code(), LoraErrorCode::NotNullConstraint);

        let missing = LoraError::from_anyhow(anyhow::anyhow!(
            "[42N51] no index named `missing` exists in the catalog"
        ));
        assert_eq!(missing.code(), LoraErrorCode::NotFound);
    }

    #[test]
    fn database_operation_errors_route_to_specific_codes() {
        let cases = [
            (
                DatabaseOperationError::invalid_params("bad params"),
                LoraErrorCode::InvalidParams,
            ),
            (
                DatabaseOperationError::invalid_vector("bad vector"),
                LoraErrorCode::InvalidVector,
            ),
            (
                DatabaseOperationError::validation("bad request"),
                LoraErrorCode::Validation,
            ),
            (
                DatabaseOperationError::not_found("missing"),
                LoraErrorCode::NotFound,
            ),
            (
                DatabaseOperationError::constraint_violation("conflict"),
                LoraErrorCode::ConstraintViolation,
            ),
            (
                DatabaseOperationError::unique_constraint("duplicate"),
                LoraErrorCode::UniqueConstraint,
            ),
            (
                DatabaseOperationError::not_null_constraint("missing property"),
                LoraErrorCode::NotNullConstraint,
            ),
        ];

        for (err, code) in cases {
            let mapped = LoraError::from_anyhow(err.into());
            assert_eq!(mapped.code(), code);
            assert_eq!(mapped.category(), code.category());
        }
    }

    #[test]
    fn connection_io_routes_to_connection() {
        let mapped = LoraError::from(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "refused",
        ));
        assert_eq!(mapped.code(), LoraErrorCode::Connection);
    }

    #[test]
    fn public_message_sanitizes_server_details() {
        let err = LoraError::new(LoraErrorCode::Internal, "panic: secret path /tmp/db");
        assert_eq!(
            err.public_message(),
            "database operation failed unexpectedly"
        );
        assert_eq!(err.message(), "panic: secret path /tmp/db");
    }
}