Perform last member removal check on the database.
This commit is contained in:
-41
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n\t\tSELECT id, name\n\t\tFROM accounts\n\t\tWHERE id IN (SELECT id FROM accessible_accounts($1))\n AND id = $2\n\t\tFOR NO KEY UPDATE\n\t\t",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "accounts",
|
||||
"name": "id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "name",
|
||||
"type_info": "Text",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "accounts",
|
||||
"name": "name"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "a4f47fa48d44b0239289b75d1f5adac86afc0498ca2e27562557f505cd96b2bf"
|
||||
}
|
||||
@@ -4,4 +4,29 @@ CREATE TABLE account_members (
|
||||
user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id),
|
||||
PRIMARY KEY (id, account_id),
|
||||
CONSTRAINT uq_account_members_account_user UNIQUE (account_id, user_id)
|
||||
);
|
||||
);
|
||||
|
||||
CREATE FUNCTION ensure_account_has_member () RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
-- Serialises concurrent removals for the same account. Without the lock, two transactions
|
||||
-- removing different members of a two-member account would each still see the other's row.
|
||||
-- No row is found when the account itself is being deleted (cascade), which is allowed.
|
||||
PERFORM 1 FROM accounts WHERE id = OLD.account_id FOR NO KEY UPDATE;
|
||||
|
||||
IF FOUND AND NOT EXISTS (
|
||||
SELECT 1 FROM account_members WHERE account_id = OLD.account_id
|
||||
) THEN
|
||||
RAISE EXCEPTION 'account must have at least one member'
|
||||
USING ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'ck_account_members_last_member';
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END
|
||||
$$;
|
||||
|
||||
CREATE CONSTRAINT TRIGGER ck_account_members_last_member
|
||||
AFTER DELETE OR UPDATE OF account_id ON account_members
|
||||
DEFERRABLE INITIALLY IMMEDIATE
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION ensure_account_has_member ();
|
||||
|
||||
+25
-1
@@ -9,10 +9,17 @@ pub mod user_app_secrets;
|
||||
pub mod user_apps;
|
||||
pub mod users;
|
||||
|
||||
use error_codes::{PG_FOREIGN_KEY_VIOLATION, PG_UNIQUE_VIOLATION};
|
||||
use error_codes::{PG_CHECK_VIOLATION, PG_FOREIGN_KEY_VIOLATION, PG_UNIQUE_VIOLATION};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DatabaseError {
|
||||
#[error("check violation ({constraint}): {source}")]
|
||||
CheckViolation {
|
||||
constraint: Constraint,
|
||||
#[source]
|
||||
source: sqlx::Error,
|
||||
},
|
||||
|
||||
#[error("foreign key violation ({constraint}): {source}")]
|
||||
ForeignKeyViolation {
|
||||
constraint: Constraint,
|
||||
@@ -34,6 +41,19 @@ pub enum DatabaseError {
|
||||
impl From<sqlx::Error> for DatabaseError {
|
||||
fn from(err: sqlx::Error) -> Self {
|
||||
match err {
|
||||
sqlx::Error::Database(db_err)
|
||||
if db_err.code().as_deref() == Some(PG_CHECK_VIOLATION) =>
|
||||
{
|
||||
let constraint = db_err
|
||||
.constraint()
|
||||
.map(Constraint::from)
|
||||
.unwrap_or(Constraint::Unnamed);
|
||||
|
||||
DatabaseError::CheckViolation {
|
||||
constraint,
|
||||
source: sqlx::Error::Database(db_err),
|
||||
}
|
||||
}
|
||||
sqlx::Error::Database(db_err)
|
||||
if db_err.code().as_deref() == Some(PG_FOREIGN_KEY_VIOLATION) =>
|
||||
{
|
||||
@@ -76,6 +96,9 @@ pub enum Constraint {
|
||||
#[error("account member user constraint")]
|
||||
AccountMemberUser,
|
||||
|
||||
#[error("account member last member constraint")]
|
||||
AccountMemberLastMember,
|
||||
|
||||
#[error("user app user constraint")]
|
||||
UserAppUser,
|
||||
|
||||
@@ -101,6 +124,7 @@ impl From<&str> for Constraint {
|
||||
"fk_account_members_account" => Constraint::AccountMemberAccount,
|
||||
"uq_account_members_account_user" => Constraint::AccountMemberAccountUser,
|
||||
"fk_account_members_user" => Constraint::AccountMemberUser,
|
||||
"ck_account_members_last_member" => Constraint::AccountMemberLastMember,
|
||||
"fk_user_apps_user" => Constraint::UserAppUser,
|
||||
"fk_user_app_secrets_app" => Constraint::UserAppSecretApp,
|
||||
"fk_transactions_account" => Constraint::TransactionAccount,
|
||||
|
||||
@@ -62,34 +62,6 @@ where
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
/// Like [`get_by_id`], but also locks the account row until the end of the transaction, so the
|
||||
/// executor must be a transaction. Callers locking the same account are serialized, while
|
||||
/// inserting members into the account is not blocked.
|
||||
pub async fn get_by_id_locking<'e, E>(
|
||||
executor: E,
|
||||
user_id: Uuid,
|
||||
id: Uuid,
|
||||
) -> Result<Option<AccountRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
AccountRow,
|
||||
r#"
|
||||
SELECT id, name
|
||||
FROM accounts
|
||||
WHERE id IN (SELECT id FROM accessible_accounts($1))
|
||||
AND id = $2
|
||||
FOR NO KEY UPDATE
|
||||
"#,
|
||||
user_id,
|
||||
id,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn get_by_ids<'e, E>(
|
||||
executor: E,
|
||||
user_id: Uuid,
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub const PG_CHECK_VIOLATION: &str = "23514";
|
||||
pub const PG_FOREIGN_KEY_VIOLATION: &str = "23503";
|
||||
pub const PG_UNIQUE_VIOLATION: &str = "23505";
|
||||
|
||||
@@ -20,9 +20,6 @@ pub enum AppError {
|
||||
#[error("transaction id already exists")]
|
||||
TransactionIdAlreadyExists,
|
||||
|
||||
#[error("cannot remove the last member of an account")]
|
||||
LastAccountMemberRemoval,
|
||||
|
||||
#[error("invalid client credentials")]
|
||||
InvalidClientCredentials,
|
||||
|
||||
|
||||
@@ -102,6 +102,9 @@ pub enum ReferenceViolationKind {
|
||||
|
||||
#[error("still referenced")]
|
||||
StillReferenced,
|
||||
|
||||
#[error("last remaining")]
|
||||
LastRemaining,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -134,13 +134,28 @@ where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let member = db::delete_by_id(executor, user_id, account_id, id)
|
||||
.await?
|
||||
.await
|
||||
.map_err(classify_delete_error)?
|
||||
.map(decode)
|
||||
.transpose()?;
|
||||
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
||||
match &error {
|
||||
DatabaseError::CheckViolation {
|
||||
constraint: Constraint::AccountMemberLastMember,
|
||||
..
|
||||
} => RepositoryError::ReferenceViolation {
|
||||
relation: ReferenceRelation::AccountMember,
|
||||
kind: ReferenceViolationKind::LastRemaining,
|
||||
source: error,
|
||||
},
|
||||
_ => RepositoryError::Database(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(row: AccountMemberRow) -> Result<AccountMember, DecodeError> {
|
||||
Ok(AccountMember {
|
||||
id: row.id,
|
||||
@@ -232,6 +247,31 @@ mod tests {
|
||||
assert!(matches!(error, RepositoryError::Database(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_account_member_delete_last_member_check_violation() {
|
||||
let error = classify_delete_error(DatabaseError::CheckViolation {
|
||||
constraint: Constraint::AccountMemberLastMember,
|
||||
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||
});
|
||||
assert!(matches!(
|
||||
error,
|
||||
RepositoryError::ReferenceViolation {
|
||||
relation: ReferenceRelation::AccountMember,
|
||||
kind: ReferenceViolationKind::LastRemaining,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_unknown_delete_check_violations_generic() {
|
||||
let error = classify_delete_error(DatabaseError::CheckViolation {
|
||||
constraint: Constraint::Unnamed,
|
||||
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||
});
|
||||
assert!(matches!(error, RepositoryError::Database(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_valid_rows() {
|
||||
let row = row();
|
||||
|
||||
@@ -62,22 +62,6 @@ where
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
pub async fn get_by_id_locking<'e, E>(
|
||||
executor: E,
|
||||
user_id: Uuid,
|
||||
id: Uuid,
|
||||
) -> Result<Option<Account>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let account = db::get_by_id_locking(executor, user_id, id)
|
||||
.await?
|
||||
.map(decode)
|
||||
.transpose()?;
|
||||
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
pub async fn get_by_ids<'e, E>(
|
||||
executor: E,
|
||||
user_id: Uuid,
|
||||
|
||||
@@ -9,11 +9,7 @@ use super::{
|
||||
dtos::account_member::{AccountMemberRequest, AccountMemberResponse},
|
||||
extractors::{Auth, Json, Path, Query},
|
||||
};
|
||||
use crate::{
|
||||
domain,
|
||||
error::AppError,
|
||||
repository::{self, RepositoryError},
|
||||
};
|
||||
use crate::{domain, error::AppError, repository};
|
||||
|
||||
pub fn create_router() -> axum::Router<crate::state::AppState> {
|
||||
axum::Router::new()
|
||||
@@ -124,32 +120,10 @@ async fn delete_account_member(
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let user_id = auth.user_id();
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
|
||||
repository::accounts::get_by_id_locking(&mut *tx, user_id, account_id)
|
||||
repository::account_members::delete_by_id(&pool, user_id, account_id, member_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
let members_query = repository::account_members::Query {
|
||||
limit: Some(2),
|
||||
offset: None,
|
||||
};
|
||||
|
||||
let members =
|
||||
repository::account_members::list(&mut *tx, user_id, account_id, members_query).await?;
|
||||
if let [only] = members.as_slice()
|
||||
&& only.id == member_id
|
||||
{
|
||||
return Err(AppError::LastAccountMemberRemoval);
|
||||
}
|
||||
|
||||
let deleted =
|
||||
repository::account_members::delete_by_id(&mut *tx, user_id, account_id, member_id).await?;
|
||||
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
deleted.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,6 @@ impl ClientError for AppError {
|
||||
Self::TransactionIdAlreadyExists => {
|
||||
(StatusCode::CONFLICT, "Transaction ID already exists".into())
|
||||
}
|
||||
Self::LastAccountMemberRemoval => (
|
||||
StatusCode::CONFLICT,
|
||||
"Cannot remove the last member of an account".into(),
|
||||
),
|
||||
Self::InvalidClientCredentials => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid client credentials".into(),
|
||||
@@ -157,6 +153,10 @@ impl ClientError for RepositoryError {
|
||||
StatusCode::CONFLICT,
|
||||
"Still referenced by one or more transactions".into(),
|
||||
),
|
||||
(Kind::LastRemaining, Relation::AccountMember) => (
|
||||
StatusCode::CONFLICT,
|
||||
"Cannot remove the last member of an account".into(),
|
||||
),
|
||||
_ => internal_error(),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user