Skip to main content

rok_db_core/
error.rs

1use std::fmt;
2
3/// Convenient alias for results returned by rok-db.
4pub type Result<T, E = Error> = std::result::Result<T, E>;
5
6/// Every error rok-db can produce.
7#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum Error {
10    /// A query that must return a row returned nothing.
11    #[error("no `{table}` record found{}", DisplayKey(.key))]
12    NotFound {
13        /// Table that was queried.
14        table: &'static str,
15        /// Primary key that was looked up, when known.
16        key: Option<String>,
17    },
18
19    /// An optimistic-locking check failed: the record was changed by someone
20    /// else since it was loaded (its `#[rok(version)]` column no longer
21    /// matches). Reload the record and retry.
22    #[error("`{table}` record with primary key {key} was modified concurrently")]
23    Conflict {
24        /// Table that was written.
25        table: &'static str,
26        /// Primary key of the record.
27        key: String,
28    },
29
30    /// The record failed validation (`#[rok(validate(…))]`); nothing was
31    /// written.
32    #[error("validation failed: {0}")]
33    Validation(crate::validate::ValidationErrors),
34
35    /// A lifecycle hook rejected the operation or failed.
36    #[error("{0}")]
37    Hook(#[source] sqlx::error::BoxDynError),
38
39    /// A pagination cursor could not be decoded.
40    #[error("invalid cursor: {0}")]
41    InvalidCursor(String),
42
43    /// Binding a parameter to the query failed.
44    #[error("failed to encode query parameter: {0}")]
45    Encode(#[source] sqlx::error::BoxDynError),
46
47    /// The configuration (e.g. `DATABASE_URL`) is missing or invalid.
48    #[error("configuration error: {0}")]
49    Config(String),
50
51    /// A query was built in a way that cannot be executed.
52    #[error("invalid query: {0}")]
53    InvalidQuery(String),
54
55    /// An error reported by the database driver.
56    #[error(transparent)]
57    Database(#[from] sqlx::Error),
58
59    /// An error raised while running migrations.
60    #[cfg(feature = "migrate")]
61    #[error(transparent)]
62    Migrate(#[from] sqlx::migrate::MigrateError),
63}
64
65impl Error {
66    /// `true` if this is a [`Error::NotFound`] (or the driver's own `RowNotFound`).
67    pub fn is_not_found(&self) -> bool {
68        matches!(
69            self,
70            Error::NotFound { .. } | Error::Database(sqlx::Error::RowNotFound)
71        )
72    }
73
74    /// Wrap any error returned from a [`Hooks`](crate::Hooks) method.
75    pub fn hook(error: impl Into<sqlx::error::BoxDynError>) -> Self {
76        Error::Hook(error.into())
77    }
78
79    /// The validation errors, if this is an [`Error::Validation`].
80    pub fn validation_errors(&self) -> Option<&crate::validate::ValidationErrors> {
81        match self {
82            Error::Validation(errors) => Some(errors),
83            _ => None,
84        }
85    }
86
87    /// `true` if this is an optimistic-locking [`Error::Conflict`].
88    pub fn is_conflict(&self) -> bool {
89        matches!(self, Error::Conflict { .. })
90    }
91
92    /// `true` for a serialization failure or deadlock (SQLSTATE `40001` /
93    /// `40P01`): the transaction can be retried as a whole.
94    pub fn is_serialization_failure(&self) -> bool {
95        self.db_error()
96            .and_then(|e| e.code())
97            .is_some_and(|code| code == "40001" || code == "40P01")
98    }
99
100    /// `true` if the database rejected the query because of a unique constraint.
101    pub fn is_unique_violation(&self) -> bool {
102        self.db_error().is_some_and(|e| e.is_unique_violation())
103    }
104
105    /// `true` if the database rejected the query because of a foreign key constraint.
106    pub fn is_foreign_key_violation(&self) -> bool {
107        self.db_error()
108            .is_some_and(|e| e.is_foreign_key_violation())
109    }
110
111    /// The name of the violated constraint, if any.
112    pub fn constraint(&self) -> Option<&str> {
113        self.db_error().and_then(|e| e.constraint())
114    }
115
116    fn db_error(&self) -> Option<&dyn sqlx::error::DatabaseError> {
117        match self {
118            Error::Database(sqlx::Error::Database(e)) => Some(e.as_ref()),
119            _ => None,
120        }
121    }
122
123    pub(crate) fn not_found<M: crate::Model>(key: Option<String>) -> Self {
124        Error::NotFound {
125            table: M::TABLE,
126            key,
127        }
128    }
129}
130
131struct DisplayKey<'a>(&'a Option<String>);
132
133impl fmt::Display for DisplayKey<'_> {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self.0 {
136            Some(key) => write!(f, " with primary key {key}"),
137            None => Ok(()),
138        }
139    }
140}