iris-shared-sqlitedb 0.1.1

Hardened SQLite WAL connection, migration, and transaction helpers for iris-stack
Documentation
use std::fmt;
use std::io;
use std::path::PathBuf;

#[derive(Debug)]
pub enum Error {
    Options(Vec<String>),
    Io {
        action: &'static str,
        source: io::Error,
    },
    NotDirectory(PathBuf),
    SharedDirectory {
        path: PathBuf,
        mode: u32,
    },
    InUse,
    Settings(String),
    Sqlite {
        action: &'static str,
        source: rusqlite::Error,
    },
    Migrations(String),
    MigrationFailed {
        action: &'static str,
        name: String,
        source: rusqlite::Error,
    },
    MigrationDrift {
        version: i64,
        name: String,
    },
    UnknownMigration {
        applied: usize,
        known: usize,
    },
    ForeignKeyViolation {
        table: String,
        parent: String,
    },
    CheckpointIncomplete {
        readers: usize,
    },
    Deadline,
    Closed,
    Shutdown,
    Joined(Vec<Self>),
}

impl Error {
    pub(crate) fn sqlite(action: &'static str) -> impl FnOnce(rusqlite::Error) -> Self {
        move |source| Self::Sqlite { action, source }
    }

    pub(crate) fn io(action: &'static str) -> impl FnOnce(io::Error) -> Self {
        move |source| Self::Io { action, source }
    }

    pub(crate) fn join(results: impl IntoIterator<Item = Result<(), Self>>) -> Result<(), Self> {
        let mut errors: Vec<Self> = results.into_iter().filter_map(Result::err).collect();
        if errors.len() > 1 {
            return Err(Self::Joined(errors));
        }
        errors.pop().map_or(Ok(()), Err)
    }

    fn write_joined(errors: &[Self], formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, error) in errors.iter().enumerate() {
            if index > 0 {
                formatter.write_str("; ")?;
            }
            write!(formatter, "{error}")?;
            let mut source = std::error::Error::source(error);
            while let Some(cause) = source {
                write!(formatter, ": {cause}")?;
                source = std::error::Error::source(cause);
            }
        }
        Ok(())
    }
}

impl From<rusqlite::Error> for Error {
    fn from(source: rusqlite::Error) -> Self {
        Self::Sqlite {
            action: "query",
            source,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Options(problems) => {
                write!(formatter, "sqlitedb: options: {}", problems.join("; "))
            }
            Self::Io { action, .. } | Self::Sqlite { action, .. } => {
                write!(formatter, "sqlitedb: {action}")
            }
            Self::NotDirectory(path) => write!(
                formatter,
                "sqlitedb: database directory is not a directory: {}",
                path.display()
            ),
            Self::SharedDirectory { path, mode } => write!(
                formatter,
                "sqlitedb: database directory is accessible to group or others: {} has mode {mode:o}",
                path.display()
            ),
            Self::InUse => formatter.write_str("sqlitedb: database is open in another process"),
            Self::Settings(found) => write!(formatter, "sqlitedb: settings not applied: {found}"),
            Self::Migrations(problem) => write!(formatter, "sqlitedb: {problem}"),
            Self::MigrationFailed { action, name, .. } => {
                write!(formatter, "sqlitedb: {action} {name}")
            }
            Self::MigrationDrift { version, name } => write!(
                formatter,
                "sqlitedb: applied migration differs from the embedded migration: version {version} {name}"
            ),
            Self::UnknownMigration { applied, known } => write!(
                formatter,
                "sqlitedb: database has migrations this binary does not know: {applied} applied, {known} known"
            ),
            Self::ForeignKeyViolation { table, parent } => write!(
                formatter,
                "sqlitedb: migration left rows that violate foreign keys: {table} references {parent}"
            ),
            Self::CheckpointIncomplete { readers } => write!(
                formatter,
                "sqlitedb: wal checkpoint did not complete: {readers} readers of this process are still open"
            ),
            Self::Deadline => formatter.write_str("sqlitedb: write deadline passed"),
            Self::Closed => formatter.write_str("sqlitedb: database is closed"),
            Self::Shutdown => formatter.write_str("sqlitedb: runtime shut down first"),
            Self::Joined(errors) => Self::write_joined(errors, formatter),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Sqlite { source, .. } | Self::MigrationFailed { source, .. } => Some(source),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error as _;

    use super::Error;

    #[test]
    fn joined_errors_show_every_chain_and_end_the_source_chain() {
        let refused = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
        let joined = Error::Joined(vec![
            Error::Io {
                action: "open",
                source: refused,
            },
            Error::Shutdown,
        ]);
        assert_eq!(
            joined.to_string(),
            "sqlitedb: open: permission denied; sqlitedb: runtime shut down first"
        );
        assert!(joined.source().is_none());
    }
}