Skip to content

Commit

Permalink
chore: new pattern for handling duplicate key violations
Browse files Browse the repository at this point in the history
  • Loading branch information
thevaibhav-dixit committed Dec 9, 2024
1 parent 0746dd8 commit 8499e6f
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions cala-ledger/src/transaction/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use sqlx::error::DatabaseError;
use thiserror::Error;

use cala_types::primitives::TransactionId;
Expand All @@ -7,8 +6,6 @@ use cala_types::primitives::TransactionId;
pub enum TransactionError {
#[error("TransactionError - Sqlx: {0}")]
Sqlx(sqlx::Error),
#[error("TransactionError - DuplicateKey: {0}")]
DuplicateKey(Box<dyn DatabaseError>),
#[error("TransactionError - NotFound: external id '{0}' not found")]
CouldNotFindByExternalId(String),
#[error("TransactionError - NotFound: id '{0}' not found")]
Expand All @@ -17,24 +14,29 @@ pub enum TransactionError {
EsEntityError(es_entity::EsEntityError),
#[error("TransactionError - CursorDestructureError: {0}")]
CursorDestructureError(#[from] es_entity::CursorDestructureError),
#[error("TransactionError - external_id already exists")]
ExternalIdAlreadyExists,
#[error("TransactionError - correlation_id already exists")]
CorrelationIdAlreadyExists,
#[error("TransactionError - DuplicateExternalId: external_id already exists")]
DuplicateExternalId,
#[error("TransactionError - DuplicateId: id already exists")]
DuplicateId,
}

impl From<sqlx::Error> for TransactionError {
fn from(error: sqlx::Error) -> Self {
if let Some(err) = error.as_database_error() {
if let Some(constraint) = err.constraint() {
fn from(e: sqlx::Error) -> Self {
match e {
sqlx::Error::Database(ref err) if err.is_unique_violation() => {
let Some(constraint) = err.constraint() else {
return Self::Sqlx(e);
};
if constraint.contains("external_id") {
return Self::ExternalIdAlreadyExists;
} else if constraint.contains("correlation_id") {
return Self::CorrelationIdAlreadyExists;
Self::DuplicateExternalId
} else if constraint.contains("id") {
Self::DuplicateId
} else {
Self::Sqlx(e)
}
}
e => Self::Sqlx(e),
}
Self::Sqlx(error)
}
}

Expand Down

0 comments on commit 8499e6f

Please sign in to comment.