Skip to main content

demesne_postgres/
error.rs

1use std::fmt;
2
3/// Why a live database could not be reached or read.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Error {
6    kind: Kind,
7    message: String,
8}
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11enum Kind {
12    ConnectionString,
13    Connect,
14    Query,
15    Sql,
16}
17
18impl Error {
19    pub(crate) fn connection_string(message: impl Into<String>) -> Self {
20        Error { kind: Kind::ConnectionString, message: message.into() }
21    }
22
23    pub(crate) fn connect(message: impl Into<String>) -> Self {
24        Error { kind: Kind::Connect, message: message.into() }
25    }
26
27    pub(crate) fn query(message: impl Into<String>) -> Self {
28        Error { kind: Kind::Query, message: message.into() }
29    }
30
31    pub(crate) fn sql(message: impl Into<String>) -> Self {
32        Error { kind: Kind::Sql, message: message.into() }
33    }
34
35    /// Returns whether the connection string does not parse.
36    #[must_use]
37    pub fn is_connection_string(&self) -> bool {
38        self.kind == Kind::ConnectionString
39    }
40
41    /// Returns whether no host in the connection string accepted a session: DNS, the network, TLS or authentication failed.
42    #[must_use]
43    pub fn is_connect(&self) -> bool {
44        self.kind == Kind::Connect
45    }
46
47    /// Returns whether a query against the connected database failed.
48    #[must_use]
49    pub fn is_query(&self) -> bool {
50        self.kind == Kind::Query
51    }
52
53    /// Returns whether the SQL to compare is not in the form demesne writes.
54    #[must_use]
55    pub fn is_sql(&self) -> bool {
56        self.kind == Kind::Sql
57    }
58}
59
60impl fmt::Display for Error {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(&self.message)
63    }
64}
65
66impl std::error::Error for Error {}