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/// [`code`](Self::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::code`] is `25P02` and
51    /// [`Error::db`] is `None`).
52    Db,
53    /// A value could not be converted between Rust and PostgreSQL: a
54    /// parameter, or a column read with [`Row::get`](crate::Row::get).
55    Type,
56    /// [`query_one`](crate::Client::query_one) found no row or more than one.
57    RowCount,
58    /// The result was larger than
59    /// [`Config::max_result_size`](crate::Config::max_result_size).
60    TooLarge,
61    /// The connection is closed: the server closed it, the network failed, or
62    /// an earlier error broke it. Open a new one (a [`Pool`](crate::Pool) does
63    /// this by itself).
64    Closed,
65    /// No pooled connection became free within
66    /// [`Pool::wait_timeout`](crate::Pool::wait_timeout).
67    PoolTimeout,
68    /// The server sent something this crate cannot understand. The connection
69    /// is closed.
70    Protocol,
71    /// The statement cannot be sent this way, and was not: a statement that
72    /// controls a transaction or changes the session (`SET`, `LISTEN`,
73    /// `COPY ... FROM STDIN` and the like) on the connections a
74    /// [`Pool`](crate::Pool) shares between tasks. The message says what to
75    /// use instead.
76    Statement,
77}
78
79impl ErrorKind {
80    /// The giong error code for errors of this kind, `GIONG-E3001` to
81    /// `GIONG-E3011`.
82    pub fn giong_code(self) -> Code {
83        match self {
84            ErrorKind::Config => Code::PostgresConfig,
85            ErrorKind::Connect => Code::PostgresConnect,
86            ErrorKind::Auth => Code::PostgresAuth,
87            ErrorKind::Db => Code::PostgresServer,
88            ErrorKind::Type => Code::PostgresType,
89            ErrorKind::RowCount => Code::PostgresRowCount,
90            ErrorKind::TooLarge => Code::PostgresTooLarge,
91            ErrorKind::Closed => Code::PostgresClosed,
92            ErrorKind::PoolTimeout => Code::PostgresPoolTimeout,
93            ErrorKind::Protocol => Code::PostgresProtocol,
94            ErrorKind::Statement => Code::PostgresStatement,
95        }
96    }
97}
98
99impl Error {
100    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
101        Self(Arc::new(Inner {
102            kind,
103            message: message.into(),
104            db: None,
105            sqlstate: None,
106            source: None,
107        }))
108    }
109
110    /// An error of kind [`ErrorKind::Db`] that the server did not report as
111    /// an error, with the SQLSTATE that describes it.
112    pub(crate) fn with_sqlstate(sqlstate: &'static str, message: impl Into<String>) -> Self {
113        Self(Arc::new(Inner {
114            kind: ErrorKind::Db,
115            message: message.into(),
116            db: None,
117            sqlstate: Some(sqlstate),
118            source: None,
119        }))
120    }
121
122    pub(crate) fn io(kind: ErrorKind, message: impl Into<String>, source: io::Error) -> Self {
123        Self(Arc::new(Inner {
124            kind,
125            message: message.into(),
126            db: None,
127            sqlstate: None,
128            source: Some(source),
129        }))
130    }
131
132    pub(crate) fn from_db(db: DbError, note: Option<String>) -> Self {
133        Self(Arc::new(Inner {
134            kind: ErrorKind::Db,
135            message: note.unwrap_or_default(),
136            db: Some(db),
137            sqlstate: None,
138            source: None,
139        }))
140    }
141
142    pub(crate) fn with_db(kind: ErrorKind, message: impl Into<String>, db: DbError) -> Self {
143        Self(Arc::new(Inner {
144            kind,
145            message: message.into(),
146            db: Some(db),
147            sqlstate: None,
148            source: None,
149        }))
150    }
151
152    /// An error for a value that cannot be converted, for implementations of
153    /// [`ToSql`](crate::ToSql) and [`FromSql`](crate::FromSql). Say what the
154    /// value was and what would work instead.
155    pub fn conversion(message: impl Into<String>) -> Self {
156        Self::new(ErrorKind::Type, message)
157    }
158
159    pub(crate) fn config(message: impl Into<String>) -> Self {
160        Self::new(ErrorKind::Config, message)
161    }
162
163    pub(crate) fn protocol(message: impl Into<String>) -> Self {
164        Self::new(
165            ErrorKind::Protocol,
166            format!(
167                "{}; the connection was closed (is this really a PostgreSQL server?)",
168                message.into()
169            ),
170        )
171    }
172
173    pub(crate) fn closed(message: impl Into<String>) -> Self {
174        Self::new(ErrorKind::Closed, message)
175    }
176
177    /// The same error with `context` in front of its message.
178    pub(crate) fn context(&self, context: &str) -> Self {
179        Self(Arc::new(Inner {
180            kind: self.0.kind,
181            message: if self.0.message.is_empty() {
182                context.to_owned()
183            } else {
184                format!("{context}: {}", self.0.message)
185            },
186            db: self.0.db.clone(),
187            sqlstate: self.0.sqlstate,
188            source: self
189                .0
190                .source
191                .as_ref()
192                .map(|e| io::Error::new(e.kind(), e.to_string())),
193        }))
194    }
195
196    /// What kind of error this is.
197    pub fn kind(&self) -> ErrorKind {
198        self.0.kind
199    }
200
201    /// The giong error code, the one shown in front of the message: one
202    /// for each [`ErrorKind`]. For the server's own code, see
203    /// [`code`](Self::code).
204    pub fn giong_code(&self) -> Code {
205        self.0.kind.giong_code()
206    }
207
208    /// The error the server reported, for [`ErrorKind::Db`] (and for
209    /// [`ErrorKind::Auth`] when the server refused the credentials).
210    pub fn db(&self) -> Option<&DbError> {
211        self.0.db.as_ref()
212    }
213
214    /// The SQLSTATE code of the server's error, such as `"23505"` for a
215    /// unique violation. The codes are listed in the PostgreSQL manual,
216    /// appendix A. A `COMMIT` that the server turned into a rollback has
217    /// `"25P02"` (in failed SQL transaction), with no [`db`](Self::db).
218    pub fn code(&self) -> Option<&str> {
219        match &self.0.db {
220            Some(db) => Some(db.code()),
221            None => self.0.sqlstate,
222        }
223    }
224}
225
226impl Error {
227    /// What happened: the message, the server's error and the cause, without
228    /// the code and the link.
229    fn what(&self) -> String {
230        let inner = &self.0;
231        let mut parts = Vec::with_capacity(3);
232        if !inner.message.is_empty() {
233            parts.push(inner.message.clone());
234        }
235        if let Some(db) = &inner.db {
236            parts.push(db.to_string());
237        }
238        if let Some(source) = &inner.source {
239            parts.push(source.to_string());
240        }
241        parts.join(": ")
242    }
243}
244
245impl fmt::Display for Error {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        let code = self.giong_code();
248        let what = self.what();
249        let stop = if what.ends_with('.') { "" } else { "." };
250        write!(f, "{code}: {what}{stop} See {}", code.url())
251    }
252}
253
254impl fmt::Debug for Error {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        f.debug_struct("Error")
257            .field("kind", &self.0.kind)
258            .field("message", &self.to_string())
259            .finish()
260    }
261}
262
263impl std::error::Error for Error {
264    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
265        match &self.0.source {
266            Some(e) => Some(e),
267            None => self.0.db.as_ref().map(|db| db as _),
268        }
269    }
270}
271
272impl From<Error> for io::Error {
273    fn from(e: Error) -> Self {
274        let kind = match (&e.0.source, e.kind()) {
275            (Some(source), _) => source.kind(),
276            (None, ErrorKind::Config | ErrorKind::Statement) => io::ErrorKind::InvalidInput,
277            (None, ErrorKind::Auth) => io::ErrorKind::PermissionDenied,
278            (None, ErrorKind::Type | ErrorKind::Protocol) => io::ErrorKind::InvalidData,
279            (None, ErrorKind::PoolTimeout) => io::ErrorKind::TimedOut,
280            (None, ErrorKind::Closed) => io::ErrorKind::ConnectionAborted,
281            (None, _) => io::ErrorKind::Other,
282        };
283        io::Error::new(kind, giong::error::Error::wrap(e.giong_code(), e))
284    }
285}
286
287/// An error reported by the server, with the fields of its `ErrorResponse`.
288#[derive(Clone, Debug, PartialEq, Eq)]
289pub struct DbError {
290    severity: String,
291    code: String,
292    message: String,
293    detail: Option<String>,
294    hint: Option<String>,
295    position: Option<u32>,
296    where_: Option<String>,
297    schema: Option<String>,
298    table: Option<String>,
299    column: Option<String>,
300    constraint: Option<String>,
301    routine: Option<String>,
302}
303
304impl DbError {
305    /// Reads the fields of an `ErrorResponse` or `NoticeResponse` body.
306    pub(crate) fn parse(body: &[u8]) -> Result<Self, Error> {
307        let mut e = DbError {
308            severity: String::new(),
309            code: String::new(),
310            message: String::new(),
311            detail: None,
312            hint: None,
313            position: None,
314            where_: None,
315            schema: None,
316            table: None,
317            column: None,
318            constraint: None,
319            routine: None,
320        };
321        let mut rest = body;
322        loop {
323            let (&field, tail) = rest
324                .split_first()
325                .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
326            if field == 0 {
327                break;
328            }
329            let end = tail
330                .iter()
331                .position(|&b| b == 0)
332                .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
333            let value = String::from_utf8_lossy(&tail[..end]).into_owned();
334            rest = &tail[end + 1..];
335            match field {
336                b'V' => e.severity = value,
337                b'S' if e.severity.is_empty() => e.severity = value,
338                b'C' => e.code = value,
339                b'M' => e.message = value,
340                b'D' => e.detail = Some(value),
341                b'H' => e.hint = Some(value),
342                b'P' => e.position = value.parse().ok(),
343                b'W' => e.where_ = Some(value),
344                b's' => e.schema = Some(value),
345                b't' => e.table = Some(value),
346                b'c' => e.column = Some(value),
347                b'n' => e.constraint = Some(value),
348                b'R' => e.routine = Some(value),
349                _ => {}
350            }
351        }
352        Ok(e)
353    }
354
355    /// `ERROR`, `FATAL` or `PANIC` (not localized).
356    pub fn severity(&self) -> &str {
357        &self.severity
358    }
359
360    /// The SQLSTATE code, such as `"23505"` (unique violation) or `"40001"`
361    /// (serialization failure).
362    pub fn code(&self) -> &str {
363        &self.code
364    }
365
366    /// The primary message.
367    pub fn message(&self) -> &str {
368        &self.message
369    }
370
371    /// More detail, when the server gave it.
372    pub fn detail(&self) -> Option<&str> {
373        self.detail.as_deref()
374    }
375
376    /// A suggestion from the server about what to do.
377    pub fn hint(&self) -> Option<&str> {
378        self.hint.as_deref()
379    }
380
381    /// Where in the SQL text the error is, as a 1-based character position.
382    pub fn position(&self) -> Option<u32> {
383        self.position
384    }
385
386    /// The call stack, for errors inside functions.
387    pub fn where_(&self) -> Option<&str> {
388        self.where_.as_deref()
389    }
390
391    /// The schema of the object the error is about.
392    pub fn schema(&self) -> Option<&str> {
393        self.schema.as_deref()
394    }
395
396    /// The table the error is about.
397    pub fn table(&self) -> Option<&str> {
398        self.table.as_deref()
399    }
400
401    /// The column the error is about.
402    pub fn column(&self) -> Option<&str> {
403        self.column.as_deref()
404    }
405
406    /// The constraint that was violated.
407    pub fn constraint(&self) -> Option<&str> {
408        self.constraint.as_deref()
409    }
410
411    /// The name of the server's source-code routine that reported the error,
412    /// such as `RevalidateCachedQuery`. Unlike the message, it is never
413    /// translated, so it tells errors with the same SQLSTATE apart whatever
414    /// the server's `lc_messages`.
415    pub fn routine(&self) -> Option<&str> {
416        self.routine.as_deref()
417    }
418}
419
420impl fmt::Display for DbError {
421    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422        write!(f, "{} {}: {}", self.severity, self.code, self.message)?;
423        if let Some(detail) = &self.detail {
424            write!(f, " (detail: {detail})")?;
425        }
426        if let Some(hint) = &self.hint {
427            write!(f, " (hint: {hint})")?;
428        }
429        if let Some(position) = self.position {
430            write!(f, " (at character {position})")?;
431        }
432        Ok(())
433    }
434}
435
436impl std::error::Error for DbError {}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441
442    #[test]
443    fn shown_with_its_giong_code_and_link() {
444        let e = Error::new(
445            ErrorKind::Auth,
446            "password authentication failed for user \"app\"",
447        );
448        assert_eq!(
449            e.to_string(),
450            "GIONG-E3003: password authentication failed for user \"app\". See \
451             https://github.com/giong-run/Giong/blob/main/docs/errors/E3003.md"
452        );
453        assert_eq!(e.giong_code(), Code::PostgresAuth);
454    }
455
456    #[test]
457    fn the_code_and_the_error_survive_the_conversion_to_io() {
458        let e = Error::new(ErrorKind::PoolTimeout, "no connection became free");
459        let shown = e.to_string();
460        let io: io::Error = e.into();
461        assert_eq!(io.kind(), io::ErrorKind::TimedOut);
462        assert_eq!(io.to_string(), shown);
463        assert_eq!(giong::error::code(&io), Some(Code::PostgresPoolTimeout));
464        let wrapped = io.get_ref().unwrap();
465        let wrapped = wrapped.downcast_ref::<giong::error::Error>().unwrap();
466        let back = wrapped.get_ref().unwrap().downcast_ref::<Error>().unwrap();
467        assert_eq!(back.kind(), ErrorKind::PoolTimeout);
468    }
469
470    #[test]
471    fn every_kind_has_its_own_code() {
472        let kinds = [
473            ErrorKind::Config,
474            ErrorKind::Connect,
475            ErrorKind::Auth,
476            ErrorKind::Db,
477            ErrorKind::Type,
478            ErrorKind::RowCount,
479            ErrorKind::TooLarge,
480            ErrorKind::Closed,
481            ErrorKind::PoolTimeout,
482            ErrorKind::Protocol,
483            ErrorKind::Statement,
484        ];
485        let codes: std::collections::HashSet<_> = kinds.iter().map(|k| k.giong_code()).collect();
486        assert_eq!(codes.len(), kinds.len());
487        assert!(codes.iter().all(|c| (3001..3100).contains(&c.number())));
488    }
489}