1use std::fmt;
4use std::io;
5use std::sync::Arc;
6
7use giong::error::Code;
8
9#[derive(Clone)]
24pub struct Error(Arc<Inner>);
25
26struct Inner {
27 kind: ErrorKind,
28 message: String,
29 db: Option<DbError>,
30 sqlstate: Option<&'static str>,
33 source: Option<io::Error>,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum ErrorKind {
40 Config,
42 Connect,
45 Auth,
48 Db,
56 Type,
59 RowCount,
61 TooLarge,
64 Closed,
68 PoolTimeout,
71 Protocol,
74 Statement,
80}
81
82impl ErrorKind {
83 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 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 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 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 pub fn kind(&self) -> ErrorKind {
201 self.0.kind
202 }
203
204 pub fn giong_code(&self) -> Code {
208 self.0.kind.giong_code()
209 }
210
211 pub fn db(&self) -> Option<&DbError> {
214 self.0.db.as_ref()
215 }
216
217 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 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 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#[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 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 pub fn severity(&self) -> &str {
400 &self.severity
401 }
402
403 pub fn code(&self) -> &str {
406 &self.code
407 }
408
409 pub fn message(&self) -> &str {
411 &self.message
412 }
413
414 pub fn detail(&self) -> Option<&str> {
416 self.detail.as_deref()
417 }
418
419 pub fn hint(&self) -> Option<&str> {
421 self.hint.as_deref()
422 }
423
424 pub fn position(&self) -> Option<u32> {
426 self.position
427 }
428
429 pub fn where_(&self) -> Option<&str> {
431 self.where_.as_deref()
432 }
433
434 pub fn schema(&self) -> Option<&str> {
436 self.schema.as_deref()
437 }
438
439 pub fn table(&self) -> Option<&str> {
441 self.table.as_deref()
442 }
443
444 pub fn column(&self) -> Option<&str> {
446 self.column.as_deref()
447 }
448
449 pub fn constraint(&self) -> Option<&str> {
451 self.constraint.as_deref()
452 }
453
454 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 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}