Lines
99.59 %
Functions
86.36 %
Branches
100 %
//! Tag handling for `UpdateTransaction`, run inside the command's DB transaction.
use std::collections::{BTreeMap, HashMap, HashSet};
use finance::price::Price;
use finance::split::Split;
use finance::tag::{Tag, insert_split_tags};
use sqlx::PgConnection;
use uuid::Uuid;
use super::tag_replace::unchanged;
use super::{CmdError, FinanceEntity};
use crate::logical::is_note;
use crate::split::split_tags_of;
use crate::tag::lock::{Key, KeyChanged};
/// Reject non-tag entities, blank tags and `note` entries in `tags`.
pub(super) fn validate_edit_tags(
tags: Option<&HashMap<String, FinanceEntity>>,
split_tags: Option<&[(Uuid, Tag)]>,
) -> Result<(), CmdError> {
for entity in tags.into_iter().flat_map(HashMap::values) {
let FinanceEntity::Tag(tag) = entity else {
return Err(CmdError::Args("Invalid entity type in tags".to_string()));
};
if is_note(tag) {
return Err(CmdError::Args(
"The note tag can only be changed with the note argument".to_string(),
));
}
if tag.is_blank() {
"Tag name and value must not be blank".to_string(),
let split_tags = split_tags.unwrap_or_default();
if split_tags.iter().any(|(_, tag)| tag.is_blank()) {
let mut seen: HashMap<(Uuid, &str), &Tag> = HashMap::new();
let conflicting = split_tags.iter().any(|(split, tag)| {
seen.insert((*split, tag.normalized().0), tag)
.is_some_and(|prev| {
(prev.normalized().1, &prev.description) != (tag.normalized().1, &tag.description)
})
});
if conflicting {
"A split cannot carry two tags with the same name".to_string(),
Ok(())
/// Every tag row the edit writes: transaction tags, split tags and the note.
fn written_tags<'a>(
tags: Option<&'a HashMap<String, FinanceEntity>>,
split_tags: Option<&'a [(Uuid, Tag)]>,
note_tag: Option<&'a Tag>,
) -> Vec<&'a Tag> {
let transaction_tags = tags
.into_iter()
.flat_map(HashMap::values)
.filter_map(|e| match e {
FinanceEntity::Tag(tag) => Some(tag),
_ => None,
let split_tags = split_tags.unwrap_or_default().iter().map(|(_, tag)| tag);
transaction_tags.chain(split_tags).chain(note_tag).collect()
fn written_note(note: Option<&str>) -> Option<Tag> {
note.filter(|n| !n.trim().is_empty()).map(note_tag)
/// Lock, until commit, every tag the edit reads for its revision or writes;
/// returns the ids of the tags linked before the edit.
pub(super) async fn lock_edit_tags(
conn: &mut PgConnection,
transaction_id: Uuid,
note: Option<&str>,
) -> Result<Result<Vec<Uuid>, KeyChanged>, sqlx::Error> {
let note_tag = written_note(note);
let written = written_tags(tags, split_tags, note_tag.as_ref());
lock_tag_keys(conn, transaction_id, &written).await
/// Lock, until commit, every tag linked to the transaction or its splits and
/// every tag in `written` through the tag lock protocol, so a concurrent
/// writer of a shared tag either commits before the revision is recomputed or
/// waits. Returns the ids of the linked tags.
pub(crate) async fn lock_tag_keys(
written: &[&Tag],
let linked = linked_tags(conn, transaction_id).await?;
Ok(crate::tag::lock::lock(conn, &linked, written)
.await?
.map(|()| linked.into_iter().map(|(id, _)| id).collect()))
/// The id and stored key of every tag the transaction or its splits link.
pub(crate) async fn linked_tags(
) -> Result<Vec<(Uuid, Key)>, sqlx::Error> {
Ok(sqlx::query_file!(
"sql/select/tags/by_transaction_and_splits.sql",
transaction_id
)
.fetch_all(conn)
.map(|row| (row.tag_id, (row.tag_name, row.tag_value)))
.collect())
pub(super) fn note_tag(value: &str) -> Tag {
Tag {
id: Uuid::new_v4(),
tag_name: "note".to_string(),
tag_value: value.to_string(),
description: None,
async fn unlink_tag(
tag_id: Uuid,
sqlx::query_file!(
"sql/delete/transaction_tags/by_pair.sql",
&transaction_id,
&tag_id
.execute(conn)
.await?;
/// Unlink the transaction's note tags (`notes`) or all its other tags.
pub(super) async fn unlink_tags(
notes: bool,
let linked = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &transaction_id)
.fetch_all(&mut *conn)
for tag in linked.iter().filter(|tag| is_note(tag) == notes) {
unlink_tag(conn, transaction_id, tag.id).await?;
/// Replace all non-note transaction tags with `tags`. A stored link that
/// already holds the wanted tag stays as it is; only the others are unlinked
/// and upserted. The caller deletes the tag rows this leaves unreferenced.
pub(super) async fn replace_transaction_tags(
tags: &HashMap<String, FinanceEntity>,
let stored = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &transaction_id)
let mut held: BTreeMap<&str, Vec<&Tag>> = BTreeMap::new();
for tag in stored.iter().filter(|tag| !is_note(tag)) {
held.entry(tag.normalized().0).or_default().push(tag);
let mut changed: Vec<&Tag> = Vec::new();
for entity in tags.values() {
match held.remove(tag.normalized().0) {
Some(same) if unchanged(&same, tag) => {}
Some(other) => {
for stale in other {
unlink_tag(conn, transaction_id, stale.id).await?;
changed.push(tag);
None => changed.push(tag),
for stale in held.into_values().flatten() {
for tag in changed {
let tag_id = tag.commit(&mut *conn).await?;
"sql/insert/transaction_tags/transaction_tag.sql",
transaction_id,
tag_id
.execute(&mut *conn)
/// The split tags linked to the transaction's splits, with their split ids.
pub(super) async fn stored_split_tags(
) -> Result<Vec<(Uuid, Tag)>, CmdError> {
"sql/select/tags/split_links_by_transaction.sql",
.map(|row| {
let tag = Tag {
id: row.id,
tag_name: row.tag_name,
tag_value: row.tag_value,
description: row.description,
(row.split_id, tag)
/// Attach `split_tags` to the transaction's current splits.
/// The splits are new, so a `stored` split tag (of any old split) that already
/// holds the wanted tag is relinked as it is, without touching the shared row.
pub(super) async fn add_split_tags(
split_tags: &[(Uuid, Tag)],
stored: &[(Uuid, Tag)],
let split_ids: HashSet<Uuid> =
sqlx::query_file!("sql/select/splits/by_transaction.sql", transaction_id)
.map(|row| row.id)
.collect();
if split_tags.iter().any(|(id, _)| !split_ids.contains(id)) {
"Split tag references a split that is not part of this transaction".to_string(),
let mut changed: Vec<(Uuid, Tag)> = Vec::new();
for (split_id, tag) in split_tags {
let mut held: Vec<&Tag> = stored
.iter()
.map(|(_, held)| held)
.filter(|held| held.normalized() == tag.normalized())
held.dedup_by_key(|held| held.id);
match (unchanged(&held, tag), held.first()) {
(true, Some(same)) => {
sqlx::query_file!("sql/insert/split_tags/split_tag.sql", split_id, same.id)
_ => changed.push((*split_id, tag.clone())),
insert_split_tags(conn, &changed).await?;
/// The locked transaction as stored: the data its revision digests.
pub(crate) struct StoredState {
pub(crate) revision: String,
pub(crate) tags: Vec<Tag>,
pub(crate) splits: Vec<Split>,
pub(crate) split_tags: HashMap<Uuid, Vec<Tag>>,
pub(crate) prices: Vec<Price>,
impl StoredState {
/// `Unkeepable` with the reason when the logical form cannot keep the transaction.
pub(crate) fn ensure_keepable(&self) -> Result<(), CmdError> {
crate::logical::form_refusal(&self.tags, &self.splits, &self.split_tags, &self.prices)
.map_err(CmdError::Unkeepable)
/// The locked transaction's stored data with its revision: the note as
/// `GetTransactionDetail` presents it, every other transaction tag and every
/// split tag.
pub(crate) async fn stored_state(
post_date: chrono::DateTime<chrono::Utc>,
) -> Result<StoredState, sqlx::Error> {
let tags: Vec<Tag> =
sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", transaction_id)
let splits: Vec<Split> = sqlx::query_file_as!(
Split,
"sql/select/splits/by_transaction.sql",
let split_tags = split_tags_of(&mut *conn, &splits).await?;
let prices = transaction_prices(conn, transaction_id).await?;
let revision =
crate::logical::stored_revision(post_date, tags.clone(), &splits, &split_tags, &prices);
Ok(StoredState {
revision,
tags,
splits,
split_tags,
prices,
/// The revision of the locked transaction.
pub(crate) async fn current_revision(
) -> Result<String, sqlx::Error> {
Ok(stored_state(conn, transaction_id, post_date)
.revision)
/// The prices of the transaction's splits.
pub(crate) async fn transaction_prices(
) -> Result<Vec<Price>, sqlx::Error> {
Ok(
sqlx::query_file!("sql/select/prices/by_transaction.sql", transaction_id)
.map(|row| Price {
date: row.price_date,
commodity_id: row.commodity_id,
currency_id: row.currency_id,
commodity_split: row.commodity_split_id,
currency_split: row.currency_split_id,
value_num: row.value_num,
value_denom: row.value_denom,
.collect(),