Skip to main content

sqlive/
error.rs

1//! The error sqlive's calls return: SQLite's failures, the handle's, and its
2//! host's. `F` is the host's failure type, which a handle the host
3//! failed carries as it is, and `R` is the type the host's policy refuses
4//! with, which a refused statement carries as it is.
5
6use panic_as_error::Bug;
7use std::path::PathBuf;
8
9/// A failure of sqlive's own that ends its handle: every later call
10/// and live query fails with the host's failure built from it.
11#[derive(Debug)]
12pub enum EngineFailure<F, R> {
13    /// Rolling back a failed transaction failed, so a connection may still
14    /// be inside it.
15    Rollback,
16    /// One of sqlive's WAL checkpoints failed with this cause, other than
17    /// on a busy or locked database, so checkpointing stopped.
18    Checkpoint(Error<F, R>),
19    /// Checking or gathering the query planner's statistics failed with this
20    /// cause, other than on a busy or locked database, so sqlive stopped
21    /// keeping them.
22    Statistics(Error<F, R>),
23    /// SQLite refused to remove a transaction's hook with this cause, so
24    /// what the connection calls next is unknown.
25    Hook(Error<F, R>),
26}
27
28/// Why a call failed.
29#[derive(Debug)]
30pub enum Error<F, R> {
31    /// SQLite refused or failed a statement, preserving its error.
32    Sqlite(rusqlite::Error),
33    /// A statement met damage SQLite reports (`SQLITE_CORRUPT`,
34    /// `SQLITE_NOTADB`).
35    DamagedDatabase,
36    /// The host's policy, or one of the host's SQL functions, refused a
37    /// statement with this refusal.
38    Refused(R),
39    /// App SQL tried transaction control, a PRAGMA, ATTACH, loading an
40    /// extension, changing a hidden rowid, or changing the schema outside a
41    /// migration.
42    StatementForbidden {
43        /// The refused operation.
44        operation: &'static str,
45    },
46    /// SQLite rolled the owned transaction back itself, so it can't go on.
47    TransactionEnded,
48    /// The handle has closed the database.
49    Closed,
50    /// The call's work panicked: a bug, which the caller reports.
51    Bug(Bug),
52    /// An earlier bug may have left the handle's state wrong, so the handle
53    /// failed with it, and every call fails with it until the host reopens
54    /// the database.
55    HandleFailed(Bug),
56    /// The host failed the handle with this failure.
57    Host(F),
58    /// sqlive broke a rule it relies on: a bug, not damage.
59    Invariant {
60        /// The broken rule.
61        what: &'static str,
62    },
63    /// SQLite kept another journal mode instead of WAL.
64    WalUnavailable {
65        /// The journal mode SQLite selected.
66        mode: String,
67    },
68    /// A SQLite setting is larger than SQLite can hold.
69    SqliteSettingOutOfRange {
70        /// The setting's PRAGMA name.
71        setting: &'static str,
72        /// The largest value SQLite holds for it.
73        maximum: u64,
74    },
75    /// The system refused a thread of sqlive's upkeep, so the database
76    /// did not open.
77    UpkeepThread(std::io::Error),
78    /// Opening the database's file at `path` failed. Only on Windows can a
79    /// name in the path mean another file once sqlive drops the path's
80    /// verbatim prefix.
81    Path {
82        /// The database file.
83        path: PathBuf,
84        /// What the file system answered.
85        source: std::io::Error,
86    },
87    /// A transaction failed and rolling it back failed too. The handle fails
88    /// with `EngineFailure::Rollback`.
89    Rollback {
90        /// The operation that required rollback.
91        operation: Box<Error<F, R>>,
92        /// SQLite's rollback failure.
93        rollback: rusqlite::Error,
94    },
95}
96
97impl<F: std::fmt::Display, R: std::fmt::Display> std::fmt::Display for Error<F, R> {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        match self {
100            Self::Sqlite(error) => error.fmt(f),
101            Self::DamagedDatabase => f.write_str("damaged database"),
102            Self::Refused(refusal) => refusal.fmt(f),
103            Self::StatementForbidden { operation } => {
104                write!(f, "app SQL cannot perform {operation}")
105            }
106            Self::TransactionEnded => f.write_str("SQLite ended the owned transaction"),
107            Self::Closed => f.write_str("the database is closed"),
108            Self::Bug(bug) => bug.fmt(f),
109            Self::HandleFailed(bug) => {
110                write!(
111                    f,
112                    "the database's handle failed on an earlier bug; reopen the database: {bug}"
113                )
114            }
115            Self::Host(failure) => failure.fmt(f),
116            Self::Invariant { what } => write!(f, "sqlive invariant failed: {what}"),
117            Self::WalUnavailable { mode } => {
118                write!(f, "SQLite kept journal mode {mode} instead of WAL")
119            }
120            Self::SqliteSettingOutOfRange { setting, maximum } => {
121                write!(f, "SQLite setting {setting} exceeds {maximum}")
122            }
123            Self::UpkeepThread(error) => write!(f, "an upkeep thread could not start: {error}"),
124            Self::Path { path, source } => write!(f, "open database at {path:?}: {source}"),
125            Self::Rollback { operation, rollback } => {
126                write!(f, "{operation}; rollback failed: {rollback}")
127            }
128        }
129    }
130}
131
132impl<F: std::error::Error + 'static, R: std::error::Error + 'static> std::error::Error
133    for Error<F, R>
134{
135    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
136        match self {
137            Self::Sqlite(error) => error.source(),
138            Self::Refused(refusal) => refusal.source(),
139            Self::Bug(bug) => bug.source(),
140            Self::Host(failure) => failure.source(),
141            Self::UpkeepThread(error) => Some(error),
142            Self::Path { source, .. } => Some(source),
143            Self::Rollback { rollback, .. } => Some(rollback),
144            _ => None,
145        }
146    }
147}
148
149impl<F, R> From<rusqlite::Error> for Error<F, R>
150where
151    F: std::error::Error + Send + Sync + 'static,
152    R: std::error::Error + Send + Sync + 'static,
153{
154    fn from(error: rusqlite::Error) -> Self {
155        match error {
156            // An error sqlive raised inside a SQL function or a column
157            // conversion comes back as it was raised.
158            rusqlite::Error::UserFunctionError(source) => match source.downcast::<Self>() {
159                Ok(error) => *error,
160                Err(source) => Self::Sqlite(rusqlite::Error::UserFunctionError(source)),
161            },
162            // SQLite found a page it can't read as what it should hold, or a
163            // file that isn't a database.
164            rusqlite::Error::SqliteFailure(failure, _)
165                if matches!(
166                    failure.code,
167                    rusqlite::ErrorCode::DatabaseCorrupt | rusqlite::ErrorCode::NotADatabase
168                ) =>
169            {
170                Self::DamagedDatabase
171            }
172            error => Self::Sqlite(error),
173        }
174    }
175}
176
177/// A caller's error for a transaction it runs: built from sqlive's
178/// errors, and able to keep a failed rollback beside its own cause.
179pub trait RollbackJoin<F, R>: From<Error<F, R>> {
180    /// Keep `rollback`, SQLite's failure to roll back, beside this error.
181    fn with_rollback(self, rollback: rusqlite::Error) -> Self;
182}
183
184impl<F, R> RollbackJoin<F, R> for Error<F, R> {
185    fn with_rollback(self, rollback: rusqlite::Error) -> Self {
186        Self::Rollback { operation: Box::new(self), rollback }
187    }
188}