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