1use std::fmt;
2
3pub struct DbError(sqlx::Error, Option<String>);
17
18impl DbError {
19 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 pub fn sealed_custom_field_key(&self) -> Option<&str> {
40 self.1.as_deref()
41 }
42
43 pub fn is_unique_violation(&self) -> bool {
45 matches!(&self.0, sqlx::Error::Database(db) if db.is_unique_violation())
46 }
47
48 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 pub fn is_row_not_found(&self) -> bool {
55 matches!(self.0, sqlx::Error::RowNotFound)
56 }
57
58 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 Some(code) => code.parse::<i32>().is_ok_and(|c| matches!(c & 0xff, 5 | 6)),
69 None => false,
70 }
71 }
72
73 pub fn is_timeout(&self) -> bool {
75 matches!(self.0, sqlx::Error::PoolTimedOut)
76 }
77
78 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 self.0.source()
107 }
108}
109
110#[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 pub(crate) fn coded(code: Option<&'static str>) -> sqlx::Error {
155 sqlx::Error::Database(Box::new(Coded(code, ErrorKind::Other)))
156 }
157
158 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 #[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 #[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}