ts_sql/
error.rs

1//! Trait for mapping certain postgres errors.
2
3/// Trait for mapping certain postgres errors.
4pub trait SqlError: Sized {
5    /// Map a foreign key violation to a different error type.
6    fn fk_violation<E, F: FnOnce() -> E>(self, f: F) -> Result<Self, E>;
7    /// Map a unique violation to a different error type.
8    fn unique_violation<E, F: FnOnce() -> E>(self, f: F) -> Result<Self, E>;
9}
10
11impl<T> SqlError for Result<T, postgres::Error> {
12    fn fk_violation<E, F: FnOnce() -> E>(self, f: F) -> Result<Self, E> {
13        if let Err(error) = &self {
14            if let Some(sql_error) = error.code() {
15                if sql_error == &postgres::error::SqlState::FOREIGN_KEY_VIOLATION {
16                    return Err(f());
17                }
18            }
19        }
20
21        Ok(self)
22    }
23
24    fn unique_violation<E, F: FnOnce() -> E>(self, f: F) -> Result<Self, E> {
25        if let Err(error) = &self {
26            if let Some(sql_error) = error.code() {
27                if sql_error == &postgres::error::SqlState::UNIQUE_VIOLATION {
28                    return Err(f());
29                }
30            }
31        }
32
33        Ok(self)
34    }
35}