redb 4.6.0

Rust Embedded 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
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
use crate::sync::PoisonError;
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, ToString};
use core::fmt::{Display, Formatter};
use core::panic;

/// Errors reported by a [`crate::StorageBackend`].
#[derive(Debug)]
#[non_exhaustive]
pub enum BackendError {
    /// The underlying storage operation failed. Not available without std.
    #[cfg(not(redb_no_std))]
    Io(std::io::Error),
    /// The backend failed with an error that is not an I/O error.
    Other(Box<dyn core::error::Error + Send + Sync>),
    /// The backend does not support the requested operation.
    Unsupported,
}

impl BackendError {
    // With std, an io::Error of the matching kind. Without it the kind is dropped
    pub(crate) fn invalid_input(message: &'static str) -> Self {
        #[cfg(not(redb_no_std))]
        {
            Self::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                message,
            ))
        }
        #[cfg(redb_no_std)]
        {
            Self::Other(message.into())
        }
    }

    // An I/O error wrapped in Other is unwrapped, so that it is matched as one
    fn normalize(self) -> Self {
        #[cfg(not(redb_no_std))]
        if let Self::Other(err) = self {
            return match err.downcast::<std::io::Error>() {
                Ok(err) => Self::Io(*err),
                Err(err) => Self::Other(err),
            };
        }
        self
    }

    // A lock method's error, with an unsupported operation reported as Self::Unsupported, as the
    // StorageBackend docs specify
    #[cfg(not(redb_no_std))]
    pub(crate) fn from_lock_io(err: std::io::Error) -> Self {
        if err.kind() == std::io::ErrorKind::Unsupported {
            return Self::Unsupported;
        }
        Self::Io(err)
    }
}

#[cfg(not(feature = "experimental-api-5"))]
impl From<std::io::Error> for BackendError {
    /// Preserves unsupported-operation errors as [`Self::Unsupported`].
    fn from(err: std::io::Error) -> Self {
        Self::from_lock_io(err)
    }
}

// Lossless, since the I/O methods report an io::Error through it too
#[cfg(all(feature = "experimental-api-5", not(redb_no_std)))]
impl From<std::io::Error> for BackendError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

#[cfg(not(redb_no_std))]
impl From<BackendError> for std::io::Error {
    fn from(err: BackendError) -> Self {
        match err.normalize() {
            BackendError::Io(err) => err,
            BackendError::Other(err) => std::io::Error::other(err),
            BackendError::Unsupported => std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "the storage backend does not support this operation",
            ),
        }
    }
}

impl From<BackendError> for Error {
    fn from(err: BackendError) -> Self {
        StorageError::from(err).into()
    }
}

impl Display for BackendError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(not(redb_no_std))]
            Self::Io(err) => write!(f, "I/O error: {err}"),
            Self::Other(err) => write!(f, "Storage backend error: {err}"),
            Self::Unsupported => f.write_str("The storage backend does not support this operation"),
        }
    }
}

impl core::error::Error for BackendError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            #[cfg(not(redb_no_std))]
            Self::Io(err) => Some(err),
            Self::Other(err) => Some(&**err),
            Self::Unsupported => None,
        }
    }
}

/// 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),
    /// An I/O error from the storage backend. Not available without std.
    #[cfg(not(redb_no_std))]
    Io(std::io::Error),
    /// The storage backend failed with an error that is not an I/O error.
    Backend(Box<dyn core::error::Error + Send + Sync>),
    /// The backend does not support a required storage operation.
    Unsupported,
    PreviousIo,
    DatabaseClosed,
    LockPoisoned(&'static panic::Location<'static>),
}

impl StorageError {
    // For checks that no file redb wrote can fail. Debug builds panic, so a test gets a backtrace to
    // the site; release builds return Corrupted. Never use it for an error that is meant to be
    // returned and handled. Fuzz builds feed redb corrupt files on purpose, so they return the error
    // as release builds do.
    #[cold]
    #[track_caller]
    pub(crate) fn unreachable(message: &str) -> Self {
        #[cfg(not(fuzzing))]
        debug_assert!(false, "{message}");
        Self::Corrupted(message.to_string())
    }

    // The storage does not hold a redb database. With std, an I/O error of kind InvalidData, as
    // open() and create() have reported it since 2.4. Without std, Corrupted, so that it is not
    // mistaken for a failure of the backend
    pub(crate) fn not_a_database(message: &'static str) -> Self {
        #[cfg(not(redb_no_std))]
        {
            Self::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                message,
            ))
        }
        #[cfg(redb_no_std)]
        {
            Self::Corrupted(message.to_string())
        }
    }

    // A lock method's error. An I/O error of kind Unsupported is Unsupported however the backend
    // wrapped it, since the callers fall back to a whole-storage lock only on Unsupported
    pub(crate) fn from_lock_error(err: BackendError) -> Self {
        match Self::from(err) {
            #[cfg(not(redb_no_std))]
            Self::Io(err) if err.kind() == std::io::ErrorKind::Unsupported => Self::Unsupported,
            err => err,
        }
    }
}

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

// Reports a poisoned lock as LockPoisoned, at the location where the lock was taken
pub(crate) trait LockResultExt<G> {
    fn or_poisoned(self) -> Result<G, StorageError>;
}

impl<G> LockResultExt<G> for Result<G, PoisonError<G>> {
    #[track_caller]
    fn or_poisoned(self) -> Result<G, StorageError> {
        match self {
            Ok(guard) => Ok(guard),
            Err(_) => Err(StorageError::LockPoisoned(panic::Location::caller())),
        }
    }
}

#[cfg(not(redb_no_std))]
impl From<std::io::Error> for StorageError {
    fn from(err: std::io::Error) -> StorageError {
        StorageError::Io(err)
    }
}

impl From<BackendError> for StorageError {
    fn from(err: BackendError) -> Self {
        match err.normalize() {
            #[cfg(not(redb_no_std))]
            BackendError::Io(err) => Self::Io(err),
            BackendError::Other(err) => Self::Backend(err),
            BackendError::Unsupported => Self::Unsupported,
        }
    }
}

impl From<StorageError> for Error {
    fn from(err: StorageError) -> Error {
        match err {
            StorageError::Corrupted(msg) => Error::Corrupted(msg),
            StorageError::ValueTooLarge(x) => Error::ValueTooLarge(x),
            #[cfg(not(redb_no_std))]
            StorageError::Io(x) => Error::Io(x),
            StorageError::Backend(x) => Error::Backend(x),
            StorageError::Unsupported => Error::Unsupported,
            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
                )
            }
            #[cfg(not(redb_no_std))]
            StorageError::Io(err) => {
                write!(f, "I/O error: {err}")
            }
            StorageError::Backend(err) => {
                write!(f, "Storage backend error: {err}")
            }
            StorageError::Unsupported => BackendError::Unsupported.fmt(f),
            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}")
            }
        }
    }
}

impl core::error::Error for StorageError {}

/// Errors related to opening tables
#[derive(Debug)]
#[non_exhaustive]
pub enum TableError {
    /// Table types didn't match.
    #[cfg(not(feature = "experimental-api-5"))]
    TableTypeMismatch {
        table: String,
        key: TypeName,
        value: TypeName,
    },
    /// The table's types are not the ones it was opened with
    #[cfg(feature = "experimental-api-5")]
    TableTypeMismatch(Box<TableTypeMismatch>),
    /// The table is a multimap table
    TableIsMultimap(String),
    /// The table is not a multimap table
    TableIsNotMultimap(String),
    #[cfg(not(feature = "experimental-api-5"))]
    TypeDefinitionChanged {
        name: TypeName,
        alignment: usize,
        width: Option<usize>,
    },
    /// A type's fixed width or alignment differs from the one it is stored with
    #[cfg(feature = "experimental-api-5")]
    TypeDefinitionChanged(Box<TypeDefinitionInfo>),
    /// 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 {
            #[cfg(not(feature = "experimental-api-5"))]
            TableError::TypeDefinitionChanged {
                name,
                alignment,
                width,
            } => Error::TypeDefinitionChanged {
                name,
                alignment,
                width,
            },
            #[cfg(feature = "experimental-api-5")]
            TableError::TypeDefinitionChanged(changed) => Error::TypeDefinitionChanged(changed),
            #[cfg(not(feature = "experimental-api-5"))]
            TableError::TableTypeMismatch { table, key, value } => {
                Error::TableTypeMismatch { table, key, value }
            }
            #[cfg(feature = "experimental-api-5")]
            TableError::TableTypeMismatch(mismatch) => Error::TableTypeMismatch(mismatch),
            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 TableError {
    pub(crate) fn type_mismatch(
        table: &str,
        stored_key: TypeName,
        stored_value: TypeName,
        requested_key: TypeName,
        requested_value: TypeName,
    ) -> Self {
        #[cfg(feature = "experimental-api-5")]
        {
            Self::TableTypeMismatch(Box::new(TableTypeMismatch {
                table: table.to_string(),
                stored_key,
                stored_value,
                requested_key,
                requested_value,
            }))
        }
        #[cfg(not(feature = "experimental-api-5"))]
        {
            let _ = (requested_key, requested_value);
            Self::TableTypeMismatch {
                table: table.to_string(),
                key: stored_key,
                value: stored_value,
            }
        }
    }

    pub(crate) fn type_definition_changed(
        name: TypeName,
        alignment: usize,
        width: Option<usize>,
    ) -> Self {
        #[cfg(feature = "experimental-api-5")]
        {
            // Always 1, since redb supports no other alignment, so it is not reported
            let _ = alignment;
            Self::TypeDefinitionChanged(Box::new(TypeDefinitionInfo { name, width }))
        }
        #[cfg(not(feature = "experimental-api-5"))]
        {
            Self::TypeDefinitionChanged {
                name,
                alignment,
                width,
            }
        }
    }
}

/// A table opened with key or value types other than the ones it is stored with. See
/// [`TableError::TableTypeMismatch`].
#[cfg(feature = "experimental-api-5")]
#[derive(Debug)]
pub struct TableTypeMismatch {
    table: String,
    stored_key: TypeName,
    stored_value: TypeName,
    requested_key: TypeName,
    requested_value: TypeName,
}

#[cfg(feature = "experimental-api-5")]
impl TableTypeMismatch {
    /// The name of the table
    pub fn table(&self) -> &str {
        &self.table
    }

    /// The key type the table is stored with
    pub fn stored_key(&self) -> &TypeName {
        &self.stored_key
    }

    /// The value type the table is stored with
    pub fn stored_value(&self) -> &TypeName {
        &self.stored_value
    }

    /// The key type the table was opened with
    pub fn requested_key(&self) -> &TypeName {
        &self.requested_key
    }

    /// The value type the table was opened with
    pub fn requested_value(&self) -> &TypeName {
        &self.requested_value
    }
}

#[cfg(feature = "experimental-api-5")]
impl Display for TableTypeMismatch {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        fmt_type_mismatch(
            f,
            &self.table,
            &self.stored_key,
            &self.stored_value,
            Some((&self.requested_key, &self.requested_value)),
        )
    }
}

/// A key or value type whose fixed width differs from the one it is stored with. See
/// [`TableError::TypeDefinitionChanged`].
#[cfg(feature = "experimental-api-5")]
#[derive(Debug)]
pub struct TypeDefinitionInfo {
    name: TypeName,
    width: Option<usize>,
}

#[cfg(feature = "experimental-api-5")]
impl TypeDefinitionInfo {
    /// The type whose definition changed
    pub fn name(&self) -> &TypeName {
        &self.name
    }

    /// The fixed width the type is stored with, or `None` if it is stored as variable width
    pub fn width(&self) -> Option<usize> {
        self.width
    }
}

#[cfg(feature = "experimental-api-5")]
impl Display for TypeDefinitionInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        fmt_type_definition_changed(f, &self.name, self.width, None)
    }
}

fn fmt_type_definition_changed(
    f: &mut Formatter<'_>,
    name: &TypeName,
    width: Option<usize>,
    alignment: Option<usize>,
) -> core::fmt::Result {
    write!(
        f,
        "Current definition of {} does not match stored definition (width={width:?}",
        name.name(),
    )?;
    if let Some(alignment) = alignment {
        write!(f, ", alignment={alignment}")?;
    }
    f.write_str(")")
}

// Names neither Table nor MultimapTable, since the mismatch may be either
fn fmt_type_mismatch(
    f: &mut Formatter<'_>,
    table: &str,
    key: &TypeName,
    value: &TypeName,
    requested: Option<(&TypeName, &TypeName)>,
) -> core::fmt::Result {
    write!(
        f,
        "{table} has key type {} and value type {}",
        key.name(),
        value.name()
    )?;
    if let Some((requested_key, requested_value)) = requested {
        write!(
            f,
            ", but was opened with key type {} and value type {}",
            requested_key.name(),
            requested_value.name()
        )?;
    }
    Ok(())
}

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 {
            #[cfg(not(feature = "experimental-api-5"))]
            TableError::TypeDefinitionChanged {
                name,
                alignment,
                width,
            } => fmt_type_definition_changed(f, name, *width, Some(*alignment)),
            #[cfg(feature = "experimental-api-5")]
            TableError::TypeDefinitionChanged(changed) => changed.fmt(f),
            #[cfg(not(feature = "experimental-api-5"))]
            TableError::TableTypeMismatch { table, key, value } => {
                fmt_type_mismatch(f, table, key, value, None)
            }
            #[cfg(feature = "experimental-api-5")]
            TableError::TableTypeMismatch(mismatch) => mismatch.fmt(f),
            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),
        }
    }
}

impl core::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,
    /// Another process has the database open with a version of redb that implements a different
    /// generation of the multi-process locking protocol
    LockProtocolMismatch,
    /// [`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),
    /// A transaction is still in-progress
    TransactionInProgress,
    /// Error from underlying storage
    Storage(StorageError),
}

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

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

impl From<BackendError> for DatabaseError {
    fn from(err: BackendError) -> Self {
        Self::Storage(err.into())
    }
}

impl DatabaseError {
    pub(crate) fn into_storage_error_or_corrupted(self) -> StorageError {
        match self {
            DatabaseError::Storage(storage) => storage,
            other => StorageError::Corrupted(other.to_string()),
        }
    }
}

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::LockProtocolMismatch => {
                write!(
                    f,
                    "Database already open by a process whose version of redb implements a different multi-process locking protocol."
                )
            }
            DatabaseError::TransactionInProgress => {
                write!(
                    f,
                    "A transaction is still in progress. Operation cannot be performed."
                )
            }
            DatabaseError::Storage(storage) => storage.fmt(f),
        }
    }
}

impl core::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,
    /// The operation requires the transaction's durability to be [`crate::Durability::Immediate`].
    ///
    /// Returned by operations that must be able to modify persistent savepoints, such as
    /// creating or deleting a persistent savepoint, or restoring an older savepoint while
    /// newer persistent savepoints exist that would need to be deleted.
    ImmediateDurabilityRequired,
    /// An ephemeral savepoint would be known to this process alone, and a persistent savepoint
    /// another process creates could take its id
    EphemeralSavepointUnsupported,
    /// Error from underlying storage
    Storage(StorageError),
}

impl From<SavepointError> for Error {
    fn from(err: SavepointError) -> Error {
        match err {
            SavepointError::InvalidSavepoint => Error::InvalidSavepoint,
            SavepointError::ImmediateDurabilityRequired => Error::ImmediateDurabilityRequired,
            SavepointError::EphemeralSavepointUnsupported => Error::EphemeralSavepointUnsupported,
            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::ImmediateDurabilityRequired => {
                write!(
                    f,
                    "Operation requires Durability::Immediate for the current transaction."
                )
            }
            SavepointError::EphemeralSavepointUnsupported => {
                write!(
                    f,
                    "Ephemeral savepoints are not supported when the database is shared with other writer processes"
                )
            }
            SavepointError::Storage(storage) => storage.fmt(f),
        }
    }
}

impl core::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),
        }
    }
}

impl core::error::Error for CompactionError {}

/// Errors related to setting a transaction's durability
#[derive(Debug)]
#[non_exhaustive]
pub enum SetDurabilityError {
    /// A persistent savepoint was modified
    PersistentSavepointModified,
    /// A non-durable commit would be invisible to the other processes sharing the database
    NonDurableCommitUnsupported,
}

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

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"
                )
            }
            SetDurabilityError::NonDurableCommitUnsupported => {
                write!(
                    f,
                    "Non-durable commits are not supported when the database is shared with other processes"
                )
            }
        }
    }
}

impl core::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>),
    /// Another write transaction is in progress, which [`crate::Database::try_begin_write`]
    /// does not wait for
    WouldBlock,
}

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)
            }
            TransactionError::WouldBlock => Error::WouldBlock,
        }
    }
}

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")
            }
            TransactionError::WouldBlock => {
                write!(f, "Another write transaction is in progress")
            }
        }
    }
}

impl core::error::Error for TransactionError {}

/// Errors related to committing transactions
#[derive(Debug)]
#[non_exhaustive]
pub enum CommitError {
    /// Error from underlying storage
    Storage(StorageError),
    /// The transaction was poisoned and can no longer be committed: an operation panicked, or
    /// failed part way through modifying the transaction, or a table was leaked
    TransactionPoisoned,
}

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

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

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),
            CommitError::TransactionPoisoned => {
                write!(
                    f,
                    "Transaction was poisoned by a panic, a failed operation, or a leaked table"
                )
            }
        }
    }
}

impl core::error::Error for CommitError {}

/// Errors related to cursors
#[derive(Debug)]
#[non_exhaustive]
pub enum CursorError {
    /// The key does not sort strictly between the entries adjacent to the cursor
    UnorderedKey,
    /// Error from underlying storage
    Storage(StorageError),
}

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

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

impl Display for CursorError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            CursorError::UnorderedKey => {
                write!(
                    f,
                    "The key does not sort strictly between the entries adjacent to the cursor"
                )
            }
            CursorError::Storage(storage) => storage.fmt(f),
        }
    }
}

impl core::error::Error for CursorError {}

/// 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,
    /// Another process has the database open with a version of redb that implements a different
    /// generation of the multi-process locking protocol
    LockProtocolMismatch,
    /// 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,
    /// A savepoint operation requires [`crate::Durability::Immediate`] for the transaction.
    ImmediateDurabilityRequired,
    /// [`crate::RepairSession::abort`] was called.
    RepairAborted,
    /// A persistent savepoint was modified
    PersistentSavepointModified,
    /// A non-durable commit would be invisible to the other processes sharing the database
    NonDurableCommitUnsupported,
    /// An ephemeral savepoint would be known to this process alone, and a persistent savepoint
    /// another process creates could take its id
    EphemeralSavepointUnsupported,
    /// A persistent savepoint exists
    PersistentSavepointExists,
    /// An Ephemeral savepoint exists
    EphemeralSavepointExists,
    /// A transaction is still in-progress
    TransactionInProgress,
    /// The transaction was poisoned and can no longer be committed: an operation panicked, or
    /// failed part way through modifying the transaction, or a table was leaked
    TransactionPoisoned,
    /// 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),
    /// The key does not sort strictly between the entries adjacent to the cursor
    UnorderedKey,
    /// Table types didn't match.
    #[cfg(not(feature = "experimental-api-5"))]
    TableTypeMismatch {
        table: String,
        key: TypeName,
        value: TypeName,
    },
    /// The table's types are not the ones it was opened with
    #[cfg(feature = "experimental-api-5")]
    TableTypeMismatch(Box<TableTypeMismatch>),
    /// The table is a multimap table
    TableIsMultimap(String),
    /// The table is not a multimap table
    TableIsNotMultimap(String),
    #[cfg(not(feature = "experimental-api-5"))]
    TypeDefinitionChanged {
        name: TypeName,
        alignment: usize,
        width: Option<usize>,
    },
    /// A type's fixed width or alignment differs from the one it is stored with
    #[cfg(feature = "experimental-api-5")]
    TypeDefinitionChanged(Box<TypeDefinitionInfo>),
    /// 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>),
    /// An I/O error from the storage backend. Not available without std.
    #[cfg(not(redb_no_std))]
    Io(std::io::Error),
    /// The storage backend failed with an error that is not an I/O error.
    Backend(Box<dyn core::error::Error + Send + Sync>),
    /// The backend does not support a required storage operation.
    Unsupported,
    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>),
    /// Another write transaction is in progress, which [`crate::Database::try_begin_write`]
    /// does not wait for
    WouldBlock,
}

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

#[cfg(not(redb_no_std))]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::Io(err)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::Unsupported => BackendError::Unsupported.fmt(f),
            Error::Corrupted(msg) => {
                write!(f, "DB corrupted: {msg}")
            }
            Error::NonDurableCommitUnsupported => {
                write!(
                    f,
                    "Non-durable commits are not supported when the database is shared with other processes"
                )
            }
            Error::EphemeralSavepointUnsupported => {
                write!(
                    f,
                    "Ephemeral savepoints are not supported when the database is shared with other writer processes"
                )
            }
            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::UnorderedKey => {
                write!(
                    f,
                    "The key does not sort strictly between the entries adjacent to the cursor"
                )
            }
            #[cfg(not(feature = "experimental-api-5"))]
            Error::TypeDefinitionChanged {
                name,
                alignment,
                width,
            } => fmt_type_definition_changed(f, name, *width, Some(*alignment)),
            #[cfg(feature = "experimental-api-5")]
            Error::TypeDefinitionChanged(changed) => changed.fmt(f),
            #[cfg(not(feature = "experimental-api-5"))]
            Error::TableTypeMismatch { table, key, value } => {
                fmt_type_mismatch(f, table, key, value, None)
            }
            #[cfg(feature = "experimental-api-5")]
            Error::TableTypeMismatch(mismatch) => mismatch.fmt(f),
            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}")
            }
            #[cfg(not(redb_no_std))]
            Error::Io(err) => {
                write!(f, "I/O error: {err}")
            }
            Error::Backend(err) => {
                write!(f, "Storage backend 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::LockProtocolMismatch => {
                write!(
                    f,
                    "Database already open by a process whose version of redb implements a different multi-process locking protocol."
                )
            }
            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::TransactionPoisoned => {
                write!(
                    f,
                    "Transaction was poisoned by a panic, a failed operation, or a leaked table"
                )
            }
            Error::InvalidSavepoint => {
                write!(f, "Savepoint is invalid or cannot be created.")
            }
            Error::ImmediateDurabilityRequired => {
                write!(
                    f,
                    "Operation requires Durability::Immediate for the current transaction."
                )
            }
            Error::ReadTransactionStillInUse(_) => {
                write!(f, "Transaction still in use")
            }
            Error::WouldBlock => {
                write!(f, "Another write transaction is in progress")
            }
        }
    }
}

impl core::error::Error for Error {}

#[cfg(test)]
mod test {
    use super::{BackendError, Error, StorageError};
    use alloc::boxed::Box;
    use alloc::string::ToString;
    use core::fmt::{Display, Formatter};

    #[derive(Debug)]
    struct FlashError;

    impl Display for FlashError {
        fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
            f.write_str("flash write failed")
        }
    }

    impl core::error::Error for FlashError {}

    #[test]
    fn other_is_reported_as_a_backend_error() {
        let err = StorageError::from(BackendError::Other(Box::new(FlashError)));
        assert_eq!(err.to_string(), "Storage backend error: flash write failed");
        let Error::Backend(inner) = Error::from(err) else {
            panic!("not a backend error");
        };
        assert!(inner.is::<FlashError>());
    }

    // A poisoned lock is reported at the line that took it, not inside this module
    #[cfg(all(not(redb_no_std), panic = "unwind"))]
    #[test]
    fn lock_poisoned_reports_the_lock_site() {
        use super::LockResultExt;
        use std::sync::Mutex;

        let lock = Mutex::new(());
        let _ = std::panic::catch_unwind(|| {
            let _guard = lock.lock().unwrap();
            panic!("poison the lock");
        });
        let line = line!() + 1;
        let err = lock.lock().or_poisoned().unwrap_err();
        let StorageError::LockPoisoned(location) = err else {
            panic!("not LockPoisoned: {err:?}");
        };
        assert_eq!((location.file(), location.line()), (file!(), line));
    }

    // However the backend wrapped it, an io::Error is reported as one
    #[cfg(not(redb_no_std))]
    #[test]
    fn other_holding_an_io_error_is_an_io_error() {
        use std::io::ErrorKind;

        let other = || BackendError::Other(Box::new(std::io::Error::from(ErrorKind::NotFound)));
        assert!(matches!(
            StorageError::from(other()),
            StorageError::Io(err) if err.kind() == ErrorKind::NotFound
        ));
        assert_eq!(std::io::Error::from(other()).kind(), ErrorKind::NotFound);
    }
}