Skip to main content

renox_core/db/
error.rs

1use std::fmt;
2
3/// A database error: a query that failed, a lost connection, a broken
4/// constraint. Converts into [`crate::Error`] with `?`.
5///
6/// ```
7/// # use renox::prelude::*;
8/// # async fn demo(db: Db) -> Result {
9/// let inserted = renox::db::sql("INSERT INTO tags (name) VALUES (?)").bind("coffee").execute(&db).await;
10/// match inserted {
11///     Err(err) if err.is_unique_violation() => { /* already there */ }
12///     other => { other?; }
13/// }
14/// # Ok(()) }
15/// ```
16pub struct DbError(sqlx::Error, Option<String>);
17
18impl DbError {
19    /// A filter or sort named the sensitive custom field `key`, whose values
20    /// are sealed. Returned by `Query::with_custom_fields` and the grid; it
21    /// answers 400.
22    ///
23    /// ```
24    /// use renox::db::DbError;
25    /// let err = DbError::sealed_custom_field("tax_id");
26    /// assert_eq!(err.sealed_custom_field_key(), Some("tax_id"));
27    /// ```
28    pub fn sealed_custom_field(key: &str) -> Self {
29        Self(
30            sqlx::Error::Protocol(format!(
31                "custom field `{key}` is sensitive: it cannot be filtered, sorted or searched"
32            )),
33            Some(key.to_owned()),
34        )
35    }
36
37    /// The key of the sealed custom field a filter, sort or search named, if
38    /// this error is [`DbError::sealed_custom_field`].
39    pub fn sealed_custom_field_key(&self) -> Option<&str> {
40        self.1.as_deref()
41    }
42
43    /// A `UNIQUE` constraint (or primary key) was violated.
44    pub fn is_unique_violation(&self) -> bool {
45        matches!(&self.0, sqlx::Error::Database(db) if db.is_unique_violation())
46    }
47
48    /// A `REFERENCES` constraint was violated.
49    pub fn is_foreign_key_violation(&self) -> bool {
50        matches!(&self.0, sqlx::Error::Database(db) if db.is_foreign_key_violation())
51    }
52
53    /// `fetch_one` or `scalar` found no row.
54    pub fn is_row_not_found(&self) -> bool {
55        matches!(self.0, sqlx::Error::RowNotFound)
56    }
57
58    /// Another transaction got in the way and trying again may work:
59    /// SQLite's "database is locked" (busy), PostgreSQL's serialization
60    /// failure or deadlock. `Db::transaction_retrying` retries on these.
61    pub fn is_retryable(&self) -> bool {
62        let sqlx::Error::Database(db) = &self.0 else {
63            return false;
64        };
65        match db.code() {
66            Some(code) if code == "40001" || code == "40P01" => true,
67            // SQLite's primary codes 5 (BUSY) and 6 (LOCKED), extended or not.
68            Some(code) => code.parse::<i32>().is_ok_and(|c| matches!(c & 0xff, 5 | 6)),
69            None => false,
70        }
71    }
72
73    /// No connection was free within `DATABASE_ACQUIRE_TIMEOUT`.
74    pub fn is_timeout(&self) -> bool {
75        matches!(self.0, sqlx::Error::PoolTimedOut)
76    }
77
78    /// The underlying sqlx error, for what Renox doesn't cover. sqlx's
79    /// version isn't part of Renox's stability promise.
80    pub fn sqlx(&self) -> &sqlx::Error {
81        &self.0
82    }
83}
84
85impl From<sqlx::Error> for DbError {
86    fn from(err: sqlx::Error) -> Self {
87        Self(err, None)
88    }
89}
90
91impl fmt::Display for DbError {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        fmt::Display::fmt(&self.0, f)
94    }
95}
96
97impl fmt::Debug for DbError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        fmt::Debug::fmt(&self.0, f)
100    }
101}
102
103impl std::error::Error for DbError {
104    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
105        // The wrapped error's own cause; its message is already ours.
106        self.0.source()
107    }
108}
109
110/// A database error with a chosen code, for tests of the code checks.
111#[cfg(test)]
112pub(crate) mod fake {
113    use std::borrow::Cow;
114    use std::fmt;
115
116    use sqlx::error::{DatabaseError, ErrorKind};
117
118    #[derive(Debug)]
119    struct Coded(Option<&'static str>, ErrorKind);
120
121    impl fmt::Display for Coded {
122        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123            write!(f, "error {:?}", self.0)
124        }
125    }
126
127    impl std::error::Error for Coded {}
128
129    impl DatabaseError for Coded {
130        fn message(&self) -> &str {
131            "fake"
132        }
133        fn code(&self) -> Option<Cow<'_, str>> {
134            self.0.map(Cow::Borrowed)
135        }
136        fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
137            self
138        }
139        fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
140            self
141        }
142        fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
143            self
144        }
145        fn kind(&self) -> ErrorKind {
146            match self.1 {
147                ErrorKind::UniqueViolation => ErrorKind::UniqueViolation,
148                _ => ErrorKind::Other,
149            }
150        }
151    }
152
153    /// A database error answering `code`.
154    pub(crate) fn coded(code: Option<&'static str>) -> sqlx::Error {
155        sqlx::Error::Database(Box::new(Coded(code, ErrorKind::Other)))
156    }
157
158    /// PostgreSQL's unique violation.
159    pub(crate) fn unique() -> sqlx::Error {
160        sqlx::Error::Database(Box::new(Coded(Some("23505"), ErrorKind::UniqueViolation)))
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::{DbError, fake};
167
168    /// Retryable: PostgreSQL's serialization failure and deadlock, SQLite's
169    /// busy and locked with their extended codes; nothing else.
170    #[test]
171    fn retryable_codes() {
172        for code in ["40001", "40P01", "5", "517", "6", "262"] {
173            assert!(
174                DbError::from(fake::coded(Some(code))).is_retryable(),
175                "{code}"
176            );
177        }
178        for code in [Some("23505"), Some("19"), Some("XX000"), None] {
179            assert!(!DbError::from(fake::coded(code)).is_retryable(), "{code:?}");
180        }
181        assert!(!DbError::from(sqlx::Error::PoolTimedOut).is_retryable());
182        assert!(DbError::from(sqlx::Error::PoolTimedOut).is_timeout());
183        assert!(!DbError::from(sqlx::Error::PoolClosed).is_unique_violation());
184    }
185
186    /// PostgreSQL's 23505 is a unique violation, through `DbError` and
187    /// through `renox::Error`, also when the raw sqlx error was converted.
188    #[test]
189    fn unique_violations_through_every_wrapper() {
190        assert!(DbError::from(fake::unique()).is_unique_violation());
191        assert!(crate::Error::from(DbError::from(fake::unique())).is_unique_violation());
192        let raw = crate::Error::from(anyhow::Error::from(fake::unique()));
193        assert!(raw.is_unique_violation());
194        assert!(!crate::Error::from(anyhow::anyhow!("no")).is_unique_violation());
195        assert!(!crate::Error::NotFound.is_unique_violation());
196    }
197}