From 7b0b6409e558a3f9dfb8ca550f21d35a35840ccd Mon Sep 17 00:00:00 2001 From: Jon Seager Date: Mon, 2 Feb 2026 14:30:30 +0000 Subject: [PATCH] refactor(repos): use SQLx is_unique_violation for constraint checks Replace string matching on "UNIQUE constraint failed" with SQLx's type-safe is_unique_violation() method in roasters.rs and roasts.rs. This aligns with users.rs and tokens.rs, and ensures the check works across different database backends (SQLite, PostgreSQL) without depending on error message formatting. --- src/infrastructure/repositories/roasters.rs | 11 +++++++---- src/infrastructure/repositories/roasts.rs | 11 +++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/infrastructure/repositories/roasters.rs b/src/infrastructure/repositories/roasters.rs index de424ee..c13a089 100644 --- a/src/infrastructure/repositories/roasters.rs +++ b/src/infrastructure/repositories/roasters.rs @@ -120,11 +120,14 @@ impl RoasterRepository for SqlRoasterRepository { .fetch_one(&mut *tx) .await .map_err(|err| { - if err.to_string().contains("UNIQUE constraint failed") { - RepositoryError::Conflict("A roaster with this name and city already exists".to_string()) - } else { - RepositoryError::unexpected(err.to_string()) + if let sqlx::Error::Database(db_err) = &err + && db_err.is_unique_violation() + { + return RepositoryError::conflict( + "A roaster with this name and city already exists", + ); } + RepositoryError::unexpected(err.to_string()) })?; let roaster = Self::into_domain(record); diff --git a/src/infrastructure/repositories/roasts.rs b/src/infrastructure/repositories/roasts.rs index e524701..19e5816 100644 --- a/src/infrastructure/repositories/roasts.rs +++ b/src/infrastructure/repositories/roasts.rs @@ -112,11 +112,14 @@ impl RoastRepository for SqlRoastRepository { .fetch_one(&mut *tx) .await .map_err(|err| { - if err.to_string().contains("UNIQUE constraint failed") { - RepositoryError::Conflict("A roast with this name already exists for this roaster".to_string()) - } else { - map_insert_error(err, "unknown roaster reference") + if let sqlx::Error::Database(db_err) = &err + && db_err.is_unique_violation() + { + return RepositoryError::conflict( + "A roast with this name already exists for this roaster", + ); } + map_insert_error(err, "unknown roaster reference") })?; let roast = record.into_roast()?;