Standardized the upsert and delete pattern across the repo.
This commit is contained in:
@@ -2,7 +2,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
DatabaseError,
|
||||
dtos::{AccountRow, Delete, Upsert},
|
||||
dtos::{AccountRow, Upsert},
|
||||
};
|
||||
|
||||
pub struct Query {
|
||||
@@ -85,6 +85,7 @@ where
|
||||
name = EXCLUDED.name
|
||||
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||
old_row.id AS "old_id?",
|
||||
COALESCE(old_row.name, new_row.name) AS "old_name!",
|
||||
new_row.id AS "id!",
|
||||
new_row.name AS "name!"
|
||||
"#,
|
||||
@@ -95,30 +96,33 @@ where
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
let account = AccountRow {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
};
|
||||
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
|
||||
// coalesced with the new row's values in case there was no previous row. This enables static
|
||||
// typing on the previous row instead of having to check nullability for each old field in code.
|
||||
let previous = row.old_id.map(|id| AccountRow {
|
||||
id,
|
||||
name: row.old_name,
|
||||
});
|
||||
|
||||
if row.old_id.is_some() {
|
||||
Ok(Upsert::Updated(account))
|
||||
} else {
|
||||
Ok(Upsert::Created(account))
|
||||
}
|
||||
Ok(Upsert {
|
||||
previous,
|
||||
current: AccountRow {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Delete, DatabaseError>
|
||||
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<AccountRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let deleted = sqlx::query!("DELETE FROM accounts WHERE id = $1 RETURNING id", id)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
Ok(if deleted.is_some() {
|
||||
Delete::Deleted
|
||||
} else {
|
||||
Delete::NotFound
|
||||
})
|
||||
sqlx::query_as!(
|
||||
AccountRow,
|
||||
"DELETE FROM accounts WHERE id = $1 RETURNING id, name",
|
||||
id,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user