1use prax_query::QueryError;
4use thiserror::Error;
5
6pub type PgResult<T> = Result<T, PgError>;
8
9#[derive(Error, Debug)]
11pub enum PgError {
12 #[error("pool error: {0}")]
14 Pool(#[from] deadpool_postgres::PoolError),
15
16 #[error("postgres error: {0}")]
18 Postgres(#[from] tokio_postgres::Error),
19
20 #[error("configuration error: {0}")]
22 Config(String),
23
24 #[error("connection error: {0}")]
26 Connection(String),
27
28 #[error("query error: {0}")]
30 Query(String),
31
32 #[error("deserialization error: {0}")]
34 Deserialization(String),
35
36 #[error("type conversion error: {0}")]
38 TypeConversion(String),
39
40 #[error("operation timed out after {0}ms")]
42 Timeout(u64),
43
44 #[error("internal error: {0}")]
46 Internal(String),
47}
48
49impl PgError {
50 pub fn config(message: impl Into<String>) -> Self {
52 Self::Config(message.into())
53 }
54
55 pub fn connection(message: impl Into<String>) -> Self {
57 Self::Connection(message.into())
58 }
59
60 pub fn query(message: impl Into<String>) -> Self {
62 Self::Query(message.into())
63 }
64
65 pub fn deserialization(message: impl Into<String>) -> Self {
67 Self::Deserialization(message.into())
68 }
69
70 pub fn type_conversion(message: impl Into<String>) -> Self {
72 Self::TypeConversion(message.into())
73 }
74
75 pub fn is_connection_error(&self) -> bool {
77 matches!(self, Self::Pool(_) | Self::Connection(_))
78 }
79
80 pub fn is_timeout(&self) -> bool {
82 matches!(self, Self::Timeout(_))
83 }
84}
85
86pub(crate) fn classify_sqlstate(
114 code: Option<&str>,
115 display: &str,
116 detail: Option<&str>,
117) -> QueryError {
118 let gate_text = detail.unwrap_or(display);
119 let error = match code {
120 Some("23505") | Some("23503") | Some("23514") => {
122 QueryError::constraint_violation("", display)
123 }
124 Some("23502") => QueryError::invalid_input("", display),
126 Some("0A000") if gate_text.contains("cached plan must not change result type") => {
130 QueryError::stale_plan(display)
131 }
132 _ => QueryError::database(display),
133 };
134 match code {
135 Some(code) => error.with_sqlstate(code),
136 None => error,
137 }
138}
139
140fn pool_error_sqlstate(error: &deadpool_postgres::PoolError) -> Option<String> {
144 use deadpool_postgres::{HookError, PoolError};
145 let backend = match error {
146 PoolError::Backend(e) | PoolError::PostCreateHook(HookError::Backend(e)) => e,
147 _ => return None,
148 };
149 backend.code().map(|code| code.code().to_owned())
150}
151
152pub(crate) fn checkout_error(error: impl Into<PgError>) -> QueryError {
156 let error = error.into();
157 let sqlstate = match &error {
158 PgError::Pool(e) => pool_error_sqlstate(e),
159 _ => None,
160 };
161 let mapped = QueryError::connection(error.to_string()).with_source(error);
162 match sqlstate {
163 Some(sqlstate) => mapped.with_sqlstate(sqlstate),
164 None => mapped,
165 }
166}
167
168impl From<PgError> for QueryError {
169 fn from(err: PgError) -> Self {
170 match err {
171 PgError::Pool(e) => {
172 let sqlstate = pool_error_sqlstate(&e);
173 let mapped = QueryError::connection(e.to_string()).with_source(e);
174 match sqlstate {
175 Some(sqlstate) => mapped.with_sqlstate(sqlstate),
176 None => mapped,
177 }
178 }
179 PgError::Postgres(e) => {
180 let code_str = e.code().map(|c| c.code().to_owned());
185 let display = e.to_string();
186 let detail = e.as_db_error().map(|db| db.message().to_owned());
187 let mapped = classify_sqlstate(code_str.as_deref(), &display, detail.as_deref());
188 mapped.with_source(e)
189 }
190 PgError::Config(msg) => QueryError::connection(msg),
191 PgError::Connection(msg) => QueryError::connection(msg),
192 PgError::Query(msg) => QueryError::database(msg),
193 PgError::Deserialization(msg) => QueryError::serialization(msg),
194 PgError::TypeConversion(msg) => QueryError::serialization(msg),
195 PgError::Timeout(ms) => QueryError::timeout(ms),
196 PgError::Internal(msg) => QueryError::internal(msg),
197 }
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn test_error_creation() {
207 let err = PgError::config("invalid URL");
208 assert!(matches!(err, PgError::Config(_)));
209
210 let err = PgError::connection("connection refused");
211 assert!(err.is_connection_error());
212
213 let err = PgError::Timeout(5000);
214 assert!(err.is_timeout());
215 }
216
217 #[test]
218 fn test_into_query_error() {
219 let pg_err = PgError::Timeout(1000);
220 let query_err: QueryError = pg_err.into();
221 assert!(query_err.is_timeout());
222 }
223
224 #[test]
225 fn test_classify_constraint_sqlstates() {
226 use prax_query::ErrorCode;
227 for code in ["23505", "23503", "23514"] {
229 let e = classify_sqlstate(Some(code), "boom", None);
230 assert_eq!(e.code, ErrorCode::UniqueConstraint, "code {code}");
231 assert!(e.is_constraint_violation(), "code {code}");
232 }
233 assert_eq!(
235 classify_sqlstate(Some("23502"), "boom", None).code,
236 ErrorCode::InvalidParameter
237 );
238 }
239
240 #[test]
241 fn test_classify_stale_cached_plan_gates_on_detail() {
242 use prax_query::ErrorCode;
243 let e = classify_sqlstate(
246 Some("0A000"),
247 "db error",
248 Some("cached plan must not change result type"),
249 );
250 assert_eq!(e.code, ErrorCode::SerializationFailure);
251 assert!(e.is_retryable());
252
253 let e = classify_sqlstate(
256 Some("0A000"),
257 "cached plan must not change result type",
258 None,
259 );
260 assert_eq!(e.code, ErrorCode::SerializationFailure);
261 }
262
263 #[test]
264 fn test_classify_other_0a000_stays_generic() {
265 use prax_query::ErrorCode;
266 let e = classify_sqlstate(Some("0A000"), "db error", Some("cannot insert into a view"));
270 assert_eq!(e.code, ErrorCode::DatabaseError);
271 assert!(!e.is_retryable());
272 }
273
274 #[test]
275 fn classified_errors_keep_their_sqlstate() {
276 for code in ["23505", "23502", "0A000", "55P03", "40P01"] {
277 let e = classify_sqlstate(Some(code), "db error", Some("boom"));
278 assert_eq!(e.sqlstate(), Some(code), "code {code}");
279 }
280 assert_eq!(classify_sqlstate(None, "no code", None).sqlstate(), None);
281 assert_eq!(QueryError::from(PgError::Timeout(5)).sqlstate(), None);
283 }
284
285 #[test]
286 fn pool_errors_without_a_server_error_carry_no_sqlstate() {
287 use deadpool_postgres::{PoolError, TimeoutType};
288 for error in [PoolError::Timeout(TimeoutType::Wait), PoolError::Closed] {
289 let mapped = checkout_error(error);
290 assert!(mapped.is_connection_error(), "{mapped:?}");
291 assert_eq!(mapped.sqlstate(), None);
292 }
293 let mapped = QueryError::from(PgError::Pool(PoolError::Closed));
294 assert!(mapped.is_connection_error());
295 assert_eq!(mapped.sqlstate(), None);
296 }
297
298 #[test]
299 fn test_classify_unknown_sqlstate_is_generic() {
300 use prax_query::ErrorCode;
301 assert_eq!(
302 classify_sqlstate(Some("40P01"), "deadlock-ish", None).code,
303 ErrorCode::DatabaseError
304 );
305 assert_eq!(
306 classify_sqlstate(None, "no code", None).code,
307 ErrorCode::DatabaseError
308 );
309 }
310}