1
//! Editing a tag row on the tag lock protocol: its stored key and the new
2
//! key, then the clash check and the row update.
3

            
4
use finance::tag::Tag;
5
use sqlx::{PgConnection, types::Uuid};
6

            
7
use super::db_err;
8
use crate::db::DBError;
9
use crate::error::ServerError;
10
use crate::tag::lock::{KeyChanged, begin, lock};
11
use crate::tag_state::tag_revision;
12

            
13
/// One attempt at storing `tag`'s key and description on the tag `id` in its
14
/// own DB transaction. `KeyChanged` when the tag was renamed before its key
15
/// was locked.
16
///
17
/// # Errors
18
/// A missing tag, [`ServerError::StaleTag`] when `revision` no longer matches
19
/// the locked tag, [`ServerError::TagClash`] when another tag holds the new
20
/// key, or a failing query.
21
2570
pub(super) async fn rename(
22
2570
    conn: &mut PgConnection,
23
2570
    id: Uuid,
24
2570
    revision: &str,
25
2570
    tag: &Tag,
26
2570
) -> Result<Result<(), KeyChanged>, ServerError> {
27
1336
    let mut tx = begin(conn).await.map_err(db_err)?;
28
1336
    let row = sqlx::query_file!("sql/select/tags/by_id.sql", id)
29
1336
        .fetch_one(&mut *tx)
30
1336
        .await
31
1336
        .map_err(row_err)?;
32
1333
    if let Err(changed) = lock(&mut tx, &[(id, (row.tag_name, row.tag_value))], &[tag])
33
1333
        .await
34
1333
        .map_err(db_err)?
35
    {
36
3
        tx.rollback().await.map_err(db_err)?;
37
3
        return Ok(Err(changed));
38
1170
    }
39
1170
    refuse_stale(&mut tx, id, revision).await?;
40
1007
    refuse_clash(&mut tx, id, tag).await?;
41
684
    sqlx::query_file!(
42
        "sql/update/tags/update.sql",
43
        &id,
44
        tag.tag_name,
45
        tag.tag_value,
46
        tag.description.as_deref()
47
    )
48
684
    .execute(&mut *tx)
49
684
    .await
50
684
    .map_err(db_err)?;
51
684
    tx.commit().await.map_err(db_err)?;
52
683
    Ok(Ok(()))
53
1336
}
54

            
55
/// A tag deleted meanwhile is the not-found failure, not a logged DB error.
56
3
fn row_err(err: sqlx::Error) -> ServerError {
57
3
    match err {
58
3
        sqlx::Error::RowNotFound => ServerError::DB(DBError::Sqlx(err)),
59
        other => db_err(other),
60
    }
61
3
}
62

            
63
/// Refuse when the locked tag `id` no longer matches `revision`.
64
2384
async fn refuse_stale(
65
2384
    conn: &mut PgConnection,
66
2384
    id: Uuid,
67
2384
    expected: &str,
68
2384
) -> Result<(), ServerError> {
69
1170
    let current = sqlx::query_file_as!(Tag, "sql/select/tags/by_id.sql", id)
70
1170
        .fetch_one(conn)
71
1170
        .await
72
1170
        .map_err(row_err)?;
73
1170
    match tag_revision(&current) == expected {
74
1007
        true => Ok(()),
75
163
        false => Err(ServerError::StaleTag),
76
    }
77
1170
}
78

            
79
/// Refuse when a tag other than `id` holds `tag`'s key; the key is locked.
80
1843
async fn refuse_clash(conn: &mut PgConnection, id: Uuid, tag: &Tag) -> Result<(), ServerError> {
81
1007
    let holder = sqlx::query_file!(
82
1007
        "sql/select/tags/lock_by_key.sql",
83
        tag.tag_name,
84
        tag.tag_value
85
    )
86
1007
    .fetch_optional(conn)
87
1007
    .await
88
1007
    .map_err(db_err)?;
89
1007
    match holder {
90
330
        Some(row) if row.id != id => Err(ServerError::TagClash {
91
323
            name: tag.tag_name.clone(),
92
323
            value: tag.tag_value.clone(),
93
323
        }),
94
684
        _ => Ok(()),
95
    }
96
1007
}