Skip to main content

prax_postgres/
error.rs

1//! Error types for PostgreSQL operations.
2
3use prax_query::QueryError;
4use thiserror::Error;
5
6/// Result type for PostgreSQL operations.
7pub type PgResult<T> = Result<T, PgError>;
8
9/// Errors that can occur during PostgreSQL operations.
10#[derive(Error, Debug)]
11pub enum PgError {
12    /// Connection pool error.
13    #[error("pool error: {0}")]
14    Pool(#[from] deadpool_postgres::PoolError),
15
16    /// PostgreSQL error.
17    #[error("postgres error: {0}")]
18    Postgres(#[from] tokio_postgres::Error),
19
20    /// Configuration error.
21    #[error("configuration error: {0}")]
22    Config(String),
23
24    /// Connection error.
25    #[error("connection error: {0}")]
26    Connection(String),
27
28    /// Query execution error.
29    #[error("query error: {0}")]
30    Query(String),
31
32    /// Row deserialization error.
33    #[error("deserialization error: {0}")]
34    Deserialization(String),
35
36    /// Type conversion error.
37    #[error("type conversion error: {0}")]
38    TypeConversion(String),
39
40    /// Timeout error.
41    #[error("operation timed out after {0}ms")]
42    Timeout(u64),
43
44    /// Internal error.
45    #[error("internal error: {0}")]
46    Internal(String),
47}
48
49impl PgError {
50    /// Create a configuration error.
51    pub fn config(message: impl Into<String>) -> Self {
52        Self::Config(message.into())
53    }
54
55    /// Create a connection error.
56    pub fn connection(message: impl Into<String>) -> Self {
57        Self::Connection(message.into())
58    }
59
60    /// Create a query error.
61    pub fn query(message: impl Into<String>) -> Self {
62        Self::Query(message.into())
63    }
64
65    /// Create a deserialization error.
66    pub fn deserialization(message: impl Into<String>) -> Self {
67        Self::Deserialization(message.into())
68    }
69
70    /// Create a type conversion error.
71    pub fn type_conversion(message: impl Into<String>) -> Self {
72        Self::TypeConversion(message.into())
73    }
74
75    /// Check if this is a connection error.
76    pub fn is_connection_error(&self) -> bool {
77        matches!(self, Self::Pool(_) | Self::Connection(_))
78    }
79
80    /// Check if this is a timeout error.
81    pub fn is_timeout(&self) -> bool {
82        matches!(self, Self::Timeout(_))
83    }
84}
85
86/// Map a PostgreSQL SQLSTATE code (and message) to a [`QueryError`].
87///
88/// Split out from the `From<PgError>` impl so the classification can be
89/// exercised directly in tests — a `tokio_postgres::Error` carrying a chosen
90/// SQLSTATE cannot be constructed by hand.
91///
92/// Recognized classes:
93///   * `23505` unique, `23503` foreign key, `23514` check → constraint
94///     violations.
95///   * `23502` not-null → invalid input.
96///   * `0A000` "cached plan must not change result type" → a *retryable*
97///     stale-plan error, so a pooled prepared statement invalidated by DDL is
98///     classified retryable (see [`QueryError::stale_plan`]) instead of an
99///     opaque generic database error. `0A000` is the shared
100///     `FEATURE_NOT_SUPPORTED` class, so this is gated on the server's message
101///     — other `0A000` conditions (genuinely unsupported features) are
102///     terminal and stay generic.
103///   * anything else → a generic database error.
104///
105/// The code is kept on the result as [`QueryError::sqlstate`].
106///
107/// `display` is the driver error's `Display` text (used as the error message);
108/// `detail` is the server's message string (`DbError::message`), used only for
109/// the `0A000` gate — a `tokio_postgres::Error` renders a DB error as just
110/// "db error" via `Display`, so the cached-plan text is only visible in the
111/// DbError. When `detail` is `None` (no DbError, e.g. a synthesized error) the
112/// gate falls back to `display`.
113pub(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        // Unique / foreign key / check violations.
121        Some("23505") | Some("23503") | Some("23514") => {
122            QueryError::constraint_violation("", display)
123        }
124        // Not null violation.
125        Some("23502") => QueryError::invalid_input("", display),
126        // Stale server-side prepared plan after DDL — transient, retry. The
127        // 0A000 class also covers real "feature not supported" errors, which
128        // are terminal, so match the specific cached-plan message.
129        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
140/// The SQLSTATE of the server error behind a failed pool checkout: the
141/// server refused the new connection (53300 too many connections, 57P03
142/// starting up, 28P01 wrong password, 3D000 no such database, ...).
143fn 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
152/// A failed pool checkout as a connection [`QueryError`] carrying the
153/// server's SQLSTATE (when the server refused the connection) and the
154/// error as its source.
155pub(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                // Categorize by SQLSTATE while preserving the driver error
181                // as the source. The cached-plan gate needs the server's
182                // message, which lives in the DbError — `Display` renders a DB
183                // error as just "db error".
184                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        // Unique, foreign key, and check all classify as constraint violations.
228        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        // Not-null maps to invalid input.
234        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        // Real Postgres path: Display is just "db error", the cached-plan text
244        // is only in the DbError detail. The gate must read `detail`.
245        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        // If the cached-plan text were only in Display (no detail), the
254        // fallback still catches it — defends the synthesized-error path.
255        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        // A genuine "feature not supported" 0A000 is terminal, not retryable —
267        // even though Display is "db error", the detail is not the cached-plan
268        // text.
269        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        // Errors without a server error carry none.
282        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}