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

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