use std::fmt;
use std::io;
use std::sync::Arc;
use giong::error::Code;
#[derive(Clone)]
pub struct Error(Arc<Inner>);
struct Inner {
kind: ErrorKind,
message: String,
db: Option<DbError>,
sqlstate: Option<&'static str>,
source: Option<io::Error>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Config,
Connect,
Auth,
Db,
Type,
RowCount,
TooLarge,
Closed,
PoolTimeout,
Protocol,
Statement,
}
impl ErrorKind {
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,
}))
}
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,
}))
}
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)
}
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())),
}))
}
pub fn kind(&self) -> ErrorKind {
self.0.kind
}
pub fn giong_code(&self) -> Code {
self.0.kind.giong_code()
}
pub fn db(&self) -> Option<&DbError> {
self.0.db.as_ref()
}
pub fn code(&self) -> Option<&str> {
match &self.0.db {
Some(db) => Some(db.code()),
None => self.0.sqlstate,
}
}
}
impl Error {
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))
}
}
#[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 {
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)
}
pub fn severity(&self) -> &str {
&self.severity
}
pub fn code(&self) -> &str {
&self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn detail(&self) -> Option<&str> {
self.detail.as_deref()
}
pub fn hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn position(&self) -> Option<u32> {
self.position
}
pub fn where_(&self) -> Option<&str> {
self.where_.as_deref()
}
pub fn schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn table(&self) -> Option<&str> {
self.table.as_deref()
}
pub fn column(&self) -> Option<&str> {
self.column.as_deref()
}
pub fn constraint(&self) -> Option<&str> {
self.constraint.as_deref()
}
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"
.replace("blob/main", concat!("blob/v", env!("CARGO_PKG_VERSION")))
);
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())));
}
}