Skip to main content

sqlitedb/
error.rs

1use std::fmt;
2use std::io;
3use std::path::PathBuf;
4
5#[derive(Debug)]
6pub enum Error {
7    Options(Vec<String>),
8    Io {
9        action: &'static str,
10        source: io::Error,
11    },
12    NotDirectory(PathBuf),
13    SharedDirectory {
14        path: PathBuf,
15        mode: u32,
16    },
17    InUse,
18    Settings(String),
19    Sqlite {
20        action: &'static str,
21        source: rusqlite::Error,
22    },
23    Migrations(String),
24    MigrationFailed {
25        action: &'static str,
26        name: String,
27        source: rusqlite::Error,
28    },
29    MigrationDrift {
30        version: i64,
31        name: String,
32    },
33    UnknownMigration {
34        applied: usize,
35        known: usize,
36    },
37    ForeignKeyViolation {
38        table: String,
39        parent: String,
40    },
41    CheckpointIncomplete {
42        readers: usize,
43    },
44    Deadline,
45    Closed,
46    Shutdown,
47    Joined(Vec<Self>),
48}
49
50impl Error {
51    pub(crate) fn sqlite(action: &'static str) -> impl FnOnce(rusqlite::Error) -> Self {
52        move |source| Self::Sqlite { action, source }
53    }
54
55    pub(crate) fn io(action: &'static str) -> impl FnOnce(io::Error) -> Self {
56        move |source| Self::Io { action, source }
57    }
58
59    pub(crate) fn join(results: impl IntoIterator<Item = Result<(), Self>>) -> Result<(), Self> {
60        let mut errors: Vec<Self> = results.into_iter().filter_map(Result::err).collect();
61        if errors.len() > 1 {
62            return Err(Self::Joined(errors));
63        }
64        errors.pop().map_or(Ok(()), Err)
65    }
66
67    fn write_joined(errors: &[Self], formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68        for (index, error) in errors.iter().enumerate() {
69            if index > 0 {
70                formatter.write_str("; ")?;
71            }
72            write!(formatter, "{error}")?;
73            let mut source = std::error::Error::source(error);
74            while let Some(cause) = source {
75                write!(formatter, ": {cause}")?;
76                source = std::error::Error::source(cause);
77            }
78        }
79        Ok(())
80    }
81}
82
83impl From<rusqlite::Error> for Error {
84    fn from(source: rusqlite::Error) -> Self {
85        Self::Sqlite {
86            action: "query",
87            source,
88        }
89    }
90}
91
92impl fmt::Display for Error {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match self {
95            Self::Options(problems) => {
96                write!(formatter, "sqlitedb: options: {}", problems.join("; "))
97            }
98            Self::Io { action, .. } | Self::Sqlite { action, .. } => {
99                write!(formatter, "sqlitedb: {action}")
100            }
101            Self::NotDirectory(path) => write!(
102                formatter,
103                "sqlitedb: database directory is not a directory: {}",
104                path.display()
105            ),
106            Self::SharedDirectory { path, mode } => write!(
107                formatter,
108                "sqlitedb: database directory is accessible to group or others: {} has mode {mode:o}",
109                path.display()
110            ),
111            Self::InUse => formatter.write_str("sqlitedb: database is open in another process"),
112            Self::Settings(found) => write!(formatter, "sqlitedb: settings not applied: {found}"),
113            Self::Migrations(problem) => write!(formatter, "sqlitedb: {problem}"),
114            Self::MigrationFailed { action, name, .. } => {
115                write!(formatter, "sqlitedb: {action} {name}")
116            }
117            Self::MigrationDrift { version, name } => write!(
118                formatter,
119                "sqlitedb: applied migration differs from the embedded migration: version {version} {name}"
120            ),
121            Self::UnknownMigration { applied, known } => write!(
122                formatter,
123                "sqlitedb: database has migrations this binary does not know: {applied} applied, {known} known"
124            ),
125            Self::ForeignKeyViolation { table, parent } => write!(
126                formatter,
127                "sqlitedb: migration left rows that violate foreign keys: {table} references {parent}"
128            ),
129            Self::CheckpointIncomplete { readers } => write!(
130                formatter,
131                "sqlitedb: wal checkpoint did not complete: {readers} readers of this process are still open"
132            ),
133            Self::Deadline => formatter.write_str("sqlitedb: write deadline passed"),
134            Self::Closed => formatter.write_str("sqlitedb: database is closed"),
135            Self::Shutdown => formatter.write_str("sqlitedb: runtime shut down first"),
136            Self::Joined(errors) => Self::write_joined(errors, formatter),
137        }
138    }
139}
140
141impl std::error::Error for Error {
142    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
143        match self {
144            Self::Io { source, .. } => Some(source),
145            Self::Sqlite { source, .. } | Self::MigrationFailed { source, .. } => Some(source),
146            _ => None,
147        }
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use std::error::Error as _;
154
155    use super::Error;
156
157    #[test]
158    fn joined_errors_show_every_chain_and_end_the_source_chain() {
159        let refused = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
160        let joined = Error::Joined(vec![
161            Error::Io {
162                action: "open",
163                source: refused,
164            },
165            Error::Shutdown,
166        ]);
167        assert_eq!(
168            joined.to_string(),
169            "sqlitedb: open: permission denied; sqlitedb: runtime shut down first"
170        );
171        assert!(joined.source().is_none());
172    }
173}