1
//! Setting and clearing one tag name of an account or a commodity on the tag
2
//! lock protocol. Each attempt is one DB transaction: the tag keys, then the
3
//! owner row, then the writes. Keys come before the row as in a merge, which
4
//! holds `from`'s keys while it waits for `from`'s row; the touched tags are
5
//! reread under the row lock, and any change makes the attempt retry. Stored
6
//! names match by their trimmed form.
7

            
8
use finance::tag::Tag;
9
use sqlx::{PgConnection, types::Uuid};
10

            
11
use super::lock::{Key, KeyChanged, begin, lock, retry, sorted_keys};
12
use super::user::{delete_tag_if_orphaned, lock_account};
13

            
14
#[derive(Clone, Copy)]
15
pub(crate) enum Owner {
16
    Account,
17
    Commodity,
18
}
19

            
20
impl Owner {
21
110926
    pub(crate) async fn lock_row(self, conn: &mut PgConnection, id: Uuid) -> sqlx::Result<()> {
22
110926
        match self {
23
96486
            Self::Account => lock_account(conn, id).await,
24
            Self::Commodity => {
25
14440
                sqlx::query_file!("sql/select/commodities/by_id_locked.sql", id)
26
14440
                    .fetch_one(conn)
27
14440
                    .await?;
28
12998
                Ok(())
29
            }
30
        }
31
110926
    }
32

            
33
    /// Link `tag` in place of any other value of its name, then drop the
34
    /// detached tag rows nothing references any more.
35
103799
    pub(crate) async fn set(
36
103799
        self,
37
103799
        conn: &mut PgConnection,
38
103799
        id: Uuid,
39
103799
        tag: &Tag,
40
103799
    ) -> sqlx::Result<Result<(), KeyChanged>> {
41
103799
        let (name, value) = tag.normalized();
42
103799
        let mut tx = begin(conn).await?;
43
103799
        let touched = self.lockable_for_set(&mut tx, id, name, value).await?;
44
103799
        if lock(&mut tx, &touched, &[tag]).await?.is_err() {
45
28
            return retry(tx).await;
46
103590
        }
47
103590
        self.lock_row(&mut tx, id).await?;
48
102509
        if self.lockable_for_set(&mut tx, id, name, value).await? != touched {
49
1
            return retry(tx).await;
50
102508
        }
51
102508
        self.write_set(&mut tx, id, tag).await?;
52
102508
        tx.commit().await?;
53
102508
        Ok(Ok(()))
54
103799
    }
55

            
56
    /// Unlink every tag named `name`, then drop the released tag rows nothing
57
    /// references any more.
58
837
    pub(crate) async fn clear(
59
837
        self,
60
837
        conn: &mut PgConnection,
61
837
        id: Uuid,
62
837
        name: &str,
63
837
    ) -> sqlx::Result<Result<(), KeyChanged>> {
64
121
        let mut tx = begin(conn).await?;
65
121
        let released = self.linked_of_name(&mut tx, id, name).await?;
66
121
        if lock(&mut tx, &released, &[]).await?.is_err() {
67
4
            return retry(tx).await;
68
117
        }
69
117
        self.lock_row(&mut tx, id).await?;
70
113
        if self.linked_of_name(&mut tx, id, name).await? != released {
71
            return retry(tx).await;
72
113
        }
73
113
        self.write_clear(&mut tx, id, name, &released).await?;
74
113
        tx.commit().await?;
75
113
        Ok(Ok(()))
76
121
    }
77

            
78
    /// Link `tag` in place of the owner's other values of its name and drop
79
    /// the detached tag rows nothing references any more. The caller holds
80
    /// the locks.
81
488751
    pub(crate) async fn write_set(
82
488751
        self,
83
488751
        conn: &mut PgConnection,
84
488751
        id: Uuid,
85
488751
        tag: &Tag,
86
488751
    ) -> sqlx::Result<()> {
87
488751
        let (name, value) = tag.normalized();
88
488751
        let detached = match self {
89
            Self::Account => {
90
                let rows =
91
94209
                    sqlx::query_file!("sql/set/accounts/tag.sql", id, name, value, tag.description)
92
94209
                        .fetch_all(&mut *conn)
93
94209
                        .await?;
94
94209
                rows.into_iter()
95
2715
                    .map(|row| (row.id, (row.tag_name, row.tag_value)))
96
                    .collect::<Vec<_>>()
97
            }
98
            Self::Commodity => {
99
394542
                let rows = sqlx::query_file!(
100
394542
                    "sql/set/commodities/tag.sql",
101
                    id,
102
                    name,
103
                    value,
104
                    tag.description
105
                )
106
394542
                .fetch_all(&mut *conn)
107
394542
                .await?;
108
394541
                rows.into_iter()
109
1992
                    .map(|row| (row.id, (row.tag_name, row.tag_value)))
110
                    .collect::<Vec<_>>()
111
            }
112
        };
113
488750
        for (tag_id, _) in &sorted_keys(detached.into_iter()) {
114
4707
            delete_tag_if_orphaned(conn, *tag_id).await?;
115
        }
116
488750
        Ok(())
117
488751
    }
118

            
119
    /// Unlink the owner's tags named `name`, the `released` rows, and drop the
120
    /// ones nothing references any more. The caller holds the locks.
121
1917
    pub(crate) async fn write_clear(
122
1917
        self,
123
1917
        conn: &mut PgConnection,
124
1917
        id: Uuid,
125
1917
        name: &str,
126
1917
        released: &[(Uuid, Key)],
127
1917
    ) -> sqlx::Result<()> {
128
445
        match self {
129
            Self::Account => {
130
274
                sqlx::query_file!("sql/delete/account_tags/by_account_and_name.sql", id, name)
131
274
                    .execute(&mut *conn)
132
274
                    .await?
133
            }
134
            Self::Commodity => {
135
171
                sqlx::query_file!(
136
                    "sql/delete/commodity_tags/by_commodity_and_name.sql",
137
                    id,
138
                    name
139
                )
140
171
                .execute(&mut *conn)
141
171
                .await?
142
            }
143
        };
144
445
        for (tag_id, _) in released {
145
445
            delete_tag_if_orphaned(conn, *tag_id).await?;
146
        }
147
445
        Ok(())
148
445
    }
149

            
150
    /// The owner's tags named `name` and the row of `(name, value)`, if stored.
151
206308
    async fn lockable_for_set(
152
206308
        self,
153
206308
        conn: &mut PgConnection,
154
206308
        id: Uuid,
155
206308
        name: &str,
156
206308
        value: &str,
157
206308
    ) -> sqlx::Result<Vec<(Uuid, Key)>> {
158
206308
        let keys = match self {
159
184292
            Self::Account => sqlx::query_file!(
160
184292
                "sql/select/tags/lockable_for_account_set.sql",
161
                id,
162
                name,
163
                value
164
            )
165
184292
            .fetch_all(conn)
166
184292
            .await?
167
            .into_iter()
168
113070
            .map(|row| (row.id, (row.tag_name, row.tag_value)))
169
            .collect::<Vec<_>>(),
170
22016
            Self::Commodity => sqlx::query_file!(
171
22016
                "sql/select/tags/lockable_for_commodity_set.sql",
172
                id,
173
                name,
174
                value
175
            )
176
22016
            .fetch_all(conn)
177
22016
            .await?
178
            .into_iter()
179
1104
            .map(|row| (row.id, (row.tag_name, row.tag_value)))
180
            .collect::<Vec<_>>(),
181
        };
182
206308
        Ok(sorted_keys(keys.into_iter()))
183
206308
    }
184

            
185
    /// The owner's tags named `name`.
186
1308
    async fn linked_of_name(
187
1308
        self,
188
1308
        conn: &mut PgConnection,
189
1308
        id: Uuid,
190
1308
        name: &str,
191
1308
    ) -> sqlx::Result<Vec<(Uuid, Key)>> {
192
234
        let keys = match self {
193
221
            Self::Account => sqlx::query_file!("sql/select/tags/by_account_and_name.sql", id, name)
194
221
                .fetch_all(conn)
195
221
                .await?
196
                .into_iter()
197
216
                .map(|row| (row.id, (row.tag_name, row.tag_value)))
198
                .collect::<Vec<_>>(),
199
            Self::Commodity => {
200
13
                sqlx::query_file!("sql/select/tags/by_commodity_and_name.sql", id, name)
201
13
                    .fetch_all(conn)
202
13
                    .await?
203
                    .into_iter()
204
14
                    .map(|row| (row.id, (row.tag_name, row.tag_value)))
205
                    .collect::<Vec<_>>()
206
            }
207
        };
208
234
        Ok(sorted_keys(keys.into_iter()))
209
234
    }
210
}