Communicate known foreign key violations to the user.
This commit is contained in:
@@ -3,8 +3,8 @@ CREATE TABLE recurring_transactions (
|
|||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0),
|
amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0),
|
||||||
direction TEXT NOT NULL CHECK (direction IN ('in', 'out')),
|
direction TEXT NOT NULL CHECK (direction IN ('in', 'out')),
|
||||||
source_account_id UUID REFERENCES accounts (id),
|
source_account_id UUID CONSTRAINT fk_recurring_transactions_source_account REFERENCES accounts (id),
|
||||||
destination_account_id UUID REFERENCES accounts (id),
|
destination_account_id UUID CONSTRAINT fk_recurring_transactions_destination_account REFERENCES accounts (id),
|
||||||
starts_at TIMESTAMPTZ NOT NULL,
|
starts_at TIMESTAMPTZ NOT NULL,
|
||||||
ends_at TIMESTAMPTZ,
|
ends_at TIMESTAMPTZ,
|
||||||
recurrence_every INTEGER NOT NULL CHECK (recurrence_every > 0),
|
recurrence_every INTEGER NOT NULL CHECK (recurrence_every > 0),
|
||||||
|
|||||||
+41
-3
@@ -5,8 +5,12 @@ pub mod transactions;
|
|||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum DatabaseError {
|
pub enum DatabaseError {
|
||||||
#[error("Foreign key violation")]
|
#[error("Foreign key violation ({constraint}): {source}")]
|
||||||
ForeignKeyViolation,
|
ForeignKeyViolation {
|
||||||
|
constraint: Constraint,
|
||||||
|
#[source]
|
||||||
|
source: sqlx::Error,
|
||||||
|
},
|
||||||
|
|
||||||
#[error("Internal error: {0}")]
|
#[error("Internal error: {0}")]
|
||||||
Internal(#[source] sqlx::Error),
|
Internal(#[source] sqlx::Error),
|
||||||
@@ -16,9 +20,43 @@ impl From<sqlx::Error> for DatabaseError {
|
|||||||
fn from(err: sqlx::Error) -> Self {
|
fn from(err: sqlx::Error) -> Self {
|
||||||
match err {
|
match err {
|
||||||
sqlx::Error::Database(db_err) if db_err.code().as_deref() == Some("23503") => {
|
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),
|
_ => 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())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+41
-4
@@ -3,7 +3,10 @@ use axum::{
|
|||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{database::DatabaseError, domain::DomainError, repository::RepositoryError};
|
use crate::{
|
||||||
|
domain::DomainError,
|
||||||
|
repository::{ReferenceRelation, ReferenceViolationKind, RepositoryError},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum AppError {
|
pub enum AppError {
|
||||||
@@ -32,15 +35,49 @@ impl IntoResponse for AppError {
|
|||||||
Self::Domain(error) => {
|
Self::Domain(error) => {
|
||||||
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
||||||
}
|
}
|
||||||
Self::Repository(RepositoryError::Database(DatabaseError::ForeignKeyViolation)) => {
|
|
||||||
return error_response(StatusCode::UNPROCESSABLE_ENTITY, "Reference violation");
|
|
||||||
}
|
|
||||||
Self::Repository(RepositoryError::Database(error)) => {
|
Self::Repository(RepositoryError::Database(error)) => {
|
||||||
tracing::error!(%error, "Database query failed");
|
tracing::error!(%error, "Database query failed");
|
||||||
}
|
}
|
||||||
Self::Repository(RepositoryError::Decode(error)) => {
|
Self::Repository(RepositoryError::Decode(error)) => {
|
||||||
tracing::error!(%error, "Invalid stored data");
|
tracing::error!(%error, "Invalid stored data");
|
||||||
}
|
}
|
||||||
|
Self::Repository(RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::SourceAccount,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
..
|
||||||
|
}) => {
|
||||||
|
return error_response(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"Source account cannot be found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Self::Repository(RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::DestinationAccount,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
..
|
||||||
|
}) => {
|
||||||
|
return error_response(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"Destination account cannot be found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Self::Repository(RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::RecurringTransaction,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
..
|
||||||
|
}) => {
|
||||||
|
return error_response(
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
"Still referenced by one or more recurring transactions",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Self::Repository(RepositoryError::ReferenceViolation {
|
||||||
|
relation,
|
||||||
|
kind,
|
||||||
|
source,
|
||||||
|
}) => {
|
||||||
|
tracing::error!(%relation, %kind, error = ?source, "Unhandled reference violation");
|
||||||
|
}
|
||||||
Self::Repository(RepositoryError::QueryConversion(error)) => {
|
Self::Repository(RepositoryError::QueryConversion(error)) => {
|
||||||
return error_response(StatusCode::BAD_REQUEST, error.to_string());
|
return error_response(StatusCode::BAD_REQUEST, error.to_string());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,14 @@ pub enum RepositoryError {
|
|||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Decode(#[from] DecodeError),
|
Decode(#[from] DecodeError),
|
||||||
|
|
||||||
|
#[error("reference violation ({kind}: {relation})")]
|
||||||
|
ReferenceViolation {
|
||||||
|
relation: ReferenceRelation,
|
||||||
|
kind: ReferenceViolationKind,
|
||||||
|
#[source]
|
||||||
|
source: DatabaseError,
|
||||||
|
},
|
||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
QueryConversion(#[from] QueryConversionError),
|
QueryConversion(#[from] QueryConversionError),
|
||||||
}
|
}
|
||||||
@@ -45,6 +53,27 @@ pub enum DecodeError {
|
|||||||
WeekendAdjustment(String),
|
WeekendAdjustment(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum ReferenceRelation {
|
||||||
|
#[error("source account")]
|
||||||
|
SourceAccount,
|
||||||
|
|
||||||
|
#[error("destination account")]
|
||||||
|
DestinationAccount,
|
||||||
|
|
||||||
|
#[error("recurring transaction")]
|
||||||
|
RecurringTransaction,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum ReferenceViolationKind {
|
||||||
|
#[error("missing")]
|
||||||
|
Missing,
|
||||||
|
|
||||||
|
#[error("still referenced")]
|
||||||
|
StillReferenced,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum QueryConversionError {
|
pub enum QueryConversionError {
|
||||||
#[error("Failed to convert limit: {0}")]
|
#[error("Failed to convert limit: {0}")]
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ use std::collections::HashMap;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
DecodeError, QueryConversionError, RepositoryError,
|
DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError,
|
||||||
dtos::{Delete, Upsert},
|
dtos::{Delete, Upsert},
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{accounts as db, dtos::AccountRow},
|
database::{Constraint, DatabaseError, accounts as db, dtos::AccountRow},
|
||||||
domain::Account,
|
domain::Account,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -109,7 +109,32 @@ pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryEr
|
|||||||
where
|
where
|
||||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
{
|
{
|
||||||
Ok(db::delete_by_id(executor, id).await?.into())
|
let deleted = db::delete_by_id(executor, id)
|
||||||
|
.await
|
||||||
|
.map_err(classify_delete_error)?;
|
||||||
|
|
||||||
|
Ok(deleted.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
||||||
|
let is_recurring_transaction_reference = matches!(
|
||||||
|
&error,
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::RecurringTransactionSourceAccount
|
||||||
|
| Constraint::RecurringTransactionDestinationAccount,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if is_recurring_transaction_reference {
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::RecurringTransaction,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
source: error,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
RepositoryError::Database(error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode(row: AccountRow) -> Result<Account, DecodeError> {
|
fn decode(row: AccountRow) -> Result<Account, DecodeError> {
|
||||||
@@ -132,6 +157,39 @@ mod tests {
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint,
|
||||||
|
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_account_delete_foreign_key_constraint() {
|
||||||
|
let error = classify_delete_error(foreign_key_violation(
|
||||||
|
Constraint::RecurringTransactionSourceAccount,
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
&error,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::RecurringTransaction,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let database_error = std::error::Error::source(&error).unwrap();
|
||||||
|
let sqlx_error = std::error::Error::source(database_error).unwrap();
|
||||||
|
assert!(sqlx_error.to_string().contains("test database cause"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_unknown_account_delete_foreign_keys_generic() {
|
||||||
|
let error = classify_delete_error(foreign_key_violation(Constraint::Unknown(None)));
|
||||||
|
|
||||||
|
assert!(matches!(error, RepositoryError::Database(_)));
|
||||||
|
}
|
||||||
|
|
||||||
fn row() -> AccountRow {
|
fn row() -> AccountRow {
|
||||||
AccountRow {
|
AccountRow {
|
||||||
id: Uuid::new_v4(),
|
id: Uuid::new_v4(),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
DecodeError, QueryConversionError, RepositoryError,
|
DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError,
|
||||||
dtos::{Delete, Upsert},
|
dtos::{Delete, Upsert},
|
||||||
encoding::{
|
encoding::{
|
||||||
decode_direction, decode_recurrence_unit, decode_weekend_adjustment, encode_direction,
|
decode_direction, decode_recurrence_unit, decode_weekend_adjustment, encode_direction,
|
||||||
@@ -9,7 +9,9 @@ use super::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{dtos::RecurringTransactionRow, recurring_transactions as db},
|
database::{
|
||||||
|
Constraint, DatabaseError, dtos::RecurringTransactionRow, recurring_transactions as db,
|
||||||
|
},
|
||||||
domain::{Cents, Recurrence, RecurrenceInterval, RecurringTransaction, Schedule},
|
domain::{Cents, Recurrence, RecurrenceInterval, RecurringTransaction, Schedule},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -81,12 +83,36 @@ where
|
|||||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
{
|
{
|
||||||
let transaction = db::upsert(executor, encode(transaction))
|
let transaction = db::upsert(executor, encode(transaction))
|
||||||
.await?
|
.await
|
||||||
|
.map_err(classify_upsert_error)?
|
||||||
.try_map(decode)?;
|
.try_map(decode)?;
|
||||||
|
|
||||||
Ok(transaction.into())
|
Ok(transaction.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
|
||||||
|
let relation = match &error {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::RecurringTransactionSourceAccount,
|
||||||
|
..
|
||||||
|
} => Some(ReferenceRelation::SourceAccount),
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::RecurringTransactionDestinationAccount,
|
||||||
|
..
|
||||||
|
} => Some(ReferenceRelation::DestinationAccount),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
match relation {
|
||||||
|
Some(relation) => RepositoryError::ReferenceViolation {
|
||||||
|
relation,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
source: error,
|
||||||
|
},
|
||||||
|
None => RepositoryError::Database(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryError>
|
pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryError>
|
||||||
where
|
where
|
||||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
@@ -144,6 +170,51 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::domain::{Direction, RecurrenceUnit, ScheduleError, WeekendAdjustment};
|
use crate::domain::{Direction, RecurrenceUnit, ScheduleError, WeekendAdjustment};
|
||||||
|
|
||||||
|
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint,
|
||||||
|
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_upsert_foreign_key_constraints() {
|
||||||
|
let source = classify_upsert_error(foreign_key_violation(
|
||||||
|
Constraint::RecurringTransactionSourceAccount,
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
&source,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::SourceAccount,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let database_error = std::error::Error::source(&source).unwrap();
|
||||||
|
let sqlx_error = std::error::Error::source(database_error).unwrap();
|
||||||
|
assert!(sqlx_error.to_string().contains("test database cause"));
|
||||||
|
|
||||||
|
let destination = classify_upsert_error(foreign_key_violation(
|
||||||
|
Constraint::RecurringTransactionDestinationAccount,
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
&destination,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::DestinationAccount,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_unknown_upsert_foreign_keys_generic() {
|
||||||
|
let error = classify_upsert_error(foreign_key_violation(Constraint::Unknown(None)));
|
||||||
|
|
||||||
|
assert!(matches!(error, RepositoryError::Database(_)));
|
||||||
|
}
|
||||||
|
|
||||||
fn row() -> RecurringTransactionRow {
|
fn row() -> RecurringTransactionRow {
|
||||||
RecurringTransactionRow {
|
RecurringTransactionRow {
|
||||||
id: Uuid::new_v4(),
|
id: Uuid::new_v4(),
|
||||||
|
|||||||
Reference in New Issue
Block a user