Lines
98.08 %
Functions
7.35 %
Branches
100 %
//! `EditCommodity`: replace the symbol, the name and the other tags of a
//! commodity in one DB transaction. Lock order: the tag keys, then the
//! commodity row; a commodity has no hierarchy. The revision is checked under
//! the locks.
use crate::command::connection;
use finance::commodity::Commodity;
use finance::tag::Tag;
use sqlx::{PgConnection, types::Uuid};
use supp_macro::command;
use super::attempt::{Attempt, found, missing};
use super::commodity_tag::{IDENTITY_TAGS, not_found};
use super::tag_replace::{identities, lock_keys, replace_tags, wanted_tags};
use super::{CmdError, CmdResult, FinanceEntity};
use crate::attempt::Tries;
use crate::commodity_state::{STALE_COMMODITY, read_commodity};
use crate::tag::lock::begin;
use crate::tag::owned::Owner;
use crate::user::User;
command! {
EditCommodity {
#[required]
user_id: Uuid,
commodity_id: Uuid,
symbol: String,
name: String,
tags: Vec<Tag>,
revision: String,
} => {
let wanted = commodity_wanted(&symbol, &name, tags)?;
let user = User { id: user_id };
let mut conn = connection(&user).await?;
let mut tries = Tries::default();
while tries
.step(edit_once(&mut conn, commodity_id, &wanted, &revision).await)?
.is_none()
{}
Ok(Some(CmdResult::Entity(FinanceEntity::Commodity(Commodity {
id: commodity_id,
}))))
}
fn identity_tag(name: &str, value: &str) -> Tag {
Tag {
id: Uuid::new_v4(),
tag_name: name.to_string(),
tag_value: value.to_string(),
description: None,
/// The tags the commodity ends up with: the `symbol` and `name` tags and the
/// given ones.
fn commodity_wanted(symbol: &str, name: &str, tags: Vec<Tag>) -> Result<Vec<Tag>, CmdError> {
let fixed: Vec<Tag> = IDENTITY_TAGS
.into_iter()
.zip([symbol, name])
.map(|(tag_name, value)| identity_tag(tag_name, value))
.collect();
match fixed.iter().find(|tag| tag.is_blank()) {
Some(blank) => Err(CmdError::Args(format!(
"The commodity {} must not be blank",
blank.tag_name
))),
None => wanted_tags("A commodity", fixed, tags),
async fn edit_once(
conn: &mut PgConnection,
wanted: &[Tag],
revision: &str,
) -> Result<(), Attempt> {
let mut tx = begin(conn).await?;
let before = found(read_commodity(&mut tx, commodity_id).await?, not_found)?;
lock_keys(&mut tx, &before.tags, wanted).await?;
Owner::Commodity
.lock_row(&mut tx, commodity_id)
.await
.map_err(|err| missing(err, not_found))?;
let stored = found(read_commodity(&mut tx, commodity_id).await?, not_found)?;
if identities(&stored.tags) != identities(&before.tags) {
return Err(Attempt::Retry);
if stored.revision() != revision {
return Err(CmdError::Args(STALE_COMMODITY.to_string()).into());
replace_tags(
&mut tx,
Owner::Commodity,
commodity_id,
&stored.tags,
wanted,
)
.await?;
tx.commit().await?;
Ok(())