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;
#[derive(Debug)]
#[non_exhaustive]
pub enum BackendError {
#[cfg(not(redb_no_std))]
Io(std::io::Error),
Other(Box<dyn core::error::Error + Send + Sync>),
Unsupported,
}
impl BackendError {
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())
}
}
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
}
#[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 {
fn from(err: std::io::Error) -> Self {
Self::from_lock_io(err)
}
}
#[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,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum StorageError {
Corrupted(String),
ValueTooLarge(usize),
#[cfg(not(redb_no_std))]
Io(std::io::Error),
Backend(Box<dyn core::error::Error + Send + Sync>),
Unsupported,
PreviousIo,
DatabaseClosed,
LockPoisoned(&'static panic::Location<'static>),
}
impl StorageError {
#[cold]
#[track_caller]
pub(crate) fn unreachable(message: &str) -> Self {
#[cfg(not(fuzzing))]
debug_assert!(false, "{message}");
Self::Corrupted(message.to_string())
}
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())
}
}
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())
}
}
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum TableError {
#[cfg(not(feature = "experimental-api-5"))]
TableTypeMismatch {
table: String,
key: TypeName,
value: TypeName,
},
#[cfg(feature = "experimental-api-5")]
TableTypeMismatch(Box<TableTypeMismatch>),
TableIsMultimap(String),
TableIsNotMultimap(String),
#[cfg(not(feature = "experimental-api-5"))]
TypeDefinitionChanged {
name: TypeName,
alignment: usize,
width: Option<usize>,
},
#[cfg(feature = "experimental-api-5")]
TypeDefinitionChanged(Box<TypeDefinitionInfo>),
TableDoesNotExist(String),
TableExists(String),
TableAlreadyOpen(String, &'static panic::Location<'static>),
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")]
{
let _ = alignment;
Self::TypeDefinitionChanged(Box::new(TypeDefinitionInfo { name, width }))
}
#[cfg(not(feature = "experimental-api-5"))]
{
Self::TypeDefinitionChanged {
name,
alignment,
width,
}
}
}
}
#[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 {
pub fn table(&self) -> &str {
&self.table
}
pub fn stored_key(&self) -> &TypeName {
&self.stored_key
}
pub fn stored_value(&self) -> &TypeName {
&self.stored_value
}
pub fn requested_key(&self) -> &TypeName {
&self.requested_key
}
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)),
)
}
}
#[cfg(feature = "experimental-api-5")]
#[derive(Debug)]
pub struct TypeDefinitionInfo {
name: TypeName,
width: Option<usize>,
}
#[cfg(feature = "experimental-api-5")]
impl TypeDefinitionInfo {
pub fn name(&self) -> &TypeName {
&self.name
}
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(")")
}
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum DatabaseError {
DatabaseAlreadyOpen,
LockProtocolMismatch,
RepairAborted,
UpgradeRequired(u8),
TransactionInProgress,
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum SavepointError {
InvalidSavepoint,
ImmediateDurabilityRequired,
EphemeralSavepointUnsupported,
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum CompactionError {
PersistentSavepointExists,
EphemeralSavepointExists,
TransactionInProgress,
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum SetDurabilityError {
PersistentSavepointModified,
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum TransactionError {
Storage(StorageError),
ReadTransactionStillInUse(Box<ReadTransaction>),
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum CommitError {
Storage(StorageError),
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum CursorError {
UnorderedKey,
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 {}
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
DatabaseAlreadyOpen,
LockProtocolMismatch,
InvalidSavepoint,
ImmediateDurabilityRequired,
RepairAborted,
PersistentSavepointModified,
NonDurableCommitUnsupported,
EphemeralSavepointUnsupported,
PersistentSavepointExists,
EphemeralSavepointExists,
TransactionInProgress,
TransactionPoisoned,
Corrupted(String),
UpgradeRequired(u8),
ValueTooLarge(usize),
UnorderedKey,
#[cfg(not(feature = "experimental-api-5"))]
TableTypeMismatch {
table: String,
key: TypeName,
value: TypeName,
},
#[cfg(feature = "experimental-api-5")]
TableTypeMismatch(Box<TableTypeMismatch>),
TableIsMultimap(String),
TableIsNotMultimap(String),
#[cfg(not(feature = "experimental-api-5"))]
TypeDefinitionChanged {
name: TypeName,
alignment: usize,
width: Option<usize>,
},
#[cfg(feature = "experimental-api-5")]
TypeDefinitionChanged(Box<TypeDefinitionInfo>),
TableDoesNotExist(String),
TableExists(String),
TableAlreadyOpen(String, &'static panic::Location<'static>),
#[cfg(not(redb_no_std))]
Io(std::io::Error),
Backend(Box<dyn core::error::Error + Send + Sync>),
Unsupported,
DatabaseClosed,
PreviousIo,
LockPoisoned(&'static panic::Location<'static>),
ReadTransactionStillInUse(Box<ReadTransaction>),
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>());
}
#[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));
}
#[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);
}
}