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
use crate::tree_store::{FILE_FORMAT_VERSION2, MAX_VALUE_LENGTH};
use crate::{ReadTransaction, TypeName};
use std::fmt::{Display, Formatter};
use std::sync::PoisonError;
use std::{io, panic};

/// 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),
    Io(io::Error),
    PreviousIo,
    LockPoisoned(&'static panic::Location<'static>),
}

impl<T> From<PoisonError<T>> for StorageError {
    fn from(_: PoisonError<T>) -> StorageError {
        StorageError::LockPoisoned(panic::Location::caller())
    }
}

impl From<io::Error> for StorageError {
    fn from(err: io::Error) -> StorageError {
        StorageError::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::Io(x) => Error::Io(x),
            StorageError::PreviousIo => Error::PreviousIo,
            StorageError::LockPoisoned(location) => Error::LockPoisoned(location),
        }
    }
}

impl Display for StorageError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::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::Io(err) => {
                write!(f, "I/O error: {err}")
            }
            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 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),
    // 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::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::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<'_>) -> std::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::TableAlreadyOpen(name, location) => {
                write!(f, "Table '{name}' already opened at: {location}")
            }
            TableError::Storage(storage) => storage.fmt(f),
        }
    }
}

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.
    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<io::Error> for DatabaseError {
    fn from(err: io::Error) -> DatabaseError {
        DatabaseError::Storage(StorageError::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<'_>) -> std::fmt::Result {
        match self {
            DatabaseError::UpgradeRequired(actual) => {
                write!(f, "Manual upgrade required. Expected file format version {FILE_FORMAT_VERSION2}, 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),
        }
    }
}

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<'_>) -> std::fmt::Result {
        match self {
            SavepointError::InvalidSavepoint => {
                write!(f, "Savepoint is invalid or cannot be created.")
            }
            SavepointError::Storage(storage) => storage.fmt(f),
        }
    }
}

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<'_>) -> std::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 std::error::Error for CompactionError {}

/// 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(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<'_>) -> std::fmt::Result {
        match self {
            TransactionError::Storage(storage) => storage.fmt(f),
            TransactionError::ReadTransactionStillInUse(_) => {
                write!(f, "Transaction still in use")
            }
        }
    }
}

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<'_>) -> std::fmt::Result {
        match self {
            CommitError::Storage(storage) => storage.fmt(f),
        }
    }
}

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 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),
    // 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>),
    Io(io::Error),
    /// 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(ReadTransaction),
}

impl<T> From<PoisonError<T>> for Error {
    fn from(_: PoisonError<T>) -> Error {
        Error::LockPoisoned(panic::Location::caller())
    }
}

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

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::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_VERSION2}, 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::TableAlreadyOpen(name, location) => {
                write!(f, "Table '{name}' already opened at: {location}")
            }
            Error::Io(err) => {
                write!(f, "I/O error: {err}")
            }
            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::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")
            }
        }
    }
}

impl std::error::Error for Error {}