1use std::fmt;
2
3pub type Result<T, E = Error> = std::result::Result<T, E>;
5
6#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum Error {
10 #[error("no `{table}` record found{}", DisplayKey(.key))]
12 NotFound {
13 table: &'static str,
15 key: Option<String>,
17 },
18
19 #[error("`{table}` record with primary key {key} was modified concurrently")]
23 Conflict {
24 table: &'static str,
26 key: String,
28 },
29
30 #[error("validation failed: {0}")]
33 Validation(crate::validate::ValidationErrors),
34
35 #[error("{0}")]
37 Hook(#[source] sqlx::error::BoxDynError),
38
39 #[error("invalid cursor: {0}")]
41 InvalidCursor(String),
42
43 #[error("failed to encode query parameter: {0}")]
45 Encode(#[source] sqlx::error::BoxDynError),
46
47 #[error("configuration error: {0}")]
49 Config(String),
50
51 #[error("invalid query: {0}")]
53 InvalidQuery(String),
54
55 #[error(transparent)]
57 Database(#[from] sqlx::Error),
58
59 #[cfg(feature = "migrate")]
61 #[error(transparent)]
62 Migrate(#[from] sqlx::migrate::MigrateError),
63}
64
65impl Error {
66 pub fn is_not_found(&self) -> bool {
68 matches!(
69 self,
70 Error::NotFound { .. } | Error::Database(sqlx::Error::RowNotFound)
71 )
72 }
73
74 pub fn hook(error: impl Into<sqlx::error::BoxDynError>) -> Self {
76 Error::Hook(error.into())
77 }
78
79 pub fn validation_errors(&self) -> Option<&crate::validate::ValidationErrors> {
81 match self {
82 Error::Validation(errors) => Some(errors),
83 _ => None,
84 }
85 }
86
87 pub fn is_conflict(&self) -> bool {
89 matches!(self, Error::Conflict { .. })
90 }
91
92 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 pub fn is_unique_violation(&self) -> bool {
102 self.db_error().is_some_and(|e| e.is_unique_violation())
103 }
104
105 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 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}