Skip to main content

giong_postgres/
error.rs

1//! Errors: what went wrong, and what to do about it.
2
3use std::fmt;
4use std::io;
5use std::sync::Arc;
6
7use giong::error::Code;
8
9/// An error from giong-postgres.
10///
11/// Every error says what happened and, where there is one, what to do about
12/// it. It is shown with the giong error code of its kind in front, and the
13/// link to that code's page at the end: `GIONG-E3003: password
14/// authentication failed for user "app". See https://…/E3003.md`.
15/// [`kind`](Self::kind) tells errors apart in code; errors the server
16/// reported carry its fields in [`db`](Self::db), with the SQLSTATE code in
17/// [`server_code`](Self::server_code).
18///
19/// Errors are cheap to clone, and convert into [`std::io::Error`], so `?`
20/// works in functions that return `io::Result`; there,
21/// [`giong::error::code`] finds the code, and
22/// [`giong::error::Error::get_ref`] gives this error back.
23#[derive(Clone)]
24pub struct Error(Arc<Inner>);
25
26struct Inner {
27    kind: ErrorKind,
28    message: String,
29    db: Option<DbError>,
30    /// A SQLSTATE for an error the server did not send as such (a `COMMIT`
31    /// it turned into a rollback).
32    sqlstate: Option<&'static str>,
33    source: Option<io::Error>,
34}
35
36/// What kind of error it is.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum ErrorKind {
40    /// The configuration or the connection URL is not valid.
41    Config,
42    /// Opening the connection failed: name resolution, TCP, TLS, or the
43    /// connect timeout.
44    Connect,
45    /// The server refused the credentials, or asked for an authentication
46    /// method this crate does not support.
47    Auth,
48    /// The server reported an error for the statement ([`Error::db`] has
49    /// the details), or turned a `COMMIT` into a rollback because a statement
50    /// in the transaction failed earlier ([`Error::server_code`] is `25P02` and
51    /// [`Error::db`] is `None`), or refused a statement or `COMMIT` in a
52    /// [`Transaction`](crate::Transaction) in which a statement was given up
53    /// before its answer came ([`Error::server_code`] and [`Error::db`] are
54    /// `None`).
55    Db,
56    /// A value could not be converted between Rust and PostgreSQL: a
57    /// parameter, or a column read with [`Row::get`](crate::Row::get).
58    Type,
59    /// [`query_one`](crate::Client::query_one) found no row or more than one.
60    RowCount,
61    /// The result was larger than
62    /// [`Config::max_result_size`](crate::Config::max_result_size).
63    TooLarge,
64    /// The connection is closed: the server closed it, the network failed, or
65    /// an earlier error broke it. Open a new one (a [`Pool`](crate::Pool) does
66    /// this by itself).
67    Closed,
68    /// No pooled connection became free within
69    /// [`Pool::wait_timeout`](crate::Pool::wait_timeout).
70    PoolTimeout,
71    /// The server sent something this crate cannot understand. The connection
72    /// is closed.
73    Protocol,
74    /// The statement cannot be sent this way, and was not: a statement that
75    /// controls a transaction or changes the session (`SET`, `LISTEN`,
76    /// `COPY ... FROM STDIN` and the like) on the connections a
77    /// [`Pool`](crate::Pool) shares between tasks. The message says what to
78    /// use instead.
79    Statement,
80}
81
82impl ErrorKind {
83    /// The giong error code for errors of this kind, `GIONG-E3001` to
84    /// `GIONG-E3011`.
85    pub fn giong_code(self) -> Code {
86        match self {
87            ErrorKind::Config => Code::PostgresConfig,
88            ErrorKind::Connect => Code::PostgresConnect,
89            ErrorKind::Auth => Code::PostgresAuth,
90            ErrorKind::Db => Code::PostgresServer,
91            ErrorKind::Type => Code::PostgresType,
92            ErrorKind::RowCount => Code::PostgresRowCount,
93            ErrorKind::TooLarge => Code::PostgresTooLarge,
94            ErrorKind::Closed => Code::PostgresClosed,
95            ErrorKind::PoolTimeout => Code::PostgresPoolTimeout,
96            ErrorKind::Protocol => Code::PostgresProtocol,
97            ErrorKind::Statement => Code::PostgresStatement,
98        }
99    }
100}
101
102impl Error {
103    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
104        Self(Arc::new(Inner {
105            kind,
106            message: message.into(),
107            db: None,
108            sqlstate: None,
109            source: None,
110        }))
111    }
112
113    /// An error of kind [`ErrorKind::Db`] that the server did not report as
114    /// an error, with the SQLSTATE that describes it.
115    pub(crate) fn with_sqlstate(sqlstate: &'static str, message: impl Into<String>) -> Self {
116        Self(Arc::new(Inner {
117            kind: ErrorKind::Db,
118            message: message.into(),
119            db: None,
120            sqlstate: Some(sqlstate),
121            source: None,
122        }))
123    }
124
125    pub(crate) fn io(kind: ErrorKind, message: impl Into<String>, source: io::Error) -> Self {
126        Self(Arc::new(Inner {
127            kind,
128            message: message.into(),
129            db: None,
130            sqlstate: None,
131            source: Some(source),
132        }))
133    }
134
135    pub(crate) fn from_db(db: DbError, note: Option<String>) -> Self {
136        Self(Arc::new(Inner {
137            kind: ErrorKind::Db,
138            message: note.unwrap_or_default(),
139            db: Some(db),
140            sqlstate: None,
141            source: None,
142        }))
143    }
144
145    pub(crate) fn with_db(kind: ErrorKind, message: impl Into<String>, db: DbError) -> Self {
146        Self(Arc::new(Inner {
147            kind,
148            message: message.into(),
149            db: Some(db),
150            sqlstate: None,
151            source: None,
152        }))
153    }
154
155    /// An error for a value that cannot be converted, for implementations of
156    /// [`ToSql`](crate::ToSql) and [`FromSql`](crate::FromSql). Say what the
157    /// value was and what would work instead.
158    pub fn conversion(message: impl Into<String>) -> Self {
159        Self::new(ErrorKind::Type, message)
160    }
161
162    pub(crate) fn config(message: impl Into<String>) -> Self {
163        Self::new(ErrorKind::Config, message)
164    }
165
166    pub(crate) fn protocol(message: impl Into<String>) -> Self {
167        Self::new(
168            ErrorKind::Protocol,
169            format!(
170                "{}; the connection was closed (is this really a PostgreSQL server?)",
171                message.into()
172            ),
173        )
174    }
175
176    pub(crate) fn closed(message: impl Into<String>) -> Self {
177        Self::new(ErrorKind::Closed, message)
178    }
179
180    /// The same error with `context` in front of its message.
181    pub(crate) fn context(&self, context: &str) -> Self {
182        Self(Arc::new(Inner {
183            kind: self.0.kind,
184            message: if self.0.message.is_empty() {
185                context.to_owned()
186            } else {
187                format!("{context}: {}", self.0.message)
188            },
189            db: self.0.db.clone(),
190            sqlstate: self.0.sqlstate,
191            source: self
192                .0
193                .source
194                .as_ref()
195                .map(|e| io::Error::new(e.kind(), e.to_string())),
196        }))
197    }
198
199    /// What kind of error this is.
200    pub fn kind(&self) -> ErrorKind {
201        self.0.kind
202    }
203
204    /// The giong error code, the one shown in front of the message: one
205    /// for each [`ErrorKind`]. For the server's own code, see
206    /// [`server_code`](Self::server_code).
207    pub fn giong_code(&self) -> Code {
208        self.0.kind.giong_code()
209    }
210
211    /// The error the server reported, for [`ErrorKind::Db`] (and for
212    /// [`ErrorKind::Auth`] when the server refused the credentials).
213    pub fn db(&self) -> Option<&DbError> {
214        self.0.db.as_ref()
215    }
216
217    /// The SQLSTATE code of the server's error, such as `"23505"` for a
218    /// unique violation. The codes are listed in the PostgreSQL manual,
219    /// appendix A. A `COMMIT` that the server turned into a rollback has
220    /// `"25P02"` (in failed SQL transaction), with no [`db`](Self::db). For
221    /// giong's own code, see [`giong_code`](Self::giong_code).
222    pub fn server_code(&self) -> Option<&str> {
223        match &self.0.db {
224            Some(db) => Some(db.code()),
225            None => self.0.sqlstate,
226        }
227    }
228
229    /// Whether trying again may succeed: the connection could not be
230    /// opened or broke, no pooled connection became free in time, or the
231    /// server reported a serialization failure (`40001`), a deadlock
232    /// (`40P01`), a lock it could not take (`55P03`), too many connections
233    /// (`53300`), a connection error (class `08`), that it is shutting down
234    /// or starting (`57P01`, `57P02`, `57P03`), or that it is a standby
235    /// (`25006`, after a failover: a [`Pool`](crate::Pool) opens a new
236    /// connection for the next try).
237    ///
238    /// A statement that changes data may have run before a
239    /// [`Closed`](ErrorKind::Closed) error: retrying it may run it twice. A
240    /// transaction that failed with `40001` or `40P01` is retried from its
241    /// start, not from the failed statement. A statement stopped by the
242    /// statement timeout (`57014`) is not counted: it would most likely run
243    /// as long again.
244    pub fn is_transient(&self) -> bool {
245        match self.0.kind {
246            ErrorKind::Connect | ErrorKind::Closed | ErrorKind::PoolTimeout => true,
247            ErrorKind::Db => match self.server_code() {
248                Some(code) => {
249                    code.starts_with("08")
250                        || matches!(
251                            code,
252                            "40001"
253                                | "40P01"
254                                | "55P03"
255                                | "53300"
256                                | "57P01"
257                                | "57P02"
258                                | "57P03"
259                                | "25006"
260                        )
261                }
262                None => false,
263            },
264            _ => false,
265        }
266    }
267}
268
269impl Error {
270    /// What happened: the message, the server's error and the cause, without
271    /// the code and the link.
272    fn what(&self) -> String {
273        let inner = &self.0;
274        let mut parts = Vec::with_capacity(3);
275        if !inner.message.is_empty() {
276            parts.push(inner.message.clone());
277        }
278        if let Some(db) = &inner.db {
279            parts.push(db.to_string());
280        }
281        if let Some(source) = &inner.source {
282            parts.push(source.to_string());
283        }
284        parts.join(": ")
285    }
286}
287
288impl fmt::Display for Error {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        let code = self.giong_code();
291        let what = self.what();
292        let stop = if what.ends_with('.') { "" } else { "." };
293        write!(f, "{code}: {what}{stop} See {}", code.url())
294    }
295}
296
297impl fmt::Debug for Error {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        f.debug_struct("Error")
300            .field("kind", &self.0.kind)
301            .field("message", &self.to_string())
302            .finish()
303    }
304}
305
306impl std::error::Error for Error {
307    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
308        match &self.0.source {
309            Some(e) => Some(e),
310            None => self.0.db.as_ref().map(|db| db as _),
311        }
312    }
313}
314
315impl From<Error> for io::Error {
316    fn from(e: Error) -> Self {
317        let kind = match (&e.0.source, e.kind()) {
318            (Some(source), _) => source.kind(),
319            (None, ErrorKind::Config | ErrorKind::Statement) => io::ErrorKind::InvalidInput,
320            (None, ErrorKind::Auth) => io::ErrorKind::PermissionDenied,
321            (None, ErrorKind::Type | ErrorKind::Protocol) => io::ErrorKind::InvalidData,
322            (None, ErrorKind::PoolTimeout) => io::ErrorKind::TimedOut,
323            (None, ErrorKind::Closed) => io::ErrorKind::ConnectionAborted,
324            (None, _) => io::ErrorKind::Other,
325        };
326        io::Error::new(kind, giong::error::Error::wrap(e.giong_code(), e))
327    }
328}
329
330/// An error reported by the server, with the fields of its `ErrorResponse`.
331#[derive(Clone, Debug, PartialEq, Eq)]
332pub struct DbError {
333    severity: String,
334    code: String,
335    message: String,
336    detail: Option<String>,
337    hint: Option<String>,
338    position: Option<u32>,
339    where_: Option<String>,
340    schema: Option<String>,
341    table: Option<String>,
342    column: Option<String>,
343    constraint: Option<String>,
344    routine: Option<String>,
345}
346
347impl DbError {
348    /// Reads the fields of an `ErrorResponse` or `NoticeResponse` body.
349    pub(crate) fn parse(body: &[u8]) -> Result<Self, Error> {
350        let mut e = DbError {
351            severity: String::new(),
352            code: String::new(),
353            message: String::new(),
354            detail: None,
355            hint: None,
356            position: None,
357            where_: None,
358            schema: None,
359            table: None,
360            column: None,
361            constraint: None,
362            routine: None,
363        };
364        let mut rest = body;
365        loop {
366            let (&field, tail) = rest
367                .split_first()
368                .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
369            if field == 0 {
370                break;
371            }
372            let end = tail
373                .iter()
374                .position(|&b| b == 0)
375                .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
376            let value = String::from_utf8_lossy(&tail[..end]).into_owned();
377            rest = &tail[end + 1..];
378            match field {
379                b'V' => e.severity = value,
380                b'S' if e.severity.is_empty() => e.severity = value,
381                b'C' => e.code = value,
382                b'M' => e.message = value,
383                b'D' => e.detail = Some(value),
384                b'H' => e.hint = Some(value),
385                b'P' => e.position = value.parse().ok(),
386                b'W' => e.where_ = Some(value),
387                b's' => e.schema = Some(value),
388                b't' => e.table = Some(value),
389                b'c' => e.column = Some(value),
390                b'n' => e.constraint = Some(value),
391                b'R' => e.routine = Some(value),
392                _ => {}
393            }
394        }
395        Ok(e)
396    }
397
398    /// `ERROR`, `FATAL` or `PANIC` (not localized).
399    pub fn severity(&self) -> &str {
400        &self.severity
401    }
402
403    /// The SQLSTATE code, such as `"23505"` (unique violation) or `"40001"`
404    /// (serialization failure).
405    pub fn code(&self) -> &str {
406        &self.code
407    }
408
409    /// The primary message.
410    pub fn message(&self) -> &str {
411        &self.message
412    }
413
414    /// More detail, when the server gave it.
415    pub fn detail(&self) -> Option<&str> {
416        self.detail.as_deref()
417    }
418
419    /// A suggestion from the server about what to do.
420    pub fn hint(&self) -> Option<&str> {
421        self.hint.as_deref()
422    }
423
424    /// Where in the SQL text the error is, as a 1-based character position.
425    pub fn position(&self) -> Option<u32> {
426        self.position
427    }
428
429    /// The call stack, for errors inside functions.
430    pub fn where_(&self) -> Option<&str> {
431        self.where_.as_deref()
432    }
433
434    /// The schema of the object the error is about.
435    pub fn schema(&self) -> Option<&str> {
436        self.schema.as_deref()
437    }
438
439    /// The table the error is about.
440    pub fn table(&self) -> Option<&str> {
441        self.table.as_deref()
442    }
443
444    /// The column the error is about.
445    pub fn column(&self) -> Option<&str> {
446        self.column.as_deref()
447    }
448
449    /// The constraint that was violated.
450    pub fn constraint(&self) -> Option<&str> {
451        self.constraint.as_deref()
452    }
453
454    /// The name of the server's source-code routine that reported the error,
455    /// such as `RevalidateCachedQuery`. Unlike the message, it is never
456    /// translated, so it tells errors with the same SQLSTATE apart whatever
457    /// the server's `lc_messages`.
458    pub fn routine(&self) -> Option<&str> {
459        self.routine.as_deref()
460    }
461}
462
463impl fmt::Display for DbError {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        write!(f, "{} {}: {}", self.severity, self.code, self.message)?;
466        if let Some(detail) = &self.detail {
467            write!(f, " (detail: {detail})")?;
468        }
469        if let Some(hint) = &self.hint {
470            write!(f, " (hint: {hint})")?;
471        }
472        if let Some(position) = self.position {
473            write!(f, " (at character {position})")?;
474        }
475        Ok(())
476    }
477}
478
479impl std::error::Error for DbError {}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    #[test]
486    fn shown_with_its_giong_code_and_link() {
487        let e = Error::new(
488            ErrorKind::Auth,
489            "password authentication failed for user \"app\"",
490        );
491        assert_eq!(
492            e.to_string(),
493            "GIONG-E3003: password authentication failed for user \"app\". See \
494             https://github.com/giong-run/Giong/blob/main/docs/errors/E3003.md"
495                .replace("blob/main", concat!("blob/v", env!("CARGO_PKG_VERSION")))
496        );
497        assert_eq!(e.giong_code(), Code::PostgresAuth);
498    }
499
500    #[test]
501    fn the_code_and_the_error_survive_the_conversion_to_io() {
502        let e = Error::new(ErrorKind::PoolTimeout, "no connection became free");
503        let shown = e.to_string();
504        let io: io::Error = e.into();
505        assert_eq!(io.kind(), io::ErrorKind::TimedOut);
506        assert_eq!(io.to_string(), shown);
507        assert_eq!(giong::error::code(&io), Some(Code::PostgresPoolTimeout));
508        let wrapped = io.get_ref().unwrap();
509        let wrapped = wrapped.downcast_ref::<giong::error::Error>().unwrap();
510        let back = wrapped.get_ref().unwrap().downcast_ref::<Error>().unwrap();
511        assert_eq!(back.kind(), ErrorKind::PoolTimeout);
512    }
513
514    #[test]
515    fn transient_errors_are_the_ones_worth_retrying() {
516        let db = |code: &str| {
517            // An ErrorResponse body: severity, SQLSTATE, message.
518            let mut body = Vec::new();
519            for (tag, value) in [(b'S', "ERROR"), (b'C', code), (b'M', "it failed")] {
520                body.push(tag);
521                body.extend_from_slice(value.as_bytes());
522                body.push(0);
523            }
524            body.push(0);
525            Error::from_db(DbError::parse(&body).unwrap(), None)
526        };
527        for code in [
528            "40001", "40P01", "55P03", "53300", "57P01", "57P02", "57P03", "25006", "08006",
529        ] {
530            assert!(db(code).is_transient(), "{code}");
531            assert_eq!(db(code).server_code(), Some(code));
532        }
533        for code in ["23505", "22012", "42601", "57014", "25P02", "28P01"] {
534            assert!(!db(code).is_transient(), "{code}");
535        }
536        for kind in [
537            ErrorKind::Connect,
538            ErrorKind::Closed,
539            ErrorKind::PoolTimeout,
540        ] {
541            assert!(Error::new(kind, "x").is_transient(), "{kind:?}");
542        }
543        for kind in [
544            ErrorKind::Config,
545            ErrorKind::Auth,
546            ErrorKind::Type,
547            ErrorKind::Statement,
548        ] {
549            assert!(!Error::new(kind, "x").is_transient(), "{kind:?}");
550        }
551        assert!(!Error::with_sqlstate("25P02", "rolled back").is_transient());
552    }
553
554    #[test]
555    fn every_kind_has_its_own_code() {
556        let kinds = [
557            ErrorKind::Config,
558            ErrorKind::Connect,
559            ErrorKind::Auth,
560            ErrorKind::Db,
561            ErrorKind::Type,
562            ErrorKind::RowCount,
563            ErrorKind::TooLarge,
564            ErrorKind::Closed,
565            ErrorKind::PoolTimeout,
566            ErrorKind::Protocol,
567            ErrorKind::Statement,
568        ];
569        let codes: std::collections::HashSet<_> = kinds.iter().map(|k| k.giong_code()).collect();
570        assert_eq!(codes.len(), kinds.len());
571        assert!(codes.iter().all(|c| (3001..3100).contains(&c.number())));
572    }
573}