shodh-redb 0.1.0

Multi-modal embedded database — vectors, blobs, TTL, merge operators, and causal tracking built on ACID B-trees
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
use crate::tree_store::{FILE_FORMAT_VERSION3, MAX_VALUE_LENGTH};
use crate::{ReadTransaction, TypeName};
use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use core::fmt::{Display, Formatter};
use core::panic;

#[cfg(feature = "std")]
use crate::group_commit::GroupCommitError;
#[cfg(feature = "std")]
use std::sync::PoisonError;

/// Error type for storage backend operations.
///
/// Under `std`, this wraps `std::io::Error`. Under `no_std`, it provides
/// a string-based error representation.
#[derive(Debug)]
pub enum BackendError {
    #[cfg(feature = "std")]
    Io(std::io::Error),
    #[cfg(not(feature = "std"))]
    Message(String),
}

impl Display for BackendError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(feature = "std")]
            BackendError::Io(err) => write!(f, "{err}"),
            #[cfg(not(feature = "std"))]
            BackendError::Message(msg) => write!(f, "{msg}"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for BackendError {}

#[cfg(feature = "std")]
impl From<std::io::Error> for BackendError {
    fn from(err: std::io::Error) -> Self {
        BackendError::Io(err)
    }
}

impl BackendError {
    /// Returns the `ErrorKind` of the underlying I/O error.
    #[cfg(feature = "std")]
    pub fn kind(&self) -> std::io::ErrorKind {
        match self {
            BackendError::Io(e) => e.kind(),
        }
    }
}

/// General errors directly from the storage layer
#[derive(Debug)]
#[non_exhaustive]
pub enum StorageError {
    /// The Database is corrupted
    Corrupted(String),
    /// The value being inserted exceeds the maximum of 3GiB
    ValueTooLarge(usize),
    /// A blob with the given sequence ID was not found in the blob store
    BlobNotFound(u64),
    /// Blob data checksum does not match the stored checksum
    BlobChecksumMismatch {
        /// Blob sequence number
        sequence: u64,
        /// Checksum stored in metadata
        expected: u128,
        /// Checksum computed from the blob data
        actual: u128,
    },
    /// A streaming blob writer is already active on this transaction
    BlobWriterActive,
    /// The requested byte range exceeds the blob's length
    BlobRangeOutOfBounds {
        /// Total blob length in bytes
        blob_length: u64,
        /// Requested range start offset
        requested_offset: u64,
        /// Requested range length
        requested_length: u64,
    },
    /// The configured memory budget has been exceeded and the operation cannot proceed
    MemoryBudgetExceeded {
        /// The configured memory budget in bytes
        budget: usize,
        /// Current memory usage in bytes
        used: usize,
    },
    Io(BackendError),
    PreviousIo,
    DatabaseClosed,
    LockPoisoned(&'static panic::Location<'static>),
}

#[cfg(feature = "std")]
impl<T> From<PoisonError<T>> for StorageError {
    fn from(_: PoisonError<T>) -> StorageError {
        StorageError::LockPoisoned(panic::Location::caller())
    }
}

impl From<BackendError> for StorageError {
    fn from(err: BackendError) -> StorageError {
        StorageError::Io(err)
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for StorageError {
    fn from(err: std::io::Error) -> StorageError {
        StorageError::Io(BackendError::Io(err))
    }
}

impl From<StorageError> for Error {
    fn from(err: StorageError) -> Error {
        match err {
            StorageError::Corrupted(msg) => Error::Corrupted(msg),
            StorageError::ValueTooLarge(x) => Error::ValueTooLarge(x),
            StorageError::BlobNotFound(seq) => Error::BlobNotFound(seq),
            StorageError::BlobChecksumMismatch {
                sequence,
                expected,
                actual,
            } => Error::BlobChecksumMismatch {
                sequence,
                expected,
                actual,
            },
            StorageError::BlobWriterActive => Error::BlobWriterActive,
            StorageError::BlobRangeOutOfBounds {
                blob_length,
                requested_offset,
                requested_length,
            } => Error::BlobRangeOutOfBounds {
                blob_length,
                requested_offset,
                requested_length,
            },
            StorageError::MemoryBudgetExceeded { budget, used } => {
                Error::MemoryBudgetExceeded { budget, used }
            }
            StorageError::Io(x) => Error::Io(x),
            StorageError::PreviousIo => Error::PreviousIo,
            StorageError::DatabaseClosed => Error::DatabaseClosed,
            StorageError::LockPoisoned(location) => Error::LockPoisoned(location),
        }
    }
}

impl Display for StorageError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            StorageError::Corrupted(msg) => {
                write!(f, "DB corrupted: {msg}")
            }
            StorageError::ValueTooLarge(len) => {
                write!(
                    f,
                    "The value (length={len}) being inserted exceeds the maximum of {}GiB",
                    MAX_VALUE_LENGTH / 1024 / 1024 / 1024
                )
            }
            StorageError::BlobNotFound(seq) => {
                write!(f, "Blob not found: sequence={seq}")
            }
            StorageError::BlobChecksumMismatch {
                sequence,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "Blob checksum mismatch: sequence={sequence}, expected={expected:#034x}, actual={actual:#034x}"
                )
            }
            StorageError::BlobWriterActive => {
                write!(
                    f,
                    "Cannot create blob writer or store blob while another writer is active"
                )
            }
            StorageError::BlobRangeOutOfBounds {
                blob_length,
                requested_offset,
                requested_length,
            } => {
                write!(
                    f,
                    "Blob range out of bounds: blob_length={blob_length}, requested offset={requested_offset}, length={requested_length}"
                )
            }
            StorageError::MemoryBudgetExceeded { budget, used } => {
                write!(
                    f,
                    "Memory budget exceeded: budget={budget} bytes, used={used} bytes"
                )
            }
            StorageError::Io(err) => {
                write!(f, "I/O error: {err}")
            }
            StorageError::DatabaseClosed => {
                write!(f, "Database has been closed")
            }
            StorageError::PreviousIo => {
                write!(
                    f,
                    "Previous I/O error occurred. Please close and re-open the database."
                )
            }
            StorageError::LockPoisoned(location) => {
                write!(f, "Poisoned internal lock: {location}")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StorageError {}

/// Errors related to opening tables
#[derive(Debug)]
#[non_exhaustive]
pub enum TableError {
    /// Table types didn't match.
    TableTypeMismatch {
        table: String,
        key: TypeName,
        value: TypeName,
    },
    /// The table is a multimap table
    TableIsMultimap(String),
    /// The table is not a multimap table
    TableIsNotMultimap(String),
    TypeDefinitionChanged {
        name: TypeName,
        alignment: usize,
        width: Option<usize>,
    },
    /// Table name does not match any table in database
    TableDoesNotExist(String),
    /// Table name already exists in the database
    TableExists(String),
    // Tables cannot be opened for writing multiple times, since they could retrieve immutable &
    // mutable references to the same dirty pages, or multiple mutable references via insert_reserve()
    TableAlreadyOpen(String, &'static panic::Location<'static>),
    /// Error from underlying storage
    Storage(StorageError),
}

impl TableError {
    pub(crate) fn into_storage_error_or_corrupted(self, msg: &str) -> StorageError {
        match self {
            TableError::TableTypeMismatch { .. }
            | TableError::TableIsMultimap(_)
            | TableError::TableIsNotMultimap(_)
            | TableError::TypeDefinitionChanged { .. }
            | TableError::TableDoesNotExist(_)
            | TableError::TableExists(_)
            | TableError::TableAlreadyOpen(_, _) => {
                StorageError::Corrupted(format!("{msg}: {self}"))
            }
            TableError::Storage(storage) => storage,
        }
    }
}

impl From<TableError> for Error {
    fn from(err: TableError) -> Error {
        match err {
            TableError::TypeDefinitionChanged {
                name,
                alignment,
                width,
            } => Error::TypeDefinitionChanged {
                name,
                alignment,
                width,
            },
            TableError::TableTypeMismatch { table, key, value } => {
                Error::TableTypeMismatch { table, key, value }
            }
            TableError::TableIsMultimap(table) => Error::TableIsMultimap(table),
            TableError::TableIsNotMultimap(table) => Error::TableIsNotMultimap(table),
            TableError::TableDoesNotExist(table) => Error::TableDoesNotExist(table),
            TableError::TableExists(table) => Error::TableExists(table),
            TableError::TableAlreadyOpen(name, location) => Error::TableAlreadyOpen(name, location),
            TableError::Storage(storage) => storage.into(),
        }
    }
}

impl From<StorageError> for TableError {
    fn from(err: StorageError) -> TableError {
        TableError::Storage(err)
    }
}

impl Display for TableError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            TableError::TypeDefinitionChanged {
                name,
                alignment,
                width,
            } => {
                write!(
                    f,
                    "Current definition of {} does not match stored definition (width={:?}, alignment={})",
                    name.name(),
                    width,
                    alignment,
                )
            }
            TableError::TableTypeMismatch { table, key, value } => {
                write!(
                    f,
                    "{table} is of type Table<{}, {}>",
                    key.name(),
                    value.name(),
                )
            }
            TableError::TableIsMultimap(table) => {
                write!(f, "{table} is a multimap table")
            }
            TableError::TableIsNotMultimap(table) => {
                write!(f, "{table} is not a multimap table")
            }
            TableError::TableDoesNotExist(table) => {
                write!(f, "Table '{table}' does not exist")
            }
            TableError::TableExists(table) => {
                write!(f, "Table '{table}' already exists")
            }
            TableError::TableAlreadyOpen(name, location) => {
                write!(f, "Table '{name}' already opened at: {location}")
            }
            TableError::Storage(storage) => storage.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for TableError {}

/// Errors related to opening a database
#[derive(Debug)]
#[non_exhaustive]
pub enum DatabaseError {
    /// The Database is already open. Cannot acquire lock.
    DatabaseAlreadyOpen,
    /// [`crate::RepairSession::abort`] was called or repair was aborted for another reason (such as the database being read-only).
    RepairAborted,
    /// The database file is in an old file format and must be manually upgraded
    UpgradeRequired(u8),
    /// Error from underlying storage
    Storage(StorageError),
}

impl From<DatabaseError> for Error {
    fn from(err: DatabaseError) -> Error {
        match err {
            DatabaseError::DatabaseAlreadyOpen => Error::DatabaseAlreadyOpen,
            DatabaseError::RepairAborted => Error::RepairAborted,
            DatabaseError::UpgradeRequired(x) => Error::UpgradeRequired(x),
            DatabaseError::Storage(storage) => storage.into(),
        }
    }
}

impl From<BackendError> for DatabaseError {
    fn from(err: BackendError) -> DatabaseError {
        DatabaseError::Storage(StorageError::Io(err))
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for DatabaseError {
    fn from(err: std::io::Error) -> DatabaseError {
        DatabaseError::Storage(StorageError::Io(BackendError::Io(err)))
    }
}

impl From<StorageError> for DatabaseError {
    fn from(err: StorageError) -> DatabaseError {
        DatabaseError::Storage(err)
    }
}

impl Display for DatabaseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            DatabaseError::UpgradeRequired(actual) => {
                write!(
                    f,
                    "Manual upgrade required. Expected file format version {FILE_FORMAT_VERSION3}, but file is version {actual}"
                )
            }
            DatabaseError::RepairAborted => {
                write!(f, "Database repair aborted.")
            }
            DatabaseError::DatabaseAlreadyOpen => {
                write!(f, "Database already open. Cannot acquire lock.")
            }
            DatabaseError::Storage(storage) => storage.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DatabaseError {}

/// Errors related to savepoints
#[derive(Debug)]
#[non_exhaustive]
pub enum SavepointError {
    /// This savepoint is invalid or cannot be created.
    ///
    /// Savepoints become invalid when an older savepoint is restored after it was created,
    /// and savepoints cannot be created if the transaction is "dirty" (any tables have been opened)
    InvalidSavepoint,
    /// Error from underlying storage
    Storage(StorageError),
}

impl From<SavepointError> for Error {
    fn from(err: SavepointError) -> Error {
        match err {
            SavepointError::InvalidSavepoint => Error::InvalidSavepoint,
            SavepointError::Storage(storage) => storage.into(),
        }
    }
}

impl From<StorageError> for SavepointError {
    fn from(err: StorageError) -> SavepointError {
        SavepointError::Storage(err)
    }
}

impl Display for SavepointError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            SavepointError::InvalidSavepoint => {
                write!(f, "Savepoint is invalid or cannot be created.")
            }
            SavepointError::Storage(storage) => storage.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for SavepointError {}

/// Errors related to compaction
#[derive(Debug)]
#[non_exhaustive]
pub enum CompactionError {
    /// A persistent savepoint exists
    PersistentSavepointExists,
    /// A ephemeral savepoint exists
    EphemeralSavepointExists,
    /// A transaction is still in-progress
    TransactionInProgress,
    /// Error from underlying storage
    Storage(StorageError),
}

impl From<CompactionError> for Error {
    fn from(err: CompactionError) -> Error {
        match err {
            CompactionError::PersistentSavepointExists => Error::PersistentSavepointExists,
            CompactionError::EphemeralSavepointExists => Error::EphemeralSavepointExists,
            CompactionError::TransactionInProgress => Error::TransactionInProgress,
            CompactionError::Storage(storage) => storage.into(),
        }
    }
}

impl From<StorageError> for CompactionError {
    fn from(err: StorageError) -> CompactionError {
        CompactionError::Storage(err)
    }
}

impl Display for CompactionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            CompactionError::PersistentSavepointExists => {
                write!(
                    f,
                    "Persistent savepoint exists. Operation cannot be performed."
                )
            }
            CompactionError::EphemeralSavepointExists => {
                write!(
                    f,
                    "Ephemeral savepoint exists. Operation cannot be performed."
                )
            }
            CompactionError::TransactionInProgress => {
                write!(
                    f,
                    "A transaction is still in progress. Operation cannot be performed."
                )
            }
            CompactionError::Storage(storage) => storage.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for CompactionError {}

/// Errors related to transactions
#[derive(Debug)]
#[non_exhaustive]
pub enum SetDurabilityError {
    /// A persistent savepoint was modified
    PersistentSavepointModified,
}

impl From<SetDurabilityError> for Error {
    fn from(err: SetDurabilityError) -> Error {
        match err {
            SetDurabilityError::PersistentSavepointModified => Error::PersistentSavepointModified,
        }
    }
}

impl Display for SetDurabilityError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            SetDurabilityError::PersistentSavepointModified => {
                write!(
                    f,
                    "Persistent savepoint modified. Cannot reduce transaction durability"
                )
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for SetDurabilityError {}

/// Errors related to transactions
#[derive(Debug)]
#[non_exhaustive]
pub enum TransactionError {
    /// Error from underlying storage
    Storage(StorageError),
    /// The transaction is still referenced by a table or other object
    ReadTransactionStillInUse(Box<ReadTransaction>),
}

impl TransactionError {
    pub(crate) fn into_storage_error(self) -> StorageError {
        match self {
            TransactionError::Storage(storage) => storage,
            _ => unreachable!(),
        }
    }
}

impl From<TransactionError> for Error {
    fn from(err: TransactionError) -> Error {
        match err {
            TransactionError::Storage(storage) => storage.into(),
            TransactionError::ReadTransactionStillInUse(txn) => {
                Error::ReadTransactionStillInUse(txn)
            }
        }
    }
}

impl From<StorageError> for TransactionError {
    fn from(err: StorageError) -> TransactionError {
        TransactionError::Storage(err)
    }
}

impl Display for TransactionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            TransactionError::Storage(storage) => storage.fmt(f),
            TransactionError::ReadTransactionStillInUse(_) => {
                write!(f, "Transaction still in use")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for TransactionError {}

/// Errors related to committing transactions
#[derive(Debug)]
#[non_exhaustive]
pub enum CommitError {
    /// Error from underlying storage
    Storage(StorageError),
}

impl CommitError {
    pub(crate) fn into_storage_error(self) -> StorageError {
        match self {
            CommitError::Storage(storage) => storage,
        }
    }
}

impl From<CommitError> for Error {
    fn from(err: CommitError) -> Error {
        match err {
            CommitError::Storage(storage) => storage.into(),
        }
    }
}

impl From<StorageError> for CommitError {
    fn from(err: StorageError) -> CommitError {
        CommitError::Storage(err)
    }
}

impl Display for CommitError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            CommitError::Storage(storage) => storage.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for CommitError {}

/// Superset of all other errors that can occur. Convenience enum so that users can convert all errors into a single type
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// The Database is already open. Cannot acquire lock.
    DatabaseAlreadyOpen,
    /// This savepoint is invalid or cannot be created.
    ///
    /// Savepoints become invalid when an older savepoint is restored after it was created,
    /// and savepoints cannot be created if the transaction is "dirty" (any tables have been opened)
    InvalidSavepoint,
    /// [`crate::RepairSession::abort`] was called.
    RepairAborted,
    /// A persistent savepoint was modified
    PersistentSavepointModified,
    /// A persistent savepoint exists
    PersistentSavepointExists,
    /// An Ephemeral savepoint exists
    EphemeralSavepointExists,
    /// A transaction is still in-progress
    TransactionInProgress,
    /// The Database is corrupted
    Corrupted(String),
    /// The database file is in an old file format and must be manually upgraded
    UpgradeRequired(u8),
    /// The value being inserted exceeds the maximum of 3GiB
    ValueTooLarge(usize),
    /// Table types didn't match.
    TableTypeMismatch {
        table: String,
        key: TypeName,
        value: TypeName,
    },
    /// The table is a multimap table
    TableIsMultimap(String),
    /// The table is not a multimap table
    TableIsNotMultimap(String),
    TypeDefinitionChanged {
        name: TypeName,
        alignment: usize,
        width: Option<usize>,
    },
    /// Table name does not match any table in database
    TableDoesNotExist(String),
    /// Table name already exists in the database
    TableExists(String),
    // Tables cannot be opened for writing multiple times, since they could retrieve immutable &
    // mutable references to the same dirty pages, or multiple mutable references via insert_reserve()
    TableAlreadyOpen(String, &'static panic::Location<'static>),
    /// A blob with the given sequence ID was not found in the blob store
    BlobNotFound(u64),
    /// Blob data checksum does not match the stored checksum
    BlobChecksumMismatch {
        /// Blob sequence number
        sequence: u64,
        /// Checksum stored in metadata
        expected: u128,
        /// Checksum computed from the blob data
        actual: u128,
    },
    /// A streaming blob writer is already active on this transaction
    BlobWriterActive,
    /// The requested byte range exceeds the blob's length
    BlobRangeOutOfBounds {
        /// Total blob length in bytes
        blob_length: u64,
        /// Requested range start offset
        requested_offset: u64,
        /// Requested range length
        requested_length: u64,
    },
    /// The configured memory budget has been exceeded and the operation cannot proceed
    MemoryBudgetExceeded {
        /// The configured memory budget in bytes
        budget: usize,
        /// Current memory usage in bytes
        used: usize,
    },
    Io(BackendError),
    DatabaseClosed,
    /// A previous IO error occurred. The database must be closed and re-opened
    PreviousIo,
    LockPoisoned(&'static panic::Location<'static>),
    /// The transaction is still referenced by a table or other object
    ReadTransactionStillInUse(Box<ReadTransaction>),
    /// A group commit batch was rolled back because a peer batch failed
    #[cfg(feature = "std")]
    GroupCommitPeerFailed,
    /// The database group committer is shutting down
    #[cfg(feature = "std")]
    GroupCommitShutdown,
}

#[cfg(feature = "std")]
impl From<GroupCommitError> for Error {
    fn from(err: GroupCommitError) -> Error {
        match err {
            GroupCommitError::BatchFailed(e) => e,
            GroupCommitError::PeerFailed => Error::GroupCommitPeerFailed,
            GroupCommitError::TransactionFailed(e) | GroupCommitError::CommitFailed(e) => e.into(),
            GroupCommitError::Shutdown => Error::GroupCommitShutdown,
        }
    }
}

#[cfg(feature = "std")]
impl<T> From<PoisonError<T>> for Error {
    fn from(_: PoisonError<T>) -> Error {
        Error::LockPoisoned(panic::Location::caller())
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::Io(BackendError::Io(err))
    }
}

impl From<BackendError> for Error {
    fn from(err: BackendError) -> Error {
        Error::Io(err)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::Corrupted(msg) => {
                write!(f, "DB corrupted: {msg}")
            }
            Error::UpgradeRequired(actual) => {
                write!(
                    f,
                    "Manual upgrade required. Expected file format version {FILE_FORMAT_VERSION3}, but file is version {actual}"
                )
            }
            Error::ValueTooLarge(len) => {
                write!(
                    f,
                    "The value (length={len}) being inserted exceeds the maximum of {}GiB",
                    MAX_VALUE_LENGTH / 1024 / 1024 / 1024
                )
            }
            Error::TypeDefinitionChanged {
                name,
                alignment,
                width,
            } => {
                write!(
                    f,
                    "Current definition of {} does not match stored definition (width={:?}, alignment={})",
                    name.name(),
                    width,
                    alignment,
                )
            }
            Error::TableTypeMismatch { table, key, value } => {
                write!(
                    f,
                    "{table} is of type Table<{}, {}>",
                    key.name(),
                    value.name(),
                )
            }
            Error::TableIsMultimap(table) => {
                write!(f, "{table} is a multimap table")
            }
            Error::TableIsNotMultimap(table) => {
                write!(f, "{table} is not a multimap table")
            }
            Error::TableDoesNotExist(table) => {
                write!(f, "Table '{table}' does not exist")
            }
            Error::TableExists(table) => {
                write!(f, "Table '{table}' already exists")
            }
            Error::TableAlreadyOpen(name, location) => {
                write!(f, "Table '{name}' already opened at: {location}")
            }
            Error::BlobNotFound(seq) => {
                write!(f, "Blob not found: sequence={seq}")
            }
            Error::BlobChecksumMismatch {
                sequence,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "Blob checksum mismatch: sequence={sequence}, expected={expected:#034x}, actual={actual:#034x}"
                )
            }
            Error::BlobWriterActive => {
                write!(
                    f,
                    "Cannot create blob writer or store blob while another writer is active"
                )
            }
            Error::BlobRangeOutOfBounds {
                blob_length,
                requested_offset,
                requested_length,
            } => {
                write!(
                    f,
                    "Blob range out of bounds: blob_length={blob_length}, requested offset={requested_offset}, length={requested_length}"
                )
            }
            Error::MemoryBudgetExceeded { budget, used } => {
                write!(
                    f,
                    "Memory budget exceeded: budget={budget} bytes, used={used} bytes"
                )
            }
            Error::Io(err) => {
                write!(f, "I/O error: {err}")
            }
            Error::DatabaseClosed => {
                write!(f, "Database has been closed")
            }
            Error::PreviousIo => {
                write!(
                    f,
                    "Previous I/O error occurred. Please close and re-open the database."
                )
            }
            Error::LockPoisoned(location) => {
                write!(f, "Poisoned internal lock: {location}")
            }
            Error::DatabaseAlreadyOpen => {
                write!(f, "Database already open. Cannot acquire lock.")
            }
            Error::RepairAborted => {
                write!(f, "Database repair aborted.")
            }
            Error::PersistentSavepointModified => {
                write!(
                    f,
                    "Persistent savepoint modified. Cannot reduce transaction durability"
                )
            }
            Error::PersistentSavepointExists => {
                write!(
                    f,
                    "Persistent savepoint exists. Operation cannot be performed."
                )
            }
            Error::EphemeralSavepointExists => {
                write!(
                    f,
                    "Ephemeral savepoint exists. Operation cannot be performed."
                )
            }
            Error::TransactionInProgress => {
                write!(
                    f,
                    "A transaction is still in progress. Operation cannot be performed."
                )
            }
            Error::InvalidSavepoint => {
                write!(f, "Savepoint is invalid or cannot be created.")
            }
            Error::ReadTransactionStillInUse(_) => {
                write!(f, "Transaction still in use")
            }
            #[cfg(feature = "std")]
            Error::GroupCommitPeerFailed => {
                write!(
                    f,
                    "Group commit batch rolled back: another batch in the group failed"
                )
            }
            #[cfg(feature = "std")]
            Error::GroupCommitShutdown => {
                write!(f, "Group commit failed: database is shutting down")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}