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.
This commit is contained in:
Jon Seager 2026-02-02 14:30:30 +00:00
parent 2e4c8722ca
commit 7b0b6409e5
No known key found for this signature in database
2 changed files with 14 additions and 8 deletions

View file

@ -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);

View file

@ -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()?;