-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmodel.rs
60 lines (57 loc) · 2.52 KB
/
model.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::sync::LazyLock;
use diesel::result::DatabaseErrorKind;
use regex::Regex;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("unique constraint violation: \"{constraint}\"")]
UniqueViolation { constraint: String },
#[error("check constraint violation on relation \"{relation}\": \"{constraint}\"")]
CheckViolation {
relation: String,
constraint: String,
},
#[error(transparent)]
DatabaseError(#[from] crate::DatabaseError),
}
impl From<diesel::result::Error> for Error {
fn from(e: diesel::result::Error) -> Self {
match &e {
diesel::result::Error::DatabaseError(DatabaseErrorKind::UniqueViolation, inner) => {
static RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r#"duplicate key value violates unique constraint "([0-9a-zA-Z_-]+)""#,
)
.unwrap()
});
if let Some(captures) = RE.captures((*inner).message()) {
Self::UniqueViolation {
constraint: captures.get(1).unwrap().as_str().to_string(),
}
} else {
// falling back to the generic error — since it's still semantically correct, logging the error is enough
tracing::error!(?RE, %e, "failed to parse PostgreSQL error message");
Self::DatabaseError(e.into())
}
}
diesel::result::Error::DatabaseError(DatabaseErrorKind::CheckViolation, inner) => {
static RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r#"new row for relation "([0-9a-zA-Z_-]+)" violates check constraint "([0-9a-zA-Z_-]+)""#,
)
.unwrap()
});
if let Some(captures) = RE.captures((*inner).message()) {
Self::CheckViolation {
relation: captures.get(1).unwrap().as_str().to_string(),
constraint: captures.get(2).unwrap().as_str().to_string(),
}
} else {
// falling back to the generic error — since it's still semantically correct, logging the error is enough
tracing::error!(?RE, %e, "failed to parse PostgreSQL error message");
Self::DatabaseError(e.into())
}
}
_ => Self::DatabaseError(e.into()),
}
}
}