Lines
98.57 %
Functions
89.29 %
Branches
100 %
//! The tag replacement an edit command shares across owners: the wanted tags,
//! the key locks and the writes of the difference.
use std::collections::{BTreeMap, HashSet};
use finance::tag::Tag;
use sqlx::{PgConnection, types::Uuid};
use super::CmdError;
use super::attempt::Attempt;
use crate::tag::lock::{Key, lock};
use crate::tag::owned::Owner;
pub(super) fn args(reason: &str) -> CmdError {
CmdError::Args(reason.to_string())
}
/// The `fixed` tags followed by the given ones, none blank, none named like a
/// fixed one, one value per name; `subject` opens the duplicate message.
pub(super) fn wanted_tags(
subject: &str,
fixed: Vec<Tag>,
tags: Vec<Tag>,
) -> Result<Vec<Tag>, CmdError> {
let fixed_names: Vec<String> = fixed
.iter()
.map(|tag| tag.normalized().0.to_string())
.collect();
let mut seen = HashSet::new();
let mut wanted = fixed;
for tag in tags {
let name = tag.normalized().0.to_string();
let blank = tag.is_blank();
let first = seen.insert(name.clone());
match (blank, first, fixed_names.contains(&name)) {
(true, ..) => return Err(args("Tag name and value must not be blank")),
(_, _, true) => {
return Err(CmdError::Args(format!(
"The {name} tag is edited in the {name} field"
)));
(_, false, _) => {
"{subject} carries one value per tag name"
_ => wanted.push(tag),
Ok(wanted)
pub(super) fn keys(tags: &[Tag]) -> Vec<(Uuid, Key)> {
tags.iter()
.map(|tag| (tag.id, (tag.tag_name.clone(), tag.tag_value.clone())))
.collect()
pub(super) fn identities(tags: &[Tag]) -> Vec<(Uuid, &str, &str)> {
.map(|tag| (tag.id, tag.tag_name.as_str(), tag.tag_value.as_str()))
/// Lock the keys of the stored and the wanted tags.
pub(super) async fn lock_keys(
conn: &mut PgConnection,
stored: &[Tag],
wanted: &[Tag],
) -> Result<(), Attempt> {
let destinations: Vec<&Tag> = wanted.iter().collect();
match lock(conn, &keys(stored), &destinations).await? {
Ok(()) => Ok(()),
Err(_) => Err(Attempt::Retry),
/// Set the wanted tags that differ from the stored ones, clear the stored
/// names that are no longer wanted.
pub(super) async fn replace_tags(
owner: Owner,
id: Uuid,
) -> Result<(), sqlx::Error> {
let mut by_name: BTreeMap<&str, Vec<&Tag>> = BTreeMap::new();
for tag in stored {
by_name.entry(tag.normalized().0).or_default().push(tag);
for tag in wanted {
match by_name.remove(tag.normalized().0) {
Some(held) if unchanged(&held, tag) => {}
_ => owner.write_set(conn, id, tag).await?,
for (name, held) in by_name {
let released: Vec<(Uuid, Key)> = keys(&held.into_iter().cloned().collect::<Vec<_>>());
owner.write_clear(conn, id, name, &released).await?;
Ok(())
/// The owner holds exactly `tag`; a blank description keeps the stored one.
pub(super) fn unchanged(held: &[&Tag], tag: &Tag) -> bool {
matches!(held, [stored]
if stored.normalized().1 == tag.normalized().1
&& (tag.description.is_none() || stored.description == tag.description))