Lines
100 %
Functions
52.38 %
Branches
//! `ReparentAccount`: move an account under another parent, or to the root,
//! under the hierarchy lock, then the account rows.
use crate::command::connection;
use finance::account::Account;
use sqlx::{PgConnection, types::Uuid};
use supp_macro::command;
use super::{CmdError, CmdResult, FinanceEntity};
use crate::{hierarchy::lock_hierarchy, user::User};
command! {
ReparentAccount {
#[required]
user_id: Uuid,
account_id: Uuid,
#[optional]
parent: Uuid,
} => {
let user = User { id: user_id };
let mut conn = connection(&user).await?;
reparent(&mut conn, user_id, account_id, parent).await?;
Ok(Some(CmdResult::Entity(FinanceEntity::Account(Account {
id: account_id,
parent,
}))))
}
/// The refusal of a move under the account itself or one of its descendants.
pub const CYCLE_REFUSED: &str =
"An account cannot be moved under itself or one of its own sub-accounts";
async fn reparent(
conn: &mut PgConnection,
parent: Option<Uuid>,
) -> Result<(), CmdError> {
let mut tx = crate::tag::lock::begin(conn).await?;
lock_hierarchy(&mut tx, user_id).await?;
move_account(&mut tx, account_id, parent).await?;
tx.commit().await?;
Ok(())
/// Move the account under `parent` (or to the root); the caller holds the
/// hierarchy lock.
pub(super) async fn move_account(
lock_rows(conn, account_id, parent).await?;
if let Some(parent) = parent {
refuse_cycle(conn, account_id, parent).await?;
sqlx::query_file!("sql/update/accounts/set_parent.sql", account_id, parent)
.execute(conn)
.await?;
/// Lock the account and its new parent in id order.
async fn lock_rows(
let mut ids: Vec<Uuid> = std::iter::once(account_id).chain(parent).collect();
ids.sort();
for id in ids {
let row = sqlx::query_file!("sql/select/accounts/by_id_locked.sql", id)
.fetch_optional(&mut *conn)
if row.is_none() {
return Err(CmdError::NotFound(format!("Account {id} not found")));
async fn refuse_cycle(
let cyclic = parent == account_id
|| sqlx::query_file!("sql/select/accounts/is_descendant.sql", parent, account_id)
.fetch_one(conn)
.await?
.is_descendant
.unwrap_or(false);
match cyclic {
true => Err(CmdError::Refused(CYCLE_REFUSED.to_string())),
false => Ok(()),