Standardized the upsert and delete pattern across the repo.

This commit is contained in:
2026-10-09 15:09:04 +02:00
parent 4a84c8330a
commit 66984567f8
30 changed files with 776 additions and 386 deletions
+25 -21
View File
@@ -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)
}
+4 -23
View File
@@ -1,25 +1,11 @@
pub enum Upsert<T> {
Created(T),
Updated(T),
}
impl<T> Upsert<T> {
pub fn try_map<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<Upsert<U>, E> {
Ok(match self {
Self::Created(value) => Upsert::Created(f(value)?),
Self::Updated(value) => Upsert::Updated(f(value)?),
})
}
}
pub struct Upserted<T> {
pub struct Upsert<T> {
pub current: T,
pub previous: Option<T>,
}
impl<T> Upserted<T> {
pub fn try_map<U, E>(self, mut f: impl FnMut(T) -> Result<U, E>) -> Result<Upserted<U>, E> {
Ok(Upserted {
impl<T> Upsert<T> {
pub fn try_map<U, E>(self, mut f: impl FnMut(T) -> Result<U, E>) -> Result<Upsert<U>, E> {
Ok(Upsert {
current: f(self.current)?,
previous: match self.previous {
Some(value) => Some(f(value)?),
@@ -28,8 +14,3 @@ impl<T> Upserted<T> {
})
}
}
pub enum Delete {
Deleted,
NotFound,
}
+62 -28
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, RecurringTransactionRow, Upsert},
dtos::{RecurringTransactionRow, Upsert},
};
pub struct Query {
@@ -108,6 +108,15 @@ where
weekend_adjustment = EXCLUDED.weekend_adjustment
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!",
COALESCE(old_row.account_id, new_row.account_id) AS "old_account_id!",
COALESCE(old_row.amount_cents, new_row.amount_cents) AS "old_amount_cents!",
COALESCE(old_row.direction, new_row.direction) AS "old_direction!",
COALESCE(old_row.starts_at, new_row.starts_at) AS "old_starts_at!",
old_row.ends_at AS "old_ends_at?",
COALESCE(old_row.recurrence_every, new_row.recurrence_every) AS "old_recurrence_every!",
COALESCE(old_row.recurrence_unit, new_row.recurrence_unit) AS "old_recurrence_unit!",
old_row.weekend_adjustment AS "old_weekend_adjustment?",
new_row.id AS "id!",
new_row.name AS "name!",
new_row.account_id AS "account_id!",
@@ -134,41 +143,66 @@ where
.await
.map_err(DatabaseError::from)?;
let transaction = RecurringTransactionRow {
id: row.id,
name: row.name,
account_id: row.account_id,
amount_cents: row.amount_cents,
direction: row.direction,
starts_at: row.starts_at,
ends_at: row.ends_at,
recurrence_every: row.recurrence_every,
recurrence_unit: row.recurrence_unit,
weekend_adjustment: row.weekend_adjustment,
};
// `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| RecurringTransactionRow {
id,
name: row.old_name,
account_id: row.old_account_id,
amount_cents: row.old_amount_cents,
direction: row.old_direction,
starts_at: row.old_starts_at,
ends_at: row.old_ends_at,
recurrence_every: row.old_recurrence_every,
recurrence_unit: row.old_recurrence_unit,
weekend_adjustment: row.old_weekend_adjustment,
});
if row.old_id.is_some() {
Ok(Upsert::Updated(transaction))
} else {
Ok(Upsert::Created(transaction))
}
Ok(Upsert {
previous,
current: RecurringTransactionRow {
id: row.id,
name: row.name,
account_id: row.account_id,
amount_cents: row.amount_cents,
direction: row.direction,
starts_at: row.starts_at,
ends_at: row.ends_at,
recurrence_every: row.recurrence_every,
recurrence_unit: row.recurrence_unit,
weekend_adjustment: row.weekend_adjustment,
},
})
}
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<RecurringTransactionRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!(
"DELETE FROM recurring_transactions WHERE id = $1 RETURNING id",
sqlx::query_as!(
RecurringTransactionRow,
r#"
DELETE FROM recurring_transactions
WHERE id = $1
RETURNING
id,
name,
account_id,
amount_cents,
direction,
starts_at,
ends_at,
recurrence_every,
recurrence_unit,
weekend_adjustment
"#,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
.map_err(DatabaseError::from)
}
+44 -25
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, TransactionRow, Upsert},
dtos::{TransactionRow, Upsert},
};
pub struct Query {
@@ -71,6 +71,11 @@ where
description = EXCLUDED.description
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.account_id, new_row.account_id) AS "old_account_id!",
COALESCE(old_row.amount_cents, new_row.amount_cents) AS "old_amount_cents!",
COALESCE(old_row.direction, new_row.direction) AS "old_direction!",
COALESCE(old_row.date, new_row.date) AS "old_date!",
COALESCE(old_row.description, new_row.description) AS "old_description!",
new_row.id AS "id!",
new_row.account_id AS "account_id!",
new_row.amount_cents AS "amount_cents!",
@@ -89,34 +94,48 @@ where
.await
.map_err(DatabaseError::from)?;
let transaction = TransactionRow {
id: row.id,
account_id: row.account_id,
amount_cents: row.amount_cents,
direction: row.direction,
date: row.date,
description: row.description,
};
// `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| TransactionRow {
id,
account_id: row.old_account_id,
amount_cents: row.old_amount_cents,
direction: row.old_direction,
date: row.old_date,
description: row.old_description,
});
if row.old_id.is_some() {
Ok(Upsert::Updated(transaction))
} else {
Ok(Upsert::Created(transaction))
}
Ok(Upsert {
previous,
current: TransactionRow {
id: row.id,
account_id: row.account_id,
amount_cents: row.amount_cents,
direction: row.direction,
date: row.date,
description: row.description,
},
})
}
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<TransactionRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!("DELETE FROM transactions 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!(
TransactionRow,
r#"
DELETE FROM transactions
WHERE id = $1
RETURNING id, account_id, amount_cents, direction, date, description
"#,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)
}
+33 -22
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, Upsert, UserAppSecretRow},
dtos::{Upsert, UserAppSecretRow},
};
pub struct Query {
@@ -73,6 +73,10 @@ where
expires_at = EXCLUDED.expires_at
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.app_id, new_row.app_id) AS "old_app_id!",
COALESCE(old_row.secret_hash, new_row.secret_hash) AS "old_secret_hash!",
COALESCE(old_row.expires_at, new_row.expires_at) AS "old_expires_at!",
COALESCE(old_row.created_at, new_row.created_at) AS "old_created_at!",
new_row.id AS "id!",
new_row.app_id AS "app_id!",
new_row.secret_hash AS "secret_hash!",
@@ -88,18 +92,26 @@ where
.await
.map_err(DatabaseError::from)?;
let secret = UserAppSecretRow {
id: row.id,
app_id: row.app_id,
secret_hash: row.secret_hash,
expires_at: row.expires_at,
created_at: row.created_at,
};
// `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| UserAppSecretRow {
id,
app_id: row.old_app_id,
secret_hash: row.old_secret_hash,
expires_at: row.old_expires_at,
created_at: row.old_created_at,
});
Ok(if row.old_id.is_some() {
Upsert::Updated(secret)
} else {
Upsert::Created(secret)
Ok(Upsert {
previous,
current: UserAppSecretRow {
id: row.id,
app_id: row.app_id,
secret_hash: row.secret_hash,
expires_at: row.expires_at,
created_at: row.created_at,
},
})
}
@@ -131,22 +143,21 @@ pub async fn delete_by_id<'e, E>(
executor: E,
app_id: Uuid,
id: Uuid,
) -> Result<Delete, DatabaseError>
) -> Result<Option<UserAppSecretRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!(
"DELETE FROM user_app_secrets WHERE app_id = $1 AND id = $2 RETURNING id",
sqlx::query_as!(
UserAppSecretRow,
r#"
DELETE FROM user_app_secrets
WHERE app_id = $1 AND id = $2
RETURNING id, app_id, secret_hash, expires_at, created_at
"#,
app_id,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
.map_err(DatabaseError::from)
}
+7 -12
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Upserted, UserAppRow},
dtos::{Upsert, UserAppRow},
};
pub struct Query {
@@ -67,7 +67,7 @@ where
pub async fn upsert<'e, E>(
executor: E,
app: UserAppRow,
) -> Result<Upserted<UserAppRow>, DatabaseError>
) -> Result<Upsert<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -92,14 +92,13 @@ where
// `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 for the previous row instead of having to check nullability for each old field
// individually.
// typing on the previous row instead of having to check nullability for each old field in code.
let previous = row.old_id.map(|id| UserAppRow {
id,
user_id: row.old_user_id,
});
Ok(Upserted {
Ok(Upsert {
previous,
current: UserAppRow {
id: row.id,
@@ -112,16 +111,12 @@ pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
sqlx::query_as!(
UserAppRow,
"DELETE FROM user_apps WHERE id = $1 RETURNING id, user_id",
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row.map(|row| UserAppRow {
id: row.id,
user_id: row.user_id,
}))
.map_err(DatabaseError::from)
}
+8 -17
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, Upsert, UserRow},
dtos::{Upsert, UserRow},
};
pub struct Query {
@@ -69,27 +69,18 @@ where
.await
.map_err(DatabaseError::from)?;
let user = UserRow { id: row.id };
if row.old_id.is_some() {
Ok(Upsert::Updated(user))
} else {
Ok(Upsert::Created(user))
}
Ok(Upsert {
previous: row.old_id.map(|id| UserRow { id }),
current: UserRow { id: row.id },
})
}
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<UserRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!("DELETE FROM users WHERE id = $1 RETURNING id", id)
sqlx::query_as!(UserRow, "DELETE FROM users WHERE id = $1 RETURNING id", id)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
.map_err(DatabaseError::from)
}