Lines
98.25 %
Functions
80 %
Branches
100 %
//! Editing a tag row on the tag lock protocol: its stored key and the new
//! key, then the clash check and the row update.
use finance::tag::Tag;
use sqlx::{PgConnection, types::Uuid};
use super::db_err;
use crate::db::DBError;
use crate::error::ServerError;
use crate::tag::lock::{KeyChanged, begin, lock};
use crate::tag_state::tag_revision;
/// One attempt at storing `tag`'s key and description on the tag `id` in its
/// own DB transaction. `KeyChanged` when the tag was renamed before its key
/// was locked.
///
/// # Errors
/// A missing tag, [`ServerError::StaleTag`] when `revision` no longer matches
/// the locked tag, [`ServerError::TagClash`] when another tag holds the new
/// key, or a failing query.
pub(super) async fn rename(
conn: &mut PgConnection,
id: Uuid,
revision: &str,
tag: &Tag,
) -> Result<Result<(), KeyChanged>, ServerError> {
let mut tx = begin(conn).await.map_err(db_err)?;
let row = sqlx::query_file!("sql/select/tags/by_id.sql", id)
.fetch_one(&mut *tx)
.await
.map_err(row_err)?;
if let Err(changed) = lock(&mut tx, &[(id, (row.tag_name, row.tag_value))], &[tag])
.map_err(db_err)?
{
tx.rollback().await.map_err(db_err)?;
return Ok(Err(changed));
}
refuse_stale(&mut tx, id, revision).await?;
refuse_clash(&mut tx, id, tag).await?;
sqlx::query_file!(
"sql/update/tags/update.sql",
&id,
tag.tag_name,
tag.tag_value,
tag.description.as_deref()
)
.execute(&mut *tx)
.map_err(db_err)?;
tx.commit().await.map_err(db_err)?;
Ok(Ok(()))
/// A tag deleted meanwhile is the not-found failure, not a logged DB error.
fn row_err(err: sqlx::Error) -> ServerError {
match err {
sqlx::Error::RowNotFound => ServerError::DB(DBError::Sqlx(err)),
other => db_err(other),
/// Refuse when the locked tag `id` no longer matches `revision`.
async fn refuse_stale(
expected: &str,
) -> Result<(), ServerError> {
let current = sqlx::query_file_as!(Tag, "sql/select/tags/by_id.sql", id)
.fetch_one(conn)
match tag_revision(¤t) == expected {
true => Ok(()),
false => Err(ServerError::StaleTag),
/// Refuse when a tag other than `id` holds `tag`'s key; the key is locked.
async fn refuse_clash(conn: &mut PgConnection, id: Uuid, tag: &Tag) -> Result<(), ServerError> {
let holder = sqlx::query_file!(
"sql/select/tags/lock_by_key.sql",
tag.tag_value
.fetch_optional(conn)
match holder {
Some(row) if row.id != id => Err(ServerError::TagClash {
name: tag.tag_name.clone(),
value: tag.tag_value.clone(),
}),
_ => Ok(()),