diesel_async/pg/
error_helper.rs1use std::error::Error;
2use std::sync::Arc;
3
4use diesel::ConnectionError;
5use diesel::result::SqlState;
6
7pub(super) struct ErrorHelper(pub(super) tokio_postgres::Error);
8
9impl From<ErrorHelper> for ConnectionError {
10 fn from(postgres_error: ErrorHelper) -> Self {
11 ConnectionError::CouldntSetupConfiguration(postgres_error.into())
12 }
13}
14
15impl From<ErrorHelper> for diesel::result::Error {
16 fn from(ErrorHelper(postgres_error): ErrorHelper) -> Self {
17 from_tokio_postgres_error(Arc::new(postgres_error))
18 }
19}
20
21pub(super) fn from_tokio_postgres_error(
22 postgres_error: Arc<tokio_postgres::Error>,
23) -> diesel::result::Error {
24 use diesel::pg::sql_state;
25 use diesel::result::DatabaseErrorKind::*;
26
27 match postgres_error.code() {
28 Some(code) => {
29 let kind = match parse_sqlstate(code) {
30 Some(sql_state::UNIQUE_VIOLATION) => UniqueViolation,
31 Some(sql_state::FOREIGN_KEY_VIOLATION) => ForeignKeyViolation,
32 Some(sql_state::RESTRICT_VIOLATION) => RestrictViolation,
33 Some(sql_state::EXCLUSION_VIOLATION) => ExclusionViolation,
34 Some(sql_state::T_R_SERIALIZATION_FAILURE) => SerializationFailure,
35 Some(sql_state::READ_ONLY_SQL_TRANSACTION) => ReadOnlyTransaction,
36 Some(sql_state::NOT_NULL_VIOLATION) => NotNullViolation,
37 Some(sql_state::CHECK_VIOLATION) => CheckViolation,
38 _ => Unknown,
39 };
40
41 diesel::result::Error::DatabaseError(
42 kind,
43 Box::new(PostgresDbErrorWrapper(
44 postgres_error
45 .source()
46 .and_then(|e| e.downcast_ref::<tokio_postgres::error::DbError>().cloned())
47 .expect("It's a db error, because we've got a SQLState code above"),
48 )) as _,
49 )
50 }
51 None => diesel::result::Error::DatabaseError(
52 UnableToSendCommand,
53 Box::new(postgres_error.to_string()),
54 ),
55 }
56}
57
58fn parse_sqlstate(code: &tokio_postgres::error::SqlState) -> Option<SqlState> {
59 code.code().parse().ok()
60}
61
62struct PostgresDbErrorWrapper(tokio_postgres::error::DbError);
63
64impl diesel::result::DatabaseErrorInformation for PostgresDbErrorWrapper {
65 fn message(&self) -> &str {
66 self.0.message()
67 }
68
69 fn details(&self) -> Option<&str> {
70 self.0.detail()
71 }
72
73 fn hint(&self) -> Option<&str> {
74 self.0.hint()
75 }
76
77 fn table_name(&self) -> Option<&str> {
78 self.0.table()
79 }
80
81 fn column_name(&self) -> Option<&str> {
82 self.0.column()
83 }
84
85 fn constraint_name(&self) -> Option<&str> {
86 self.0.constraint()
87 }
88
89 fn statement_position(&self) -> Option<i32> {
90 use tokio_postgres::error::ErrorPosition;
91 self.0.position().and_then(|e| match *e {
92 ErrorPosition::Original(position) | ErrorPosition::Internal { position, .. } => {
93 position.try_into().ok()
94 }
95 })
96 }
97
98 fn sqlstate(&self) -> Option<SqlState> {
99 parse_sqlstate(self.0.code())
100 }
101}