Moved domain logic out of the database layer, to the user app route.

This commit is contained in:
2026-10-09 14:47:30 +02:00
parent 0517ddd02e
commit 054cbe985d
11 changed files with 141 additions and 158 deletions
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, user_id\n FROM user_apps\n WHERE user_id = $1 AND id = $2\n ",
"query": "DELETE FROM user_apps WHERE id = $1 RETURNING id, user_id",
"describe": {
"columns": [
{
@@ -28,7 +28,6 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
@@ -37,5 +36,5 @@
false
]
},
"hash": "1726695ea4d8786d8e489a763cd615644f66ad541bbad08d38f4a67c86c57a37"
"hash": "40214db76bbef12fdb3acb184b115d7ddc4e266cbbc7695f796990f78c07e61d"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT user_id FROM user_apps WHERE id = $1 FOR SHARE",
"query": "SELECT user_id FROM user_apps WHERE id = $1 FOR KEY SHARE",
"describe": {
"columns": [
{
@@ -24,5 +24,5 @@
false
]
},
"hash": "f9a9d0e201e0f1c912d940fb6d0e4c27664bf4a0dbc2e71b2ade48df2e8dcd6e"
"hash": "53d120ed51ed58125e16bafaaf2850c48fbc5c5a259b0e0a6558d02828b98d98"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO user_apps (id, user_id)\n VALUES ($1, $2)\n ON CONFLICT (id) DO UPDATE SET\n id = EXCLUDED.id\n WHERE user_apps.user_id = $2\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.user_id AS \"user_id!\"\n ",
"query": "\n INSERT INTO user_apps (id, user_id)\n VALUES ($1, $2)\n ON CONFLICT (id) DO UPDATE SET\n user_id = user_apps.user_id\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.user_id, new_row.user_id) AS \"old_user_id!\",\n new_row.id AS \"id!\",\n new_row.user_id AS \"user_id!\"\n ",
"describe": {
"columns": [
{
@@ -16,6 +16,12 @@
},
{
"ordinal": 1,
"name": "old_user_id!",
"type_info": "Uuid",
"origin": "Expression"
},
{
"ordinal": 2,
"name": "id!",
"type_info": "Uuid",
"origin": {
@@ -26,7 +32,7 @@
}
},
{
"ordinal": 2,
"ordinal": 3,
"name": "user_id!",
"type_info": "Uuid",
"origin": {
@@ -45,9 +51,10 @@
},
"nullable": [
false,
null,
false,
false
]
},
"hash": "977a6afaf7511915973fd20ab3a3fb03aeda84d0d460c9db1b5b1e7025493879"
"hash": "bf2a5b137b07bc056060d1e2d55f096ec1f7279f90d37c3c11f6b4dc71708db9"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id",
"query": "SELECT id, user_id FROM user_apps WHERE id = $1",
"describe": {
"columns": [
{
@@ -13,17 +13,28 @@
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "user_apps",
"name": "user_id"
}
}
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false,
false
]
},
"hash": "38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e"
"hash": "ee6d6a2b689fc47af3d9702fd51c8c3cb30f1b496d03b748d24eb3bd854f4622"
}
+11 -10
View File
@@ -12,18 +12,19 @@ impl<T> Upsert<T> {
}
}
pub enum GuardedUpsert<T> {
Created(T),
Updated(T),
Rejected,
pub struct Upserted<T> {
pub current: T,
pub previous: Option<T>,
}
impl<T> GuardedUpsert<T> {
pub fn try_map<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<GuardedUpsert<U>, E> {
Ok(match self {
Self::Created(value) => GuardedUpsert::Created(f(value)?),
Self::Updated(value) => GuardedUpsert::Updated(f(value)?),
Self::Rejected => GuardedUpsert::Rejected,
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 {
current: f(self.current)?,
previous: match self.previous {
Some(value) => Some(f(value)?),
None => None,
},
})
}
}
+29 -42
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, GuardedUpsert, UserAppRow},
dtos::{Upserted, UserAppRow},
};
pub struct Query {
@@ -34,22 +34,13 @@ where
.map_err(DatabaseError::from)
}
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppRow>, DatabaseError>
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppRow,
r#"
SELECT id, user_id
FROM user_apps
WHERE user_id = $1 AND id = $2
"#,
user_id,
"SELECT id, user_id FROM user_apps WHERE id = $1",
id,
)
.fetch_optional(executor)
@@ -65,7 +56,7 @@ where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_scalar!(
"SELECT user_id FROM user_apps WHERE id = $1 FOR SHARE",
"SELECT user_id FROM user_apps WHERE id = $1 FOR KEY SHARE",
app_id,
)
.fetch_optional(executor)
@@ -76,7 +67,7 @@ where
pub async fn upsert<'e, E>(
executor: E,
app: UserAppRow,
) -> Result<GuardedUpsert<UserAppRow>, DatabaseError>
) -> Result<Upserted<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -85,56 +76,52 @@ where
INSERT INTO user_apps (id, user_id)
VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE SET
id = EXCLUDED.id
WHERE user_apps.user_id = $2
user_id = user_apps.user_id
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.user_id, new_row.user_id) AS "old_user_id!",
new_row.id AS "id!",
new_row.user_id AS "user_id!"
"#,
app.id,
app.user_id,
)
.fetch_optional(executor)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)?;
let Some(row) = row else {
return Ok(GuardedUpsert::Rejected);
};
// `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.
let previous = row.old_id.map(|id| UserAppRow {
id,
user_id: row.old_user_id,
});
let app = UserAppRow {
id: row.id,
user_id: row.user_id,
};
Ok(if row.old_id.is_some() {
GuardedUpsert::Updated(app)
} else {
GuardedUpsert::Created(app)
Ok(Upserted {
previous,
current: UserAppRow {
id: row.id,
user_id: row.user_id,
},
})
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Delete, DatabaseError>
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!(
"DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id",
user_id,
let row = sqlx::query!(
"DELETE FROM user_apps WHERE id = $1 RETURNING id, user_id",
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
Ok(row.map(|row| UserAppRow {
id: row.id,
user_id: row.user_id,
}))
}
+9 -9
View File
@@ -54,12 +54,6 @@ impl IntoResponse for AppError {
Self::Repository(RepositoryError::Decode(error)) => {
tracing::error!(%error, "invalid stored data");
}
Self::Repository(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}) => {
tracing::warn!("user app ownership conflict");
return error_response(StatusCode::CONFLICT, "User app belongs to another user");
}
Self::Repository(RepositoryError::NotFound {
relation: ReferenceRelation::User,
}) => {
@@ -72,12 +66,18 @@ impl IntoResponse for AppError {
tracing::debug!("user app not found");
return error_response(StatusCode::NOT_FOUND, "User app cannot be found");
}
Self::Repository(RepositoryError::OwnershipConflict { relation }) => {
tracing::error!(%relation, "unhandled ownership conflict");
}
Self::Repository(RepositoryError::NotFound { relation }) => {
tracing::error!(%relation, "unhandled not found");
}
Self::Repository(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}) => {
tracing::warn!("user app ownership conflict");
return error_response(StatusCode::CONFLICT, "User app ID is already in use");
}
Self::Repository(RepositoryError::OwnershipConflict { relation }) => {
tracing::error!(%relation, "unhandled ownership conflict");
}
Self::Repository(RepositoryError::ReferenceViolation {
relation: ReferenceRelation::User,
kind: ReferenceViolationKind::Missing,
+3 -3
View File
@@ -21,12 +21,12 @@ pub enum RepositoryError {
#[error(transparent)]
Decode(#[from] DecodeError),
#[error("{relation} is owned by another user")]
OwnershipConflict { relation: ReferenceRelation },
#[error("{relation} cannot be found")]
NotFound { relation: ReferenceRelation },
#[error("{relation} is owned by another user")]
OwnershipConflict { relation: ReferenceRelation },
#[error("reference violation ({kind}: {relation})")]
ReferenceViolation {
relation: ReferenceRelation,
+14
View File
@@ -14,6 +14,20 @@ impl<T> From<database::dtos::Upsert<T>> for Upsert<T> {
}
}
pub struct Upserted<T> {
pub current: T,
pub previous: Option<T>,
}
impl<T> From<database::dtos::Upserted<T>> for Upserted<T> {
fn from(value: database::dtos::Upserted<T>) -> Self {
Self {
current: value.current,
previous: value.previous,
}
}
}
pub enum Delete {
Deleted,
NotFound,
+16 -70
View File
@@ -1,12 +1,8 @@
use uuid::Uuid;
use super::{QueryConversionError, ReferenceRelation, RepositoryError, dtos::Upsert};
use super::{QueryConversionError, RepositoryError, dtos::Upserted};
use crate::{
database::{
Constraint, DatabaseError,
dtos::{GuardedUpsert, UserAppRow},
user_apps as db,
},
database::{Constraint, DatabaseError, dtos::UserAppRow, user_apps as db},
domain::UserApp,
repository::DecodeError,
};
@@ -42,15 +38,11 @@ where
Ok(apps)
}
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserApp>, RepositoryError>
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let app = db::get_by_id(executor, user_id, id)
let app = db::get_by_id(executor, id)
.await?
.map(decode)
.transpose()?;
@@ -70,27 +62,17 @@ where
Ok(owner)
}
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upsert<UserApp>, RepositoryError>
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upserted<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let outcome = db::upsert(executor, encode(app))
let app = db::upsert(executor, encode(app))
.await
.map_err(classify_upsert_error)?;
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
map_upsert(outcome)
}
fn map_upsert(outcome: GuardedUpsert<UserAppRow>) -> Result<Upsert<UserApp>, RepositoryError> {
Ok(match outcome.try_map(decode)? {
GuardedUpsert::Created(app) => Upsert::Created(app),
GuardedUpsert::Updated(app) => Upsert::Updated(app),
GuardedUpsert::Rejected => {
return Err(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
});
}
})
Ok(app)
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
@@ -107,17 +89,16 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
}
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<super::dtos::Delete, RepositoryError>
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let result = db::delete_by_id(executor, user_id, id).await?.into();
let app = db::delete_by_id(executor, id)
.await?
.map(decode)
.transpose()?;
Ok(result)
Ok(app)
}
fn decode(row: UserAppRow) -> Result<UserApp, DecodeError> {
@@ -164,41 +145,6 @@ mod tests {
assert!(matches!(error, RepositoryError::Database(_)));
}
#[test]
fn maps_created_upsert() {
let row = row();
let id = row.id;
let Ok(Upsert::Created(app)) = map_upsert(GuardedUpsert::Created(row)) else {
panic!("expected created upsert");
};
assert_eq!(app.id, id);
}
#[test]
fn maps_updated_upsert() {
let row = row();
let id = row.id;
let Ok(Upsert::Updated(app)) = map_upsert(GuardedUpsert::Updated(row)) else {
panic!("expected updated upsert");
};
assert_eq!(app.id, id);
}
#[test]
fn maps_rejected_upsert_to_ownership_conflict() {
let Err(error) = map_upsert(GuardedUpsert::Rejected) else {
panic!("expected ownership conflict");
};
assert!(matches!(
error,
RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}
));
}
fn row() -> UserAppRow {
UserAppRow {
id: Uuid::new_v4(),
+31 -13
View File
@@ -9,10 +9,7 @@ use super::{
};
use crate::{
error::AppError,
repository::{
self,
dtos::{Delete, Upsert},
},
repository::{self, ReferenceRelation, RepositoryError},
};
pub fn create_router() -> axum::Router<PgPool> {
@@ -60,8 +57,9 @@ async fn get_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
) -> Result<Json<UserAppResponse>, AppError> {
let app = repository::user_apps::get_by_id(&pool, user_id, app_id)
let app = repository::user_apps::get_by_id(&pool, app_id)
.await?
.filter(|app| app.user_id == user_id)
.ok_or(AppError::NotFound)?;
Ok(Json(app.into()))
@@ -75,14 +73,28 @@ async fn upsert_user_app(
Json(request): Json<UserAppRequest>,
) -> Result<(StatusCode, Json<UserAppResponse>), AppError> {
let app = request.into_domain(user_id, app_id);
let upsert = repository::user_apps::upsert(&pool, app).await?;
let (status, app) = match upsert {
Upsert::Created(app) => (StatusCode::CREATED, app),
Upsert::Updated(app) => (StatusCode::OK, app),
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let upserted = repository::user_apps::upsert(&mut *tx, app).await?;
if upserted
.previous
.as_ref()
.is_some_and(|previous| previous.user_id != user_id)
{
return Err(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}
.into());
}
tx.commit().await.map_err(RepositoryError::from)?;
let status = if upserted.previous.is_some() {
StatusCode::OK
} else {
StatusCode::CREATED
};
Ok((status, Json(app.into())))
Ok((status, Json(upserted.current.into())))
}
#[axum::debug_handler]
@@ -91,8 +103,14 @@ async fn delete_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
) -> Result<StatusCode, AppError> {
match repository::user_apps::delete_by_id(&pool, user_id, app_id).await? {
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
Delete::NotFound => Err(AppError::NotFound),
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
if repository::user_apps::delete_by_id(&mut *tx, app_id)
.await?
.is_none_or(|user_app| user_app.user_id != user_id)
{
return Err(AppError::NotFound);
}
tx.commit().await.map_err(RepositoryError::from)?;
Ok(StatusCode::NO_CONTENT)
}