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