giong-postgres 0.6.0

A PostgreSQL client and connection pool for the giong thread-per-core runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! Errors: what went wrong, and what to do about it.

use std::fmt;
use std::io;
use std::sync::Arc;

use giong::error::Code;

/// An error from giong-postgres.
///
/// Every error says what happened and, where there is one, what to do about
/// it. It is shown with the giong error code of its kind in front, and the
/// link to that code's page at the end: `GIONG-E3003: password
/// authentication failed for user "app". See https://…/E3003.md`.
/// [`kind`](Self::kind) tells errors apart in code; errors the server
/// reported carry its fields in [`db`](Self::db), with the SQLSTATE code in
/// [`code`](Self::code).
///
/// Errors are cheap to clone, and convert into [`std::io::Error`], so `?`
/// works in functions that return `io::Result`; there,
/// [`giong::error::code`] finds the code, and
/// [`giong::error::Error::get_ref`] gives this error back.
#[derive(Clone)]
pub struct Error(Arc<Inner>);

struct Inner {
    kind: ErrorKind,
    message: String,
    db: Option<DbError>,
    /// A SQLSTATE for an error the server did not send as such (a `COMMIT`
    /// it turned into a rollback).
    sqlstate: Option<&'static str>,
    source: Option<io::Error>,
}

/// What kind of error it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The configuration or the connection URL is not valid.
    Config,
    /// Opening the connection failed: name resolution, TCP, TLS, or the
    /// connect timeout.
    Connect,
    /// The server refused the credentials, or asked for an authentication
    /// method this crate does not support.
    Auth,
    /// The server reported an error for the statement ([`Error::db`] has
    /// the details), or turned a `COMMIT` into a rollback because a statement
    /// in the transaction failed earlier ([`Error::code`] is `25P02` and
    /// [`Error::db`] is `None`).
    Db,
    /// A value could not be converted between Rust and PostgreSQL: a
    /// parameter, or a column read with [`Row::get`](crate::Row::get).
    Type,
    /// [`query_one`](crate::Client::query_one) found no row or more than one.
    RowCount,
    /// The result was larger than
    /// [`Config::max_result_size`](crate::Config::max_result_size).
    TooLarge,
    /// The connection is closed: the server closed it, the network failed, or
    /// an earlier error broke it. Open a new one (a [`Pool`](crate::Pool) does
    /// this by itself).
    Closed,
    /// No pooled connection became free within
    /// [`Pool::wait_timeout`](crate::Pool::wait_timeout).
    PoolTimeout,
    /// The server sent something this crate cannot understand. The connection
    /// is closed.
    Protocol,
    /// The statement cannot be sent this way, and was not: a statement that
    /// controls a transaction or changes the session (`SET`, `LISTEN`,
    /// `COPY ... FROM STDIN` and the like) on the connections a
    /// [`Pool`](crate::Pool) shares between tasks. The message says what to
    /// use instead.
    Statement,
}

impl ErrorKind {
    /// The giong error code for errors of this kind, `GIONG-E3001` to
    /// `GIONG-E3011`.
    pub fn giong_code(self) -> Code {
        match self {
            ErrorKind::Config => Code::PostgresConfig,
            ErrorKind::Connect => Code::PostgresConnect,
            ErrorKind::Auth => Code::PostgresAuth,
            ErrorKind::Db => Code::PostgresServer,
            ErrorKind::Type => Code::PostgresType,
            ErrorKind::RowCount => Code::PostgresRowCount,
            ErrorKind::TooLarge => Code::PostgresTooLarge,
            ErrorKind::Closed => Code::PostgresClosed,
            ErrorKind::PoolTimeout => Code::PostgresPoolTimeout,
            ErrorKind::Protocol => Code::PostgresProtocol,
            ErrorKind::Statement => Code::PostgresStatement,
        }
    }
}

impl Error {
    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self(Arc::new(Inner {
            kind,
            message: message.into(),
            db: None,
            sqlstate: None,
            source: None,
        }))
    }

    /// An error of kind [`ErrorKind::Db`] that the server did not report as
    /// an error, with the SQLSTATE that describes it.
    pub(crate) fn with_sqlstate(sqlstate: &'static str, message: impl Into<String>) -> Self {
        Self(Arc::new(Inner {
            kind: ErrorKind::Db,
            message: message.into(),
            db: None,
            sqlstate: Some(sqlstate),
            source: None,
        }))
    }

    pub(crate) fn io(kind: ErrorKind, message: impl Into<String>, source: io::Error) -> Self {
        Self(Arc::new(Inner {
            kind,
            message: message.into(),
            db: None,
            sqlstate: None,
            source: Some(source),
        }))
    }

    pub(crate) fn from_db(db: DbError, note: Option<String>) -> Self {
        Self(Arc::new(Inner {
            kind: ErrorKind::Db,
            message: note.unwrap_or_default(),
            db: Some(db),
            sqlstate: None,
            source: None,
        }))
    }

    pub(crate) fn with_db(kind: ErrorKind, message: impl Into<String>, db: DbError) -> Self {
        Self(Arc::new(Inner {
            kind,
            message: message.into(),
            db: Some(db),
            sqlstate: None,
            source: None,
        }))
    }

    /// An error for a value that cannot be converted, for implementations of
    /// [`ToSql`](crate::ToSql) and [`FromSql`](crate::FromSql). Say what the
    /// value was and what would work instead.
    pub fn conversion(message: impl Into<String>) -> Self {
        Self::new(ErrorKind::Type, message)
    }

    pub(crate) fn config(message: impl Into<String>) -> Self {
        Self::new(ErrorKind::Config, message)
    }

    pub(crate) fn protocol(message: impl Into<String>) -> Self {
        Self::new(
            ErrorKind::Protocol,
            format!(
                "{}; the connection was closed (is this really a PostgreSQL server?)",
                message.into()
            ),
        )
    }

    pub(crate) fn closed(message: impl Into<String>) -> Self {
        Self::new(ErrorKind::Closed, message)
    }

    /// The same error with `context` in front of its message.
    pub(crate) fn context(&self, context: &str) -> Self {
        Self(Arc::new(Inner {
            kind: self.0.kind,
            message: if self.0.message.is_empty() {
                context.to_owned()
            } else {
                format!("{context}: {}", self.0.message)
            },
            db: self.0.db.clone(),
            sqlstate: self.0.sqlstate,
            source: self
                .0
                .source
                .as_ref()
                .map(|e| io::Error::new(e.kind(), e.to_string())),
        }))
    }

    /// What kind of error this is.
    pub fn kind(&self) -> ErrorKind {
        self.0.kind
    }

    /// The giong error code, the one shown in front of the message: one
    /// for each [`ErrorKind`]. For the server's own code, see
    /// [`code`](Self::code).
    pub fn giong_code(&self) -> Code {
        self.0.kind.giong_code()
    }

    /// The error the server reported, for [`ErrorKind::Db`] (and for
    /// [`ErrorKind::Auth`] when the server refused the credentials).
    pub fn db(&self) -> Option<&DbError> {
        self.0.db.as_ref()
    }

    /// The SQLSTATE code of the server's error, such as `"23505"` for a
    /// unique violation. The codes are listed in the PostgreSQL manual,
    /// appendix A. A `COMMIT` that the server turned into a rollback has
    /// `"25P02"` (in failed SQL transaction), with no [`db`](Self::db).
    pub fn code(&self) -> Option<&str> {
        match &self.0.db {
            Some(db) => Some(db.code()),
            None => self.0.sqlstate,
        }
    }
}

impl Error {
    /// What happened: the message, the server's error and the cause, without
    /// the code and the link.
    fn what(&self) -> String {
        let inner = &self.0;
        let mut parts = Vec::with_capacity(3);
        if !inner.message.is_empty() {
            parts.push(inner.message.clone());
        }
        if let Some(db) = &inner.db {
            parts.push(db.to_string());
        }
        if let Some(source) = &inner.source {
            parts.push(source.to_string());
        }
        parts.join(": ")
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = self.giong_code();
        let what = self.what();
        let stop = if what.ends_with('.') { "" } else { "." };
        write!(f, "{code}: {what}{stop} See {}", code.url())
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Error")
            .field("kind", &self.0.kind)
            .field("message", &self.to_string())
            .finish()
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.0.source {
            Some(e) => Some(e),
            None => self.0.db.as_ref().map(|db| db as _),
        }
    }
}

impl From<Error> for io::Error {
    fn from(e: Error) -> Self {
        let kind = match (&e.0.source, e.kind()) {
            (Some(source), _) => source.kind(),
            (None, ErrorKind::Config | ErrorKind::Statement) => io::ErrorKind::InvalidInput,
            (None, ErrorKind::Auth) => io::ErrorKind::PermissionDenied,
            (None, ErrorKind::Type | ErrorKind::Protocol) => io::ErrorKind::InvalidData,
            (None, ErrorKind::PoolTimeout) => io::ErrorKind::TimedOut,
            (None, ErrorKind::Closed) => io::ErrorKind::ConnectionAborted,
            (None, _) => io::ErrorKind::Other,
        };
        io::Error::new(kind, giong::error::Error::wrap(e.giong_code(), e))
    }
}

/// An error reported by the server, with the fields of its `ErrorResponse`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DbError {
    severity: String,
    code: String,
    message: String,
    detail: Option<String>,
    hint: Option<String>,
    position: Option<u32>,
    where_: Option<String>,
    schema: Option<String>,
    table: Option<String>,
    column: Option<String>,
    constraint: Option<String>,
    routine: Option<String>,
}

impl DbError {
    /// Reads the fields of an `ErrorResponse` or `NoticeResponse` body.
    pub(crate) fn parse(body: &[u8]) -> Result<Self, Error> {
        let mut e = DbError {
            severity: String::new(),
            code: String::new(),
            message: String::new(),
            detail: None,
            hint: None,
            position: None,
            where_: None,
            schema: None,
            table: None,
            column: None,
            constraint: None,
            routine: None,
        };
        let mut rest = body;
        loop {
            let (&field, tail) = rest
                .split_first()
                .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
            if field == 0 {
                break;
            }
            let end = tail
                .iter()
                .position(|&b| b == 0)
                .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
            let value = String::from_utf8_lossy(&tail[..end]).into_owned();
            rest = &tail[end + 1..];
            match field {
                b'V' => e.severity = value,
                b'S' if e.severity.is_empty() => e.severity = value,
                b'C' => e.code = value,
                b'M' => e.message = value,
                b'D' => e.detail = Some(value),
                b'H' => e.hint = Some(value),
                b'P' => e.position = value.parse().ok(),
                b'W' => e.where_ = Some(value),
                b's' => e.schema = Some(value),
                b't' => e.table = Some(value),
                b'c' => e.column = Some(value),
                b'n' => e.constraint = Some(value),
                b'R' => e.routine = Some(value),
                _ => {}
            }
        }
        Ok(e)
    }

    /// `ERROR`, `FATAL` or `PANIC` (not localized).
    pub fn severity(&self) -> &str {
        &self.severity
    }

    /// The SQLSTATE code, such as `"23505"` (unique violation) or `"40001"`
    /// (serialization failure).
    pub fn code(&self) -> &str {
        &self.code
    }

    /// The primary message.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// More detail, when the server gave it.
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }

    /// A suggestion from the server about what to do.
    pub fn hint(&self) -> Option<&str> {
        self.hint.as_deref()
    }

    /// Where in the SQL text the error is, as a 1-based character position.
    pub fn position(&self) -> Option<u32> {
        self.position
    }

    /// The call stack, for errors inside functions.
    pub fn where_(&self) -> Option<&str> {
        self.where_.as_deref()
    }

    /// The schema of the object the error is about.
    pub fn schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    /// The table the error is about.
    pub fn table(&self) -> Option<&str> {
        self.table.as_deref()
    }

    /// The column the error is about.
    pub fn column(&self) -> Option<&str> {
        self.column.as_deref()
    }

    /// The constraint that was violated.
    pub fn constraint(&self) -> Option<&str> {
        self.constraint.as_deref()
    }

    /// The name of the server's source-code routine that reported the error,
    /// such as `RevalidateCachedQuery`. Unlike the message, it is never
    /// translated, so it tells errors with the same SQLSTATE apart whatever
    /// the server's `lc_messages`.
    pub fn routine(&self) -> Option<&str> {
        self.routine.as_deref()
    }
}

impl fmt::Display for DbError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}: {}", self.severity, self.code, self.message)?;
        if let Some(detail) = &self.detail {
            write!(f, " (detail: {detail})")?;
        }
        if let Some(hint) = &self.hint {
            write!(f, " (hint: {hint})")?;
        }
        if let Some(position) = self.position {
            write!(f, " (at character {position})")?;
        }
        Ok(())
    }
}

impl std::error::Error for DbError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn shown_with_its_giong_code_and_link() {
        let e = Error::new(
            ErrorKind::Auth,
            "password authentication failed for user \"app\"",
        );
        assert_eq!(
            e.to_string(),
            "GIONG-E3003: password authentication failed for user \"app\". See \
             https://github.com/giong-run/Giong/blob/main/docs/errors/E3003.md"
        );
        assert_eq!(e.giong_code(), Code::PostgresAuth);
    }

    #[test]
    fn the_code_and_the_error_survive_the_conversion_to_io() {
        let e = Error::new(ErrorKind::PoolTimeout, "no connection became free");
        let shown = e.to_string();
        let io: io::Error = e.into();
        assert_eq!(io.kind(), io::ErrorKind::TimedOut);
        assert_eq!(io.to_string(), shown);
        assert_eq!(giong::error::code(&io), Some(Code::PostgresPoolTimeout));
        let wrapped = io.get_ref().unwrap();
        let wrapped = wrapped.downcast_ref::<giong::error::Error>().unwrap();
        let back = wrapped.get_ref().unwrap().downcast_ref::<Error>().unwrap();
        assert_eq!(back.kind(), ErrorKind::PoolTimeout);
    }

    #[test]
    fn every_kind_has_its_own_code() {
        let kinds = [
            ErrorKind::Config,
            ErrorKind::Connect,
            ErrorKind::Auth,
            ErrorKind::Db,
            ErrorKind::Type,
            ErrorKind::RowCount,
            ErrorKind::TooLarge,
            ErrorKind::Closed,
            ErrorKind::PoolTimeout,
            ErrorKind::Protocol,
            ErrorKind::Statement,
        ];
        let codes: std::collections::HashSet<_> = kinds.iter().map(|k| k.giong_code()).collect();
        assert_eq!(codes.len(), kinds.len());
        assert!(codes.iter().all(|c| (3001..3100).contains(&c.number())));
    }
}