Communicate known foreign key violations to the user.
This commit is contained in:
+41
-3
@@ -5,8 +5,12 @@ pub mod transactions;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DatabaseError {
|
||||
#[error("Foreign key violation")]
|
||||
ForeignKeyViolation,
|
||||
#[error("Foreign key violation ({constraint}): {source}")]
|
||||
ForeignKeyViolation {
|
||||
constraint: Constraint,
|
||||
#[source]
|
||||
source: sqlx::Error,
|
||||
},
|
||||
|
||||
#[error("Internal error: {0}")]
|
||||
Internal(#[source] sqlx::Error),
|
||||
@@ -16,9 +20,43 @@ impl From<sqlx::Error> for DatabaseError {
|
||||
fn from(err: sqlx::Error) -> Self {
|
||||
match err {
|
||||
sqlx::Error::Database(db_err) if db_err.code().as_deref() == Some("23503") => {
|
||||
DatabaseError::ForeignKeyViolation
|
||||
let constraint = db_err
|
||||
.constraint()
|
||||
.map(Constraint::from)
|
||||
.unwrap_or(Constraint::Unknown(None));
|
||||
|
||||
DatabaseError::ForeignKeyViolation {
|
||||
constraint,
|
||||
source: sqlx::Error::Database(db_err),
|
||||
}
|
||||
}
|
||||
_ => DatabaseError::Internal(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Constraint {
|
||||
#[error("Recurring transaction source account constraint violation")]
|
||||
RecurringTransactionSourceAccount,
|
||||
|
||||
#[error("Recurring transaction destination account constraint violation")]
|
||||
RecurringTransactionDestinationAccount,
|
||||
|
||||
#[error("Unknown constraint violation: {0:?}")]
|
||||
Unknown(Option<String>),
|
||||
}
|
||||
|
||||
impl From<&str> for Constraint {
|
||||
fn from(constraint: &str) -> Self {
|
||||
match constraint {
|
||||
"fk_recurring_transactions_source_account" => {
|
||||
Constraint::RecurringTransactionSourceAccount
|
||||
}
|
||||
"fk_recurring_transactions_destination_account" => {
|
||||
Constraint::RecurringTransactionDestinationAccount
|
||||
}
|
||||
_ => Constraint::Unknown(Some(constraint.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user