Lines
90.51 %
Functions
72.94 %
Branches
100 %
pub(crate) mod artifact;
pub(crate) mod lock;
pub(crate) mod owned;
pub mod user {
use crate::attempt::{Attempt, Tries};
use crate::error::ServerError;
use crate::tag::lock;
use crate::user::User;
use finance::tag::{Tag, normalize};
use sqlx::types::Uuid;
/// Which join table to scope `list_tag_names` / `list_tag_values_for` to.
#[derive(Debug, Clone, Copy)]
pub enum TagScope {
Transaction,
Account,
Commodity,
Split,
}
fn db_err(err: sqlx::Error) -> ServerError {
tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
ServerError::DB(crate::db::DBError::Sqlx(err))
pub(crate) mod links;
mod owner;
mod remove;
mod rename;
use owner::TagOwner;
pub(crate) async fn lock_account(
conn: &mut sqlx::PgConnection,
account_id: Uuid,
) -> Result<(), sqlx::Error> {
sqlx::query_file!("sql/select/accounts/by_id_locked.sql", account_id)
.fetch_one(conn)
.await?;
Ok(())
fn new_tag(
name: String,
value: String,
description: Option<String>,
) -> Result<Tag, ServerError> {
let (tag_name, tag_value) = normalize(&name, &value);
if tag_name.is_empty() || tag_value.is_empty() {
return Err(ServerError::Creation);
Ok(Tag {
id: Uuid::new_v4(),
tag_name: tag_name.to_string(),
tag_value: tag_value.to_string(),
description: description.filter(|text| !text.is_empty()),
})
/// Lock the tag row, then delete it if nothing references it. The lock
/// makes a concurrent writer that links the tag finish before the check.
pub(crate) async fn delete_tag_if_orphaned(
tag_id: Uuid,
sqlx::query_file!("sql/select/tags/lock_by_id.sql", tag_id)
.fetch_optional(&mut *conn)
let is_orphaned = sqlx::query_file!("sql/check/tags/is_orphaned.sql", tag_id)
.fetch_one(&mut *conn)
.await?
.is_orphaned
.unwrap_or(false);
if is_orphaned {
sqlx::query_file!("sql/delete/tags/by_id.sql", tag_id)
.execute(&mut *conn)
impl User {
pub async fn create_tag(
&self,
) -> Result<Uuid, ServerError> {
let tag = new_tag(name, value, description)?;
let mut conn = self.get_connection().await.map_err(|err| {
ServerError::DB(err)
})?;
tag.commit(&mut *conn).await.map_err(|err| {
ServerError::Finance(err)
pub async fn list_tags(&self) -> Result<Vec<Tag>, ServerError> {
let mut conn = self.get_connection().await?;
let tags = sqlx::query_file_as!(Tag, "sql/select/tags/all.sql")
.fetch_all(&mut *conn)
.await
.map_err(|err| {
Ok(tags)
/// Replace the tag, refusing with [`ServerError::StaleTag`] when it no
/// longer matches `revision`, checked under the key lock.
pub async fn update_tag(
id: Uuid,
revision: &str,
) -> Result<(), ServerError> {
let mut tries = Tries::default();
while tries
.step(Attempt::of(
rename::rename(&mut conn, id, revision, &tag).await,
ServerError::is_retryable,
std::convert::identity,
))?
.is_none()
{}
pub async fn get_transaction_tags(&self, tx_id: Uuid) -> Result<Vec<Tag>, ServerError> {
let tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &tx_id)
/// Upsert the tag and link it to the transaction in one DB
/// transaction, owner locked first.
pub async fn create_transaction_tag(
tx_id: Uuid,
self.attach_tag(TagOwner::Transaction(tx_id), name, value, description)
async fn attach_tag(
owner: TagOwner,
owner::write(&mut conn, owner, &tag, owner::attach).await
/// Cascade-delete a tag: detach from every join table, then drop the
/// row from `tags`, under its key lock. Used by user-initiated tag
/// deletion in the UI.
///
/// # Errors
/// A failing write, or [`crate::db::DBError::WriteConflict`] when the
/// tag was renamed during every attempt.
/// Whether the tag existed.
pub async fn delete_tag(&self, id: Uuid) -> Result<bool, ServerError> {
loop {
let attempt = Attempt::of(
remove::remove(&mut conn, id).await,
lock::is_retryable,
db_err,
);
if let Some(existed) = tries.step(attempt)? {
return Ok(existed);
pub async fn list_tag_names(&self, scope: TagScope) -> Result<Vec<String>, ServerError> {
let result = match scope {
TagScope::Transaction => sqlx::query_file!("sql/select/tags/transaction/names.sql")
.map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
TagScope::Account => sqlx::query_file!("sql/select/tags/account/names.sql")
TagScope::Commodity => sqlx::query_file!("sql/select/tags/commodity/names.sql")
TagScope::Split => sqlx::query_file!("sql/select/tags/split/names.sql")
};
result.map_err(|err| {
pub async fn list_tag_values_for(
scope: TagScope,
tag_name: &str,
) -> Result<Vec<String>, ServerError> {
TagScope::Transaction => {
sqlx::query_file!("sql/select/tags/transaction/values_by_name.sql", tag_name)
.map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
TagScope::Account => {
sqlx::query_file!("sql/select/tags/account/values_by_name.sql", tag_name)
TagScope::Commodity => {
sqlx::query_file!("sql/select/tags/commodity/values_by_name.sql", tag_name)
TagScope::Split => {
sqlx::query_file!("sql/select/tags/split/values_by_name.sql", tag_name)
pub async fn list_transaction_tag_names(&self) -> Result<Vec<String>, ServerError> {
self.list_tag_names(TagScope::Transaction).await
pub async fn list_transaction_tag_values(
self.list_tag_values_for(TagScope::Transaction, tag_name)
/// Split counterpart of `create_transaction_tag`; locks the split's
/// owning transaction.
pub async fn create_split_tag(
split_id: Uuid,
self.attach_tag(TagOwner::Split(split_id), name, value, description)
/// Upsert-style set: replace any existing (split, tag_name) link with
/// the (tag_name, tag_value) pair from `t`. Mirrors `set_account_tag`
/// — script-friendly idempotent set semantics.
pub async fn set_split_tag(&self, split_id: Uuid, t: &Tag) -> Result<(), ServerError> {
owner::write(&mut conn, TagOwner::Split(split_id), t, owner::set).await
/// Companion to `set_split_tag` for transactions.
pub async fn set_transaction_tag(&self, tx_id: Uuid, t: &Tag) -> Result<(), ServerError> {
owner::write(&mut conn, TagOwner::Transaction(tx_id), t, owner::set).await
/// Read all tags attached to a single split. Parallel to
/// `get_transaction_tags`; the script-side `get-split-tag` native
/// looks up by name in the returned vec.
pub async fn get_split_tags(&self, split_id: Uuid) -> Result<Vec<Tag>, ServerError> {
let tags = crate::split::tags_of_split(&mut conn, split_id)
pub async fn list_account_tag_names(&self) -> Result<Vec<String>, ServerError> {
self.list_tag_names(TagScope::Account).await
pub async fn list_account_tag_values(
self.list_tag_values_for(TagScope::Account, tag_name).await
pub async fn list_commodity_tag_names(&self) -> Result<Vec<String>, ServerError> {
self.list_tag_names(TagScope::Commodity).await
pub async fn list_commodity_tag_values(
self.list_tag_values_for(TagScope::Commodity, tag_name)
pub async fn list_split_tag_names(&self) -> Result<Vec<String>, ServerError> {
self.list_tag_names(TagScope::Split).await
pub async fn list_split_tag_values(
self.list_tag_values_for(TagScope::Split, tag_name).await
#[cfg(test)]
mod tag_tests;
mod test_support;