1
pub(crate) mod artifact;
2
pub(crate) mod lock;
3
pub(crate) mod owned;
4

            
5
pub mod user {
6

            
7
    use crate::attempt::{Attempt, Tries};
8
    use crate::error::ServerError;
9
    use crate::tag::lock;
10
    use crate::user::User;
11
    use finance::tag::{Tag, normalize};
12
    use sqlx::types::Uuid;
13

            
14
    /// Which join table to scope `list_tag_names` / `list_tag_values_for` to.
15
    #[derive(Debug, Clone, Copy)]
16
    pub enum TagScope {
17
        Transaction,
18
        Account,
19
        Commodity,
20
        Split,
21
    }
22

            
23
448
    fn db_err(err: sqlx::Error) -> ServerError {
24
448
        tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
25
448
        ServerError::DB(crate::db::DBError::Sqlx(err))
26
448
    }
27

            
28
    pub(crate) mod links;
29
    mod owner;
30
    mod remove;
31
    mod rename;
32

            
33
    use owner::TagOwner;
34

            
35
96486
    pub(crate) async fn lock_account(
36
96486
        conn: &mut sqlx::PgConnection,
37
96486
        account_id: Uuid,
38
96486
    ) -> Result<(), sqlx::Error> {
39
96486
        sqlx::query_file!("sql/select/accounts/by_id_locked.sql", account_id)
40
96486
            .fetch_one(conn)
41
96486
            .await?;
42
96485
        Ok(())
43
96486
    }
44

            
45
83534
    fn new_tag(
46
83534
        name: String,
47
83534
        value: String,
48
83534
        description: Option<String>,
49
83534
    ) -> Result<Tag, ServerError> {
50
83534
        let (tag_name, tag_value) = normalize(&name, &value);
51
83534
        if tag_name.is_empty() || tag_value.is_empty() {
52
4
            return Err(ServerError::Creation);
53
83530
        }
54
        Ok(Tag {
55
83530
            id: Uuid::new_v4(),
56
83530
            tag_name: tag_name.to_string(),
57
83530
            tag_value: tag_value.to_string(),
58
83530
            description: description.filter(|text| !text.is_empty()),
59
        })
60
83534
    }
61

            
62
    /// Lock the tag row, then delete it if nothing references it. The lock
63
    /// makes a concurrent writer that links the tag finish before the check.
64
58312
    pub(crate) async fn delete_tag_if_orphaned(
65
58312
        conn: &mut sqlx::PgConnection,
66
58312
        tag_id: Uuid,
67
58312
    ) -> Result<(), sqlx::Error> {
68
58312
        sqlx::query_file!("sql/select/tags/lock_by_id.sql", tag_id)
69
58312
            .fetch_optional(&mut *conn)
70
58312
            .await?;
71
58312
        let is_orphaned = sqlx::query_file!("sql/check/tags/is_orphaned.sql", tag_id)
72
58312
            .fetch_one(&mut *conn)
73
58312
            .await?
74
            .is_orphaned
75
58312
            .unwrap_or(false);
76
58312
        if is_orphaned {
77
17814
            sqlx::query_file!("sql/delete/tags/by_id.sql", tag_id)
78
17814
                .execute(&mut *conn)
79
17814
                .await?;
80
40498
        }
81
58312
        Ok(())
82
58312
    }
83

            
84
    impl User {
85
6682
        pub async fn create_tag(
86
6682
            &self,
87
6682
            name: String,
88
6682
            value: String,
89
6682
            description: Option<String>,
90
6682
        ) -> Result<Uuid, ServerError> {
91
3557
            let tag = new_tag(name, value, description)?;
92
3556
            let mut conn = self.get_connection().await.map_err(|err| {
93
                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
94
                ServerError::DB(err)
95
            })?;
96

            
97
3556
            tag.commit(&mut *conn).await.map_err(|err| {
98
                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
99
                ServerError::Finance(err)
100
            })
101
3557
        }
102

            
103
2530
        pub async fn list_tags(&self) -> Result<Vec<Tag>, ServerError> {
104
1137
            let mut conn = self.get_connection().await?;
105

            
106
977
            let tags = sqlx::query_file_as!(Tag, "sql/select/tags/all.sql")
107
977
                .fetch_all(&mut *conn)
108
977
                .await
109
                .map_err(|err| {
110
                    tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
111
                    ServerError::DB(crate::db::DBError::Sqlx(err))
112
                })?;
113

            
114
977
            Ok(tags)
115
1137
        }
116

            
117
        /// Replace the tag, refusing with [`ServerError::StaleTag`] when it no
118
        /// longer matches `revision`, checked under the key lock.
119
2570
        pub async fn update_tag(
120
2570
            &self,
121
2570
            id: Uuid,
122
2570
            revision: &str,
123
2570
            name: String,
124
2570
            value: String,
125
2570
            description: Option<String>,
126
2570
        ) -> Result<(), ServerError> {
127
1336
            let tag = new_tag(name, value, description)?;
128
1334
            let mut conn = self.get_connection().await?;
129
1334
            let mut tries = Tries::default();
130
1336
            while tries
131
1336
                .step(Attempt::of(
132
1336
                    rename::rename(&mut conn, id, revision, &tag).await,
133
1336
                    ServerError::is_retryable,
134
1336
                    std::convert::identity,
135
651
                ))?
136
                .is_none()
137
2
            {}
138
683
            Ok(())
139
1336
        }
140

            
141
2623
        pub async fn get_transaction_tags(&self, tx_id: Uuid) -> Result<Vec<Tag>, ServerError> {
142
2623
            let mut conn = self.get_connection().await?;
143

            
144
2623
            let tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &tx_id)
145
2623
                .fetch_all(&mut *conn)
146
2623
                .await
147
                .map_err(|err| {
148
                    tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
149
                    ServerError::DB(crate::db::DBError::Sqlx(err))
150
                })?;
151

            
152
2623
            Ok(tags)
153
2623
        }
154

            
155
        /// Upsert the tag and link it to the transaction in one DB
156
        /// transaction, owner locked first.
157
61284
        pub async fn create_transaction_tag(
158
61284
            &self,
159
61284
            tx_id: Uuid,
160
61284
            name: String,
161
61284
            value: String,
162
61284
            description: Option<String>,
163
61284
        ) -> Result<Uuid, ServerError> {
164
61284
            self.attach_tag(TagOwner::Transaction(tx_id), name, value, description)
165
61284
                .await
166
61284
        }
167

            
168
74282
        async fn attach_tag(
169
74282
            &self,
170
74282
            owner: TagOwner,
171
74282
            name: String,
172
74282
            value: String,
173
74282
            description: Option<String>,
174
74282
        ) -> Result<Uuid, ServerError> {
175
74282
            let tag = new_tag(name, value, description)?;
176
74281
            let mut conn = self.get_connection().await?;
177
74281
            owner::write(&mut conn, owner, &tag, owner::attach).await
178
74282
        }
179

            
180
        /// Cascade-delete a tag: detach from every join table, then drop the
181
        /// row from `tags`, under its key lock. Used by user-initiated tag
182
        /// deletion in the UI.
183
        ///
184
        /// # Errors
185
        /// A failing write, or [`crate::db::DBError::WriteConflict`] when the
186
        /// tag was renamed during every attempt.
187
        ///
188
        /// Whether the tag existed.
189
1629
        pub async fn delete_tag(&self, id: Uuid) -> Result<bool, ServerError> {
190
972
            let mut conn = self.get_connection().await?;
191
972
            let mut tries = Tries::default();
192
            loop {
193
976
                let attempt = Attempt::of(
194
976
                    remove::remove(&mut conn, id).await,
195
976
                    lock::is_retryable,
196
976
                    db_err,
197
                );
198
976
                if let Some(existed) = tries.step(attempt)? {
199
971
                    return Ok(existed);
200
4
                }
201
            }
202
972
        }
203

            
204
3067
        pub async fn list_tag_names(&self, scope: TagScope) -> Result<Vec<String>, ServerError> {
205
1773
            let mut conn = self.get_connection().await?;
206
1612
            let result = match scope {
207
323
                TagScope::Transaction => sqlx::query_file!("sql/select/tags/transaction/names.sql")
208
323
                    .fetch_all(&mut *conn)
209
323
                    .await
210
643
                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
211
323
                TagScope::Account => sqlx::query_file!("sql/select/tags/account/names.sql")
212
323
                    .fetch_all(&mut *conn)
213
323
                    .await
214
645
                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
215
322
                TagScope::Commodity => sqlx::query_file!("sql/select/tags/commodity/names.sql")
216
322
                    .fetch_all(&mut *conn)
217
322
                    .await
218
966
                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
219
644
                TagScope::Split => sqlx::query_file!("sql/select/tags/split/names.sql")
220
644
                    .fetch_all(&mut *conn)
221
644
                    .await
222
645
                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
223
            };
224
1612
            result.map_err(|err| {
225
                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
226
                ServerError::DB(crate::db::DBError::Sqlx(err))
227
            })
228
1773
        }
229

            
230
4513
        pub async fn list_tag_values_for(
231
4513
            &self,
232
4513
            scope: TagScope,
233
4513
            tag_name: &str,
234
4513
        ) -> Result<Vec<String>, ServerError> {
235
833
            let mut conn = self.get_connection().await?;
236
833
            let result = match scope {
237
                TagScope::Transaction => {
238
168
                    sqlx::query_file!("sql/select/tags/transaction/values_by_name.sql", tag_name)
239
168
                        .fetch_all(&mut *conn)
240
168
                        .await
241
168
                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
242
                }
243
                TagScope::Account => {
244
167
                    sqlx::query_file!("sql/select/tags/account/values_by_name.sql", tag_name)
245
167
                        .fetch_all(&mut *conn)
246
167
                        .await
247
167
                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
248
                }
249
                TagScope::Commodity => {
250
166
                    sqlx::query_file!("sql/select/tags/commodity/values_by_name.sql", tag_name)
251
166
                        .fetch_all(&mut *conn)
252
166
                        .await
253
166
                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
254
                }
255
                TagScope::Split => {
256
332
                    sqlx::query_file!("sql/select/tags/split/values_by_name.sql", tag_name)
257
332
                        .fetch_all(&mut *conn)
258
332
                        .await
259
332
                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
260
                }
261
            };
262
833
            result.map_err(|err| {
263
                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
264
                ServerError::DB(crate::db::DBError::Sqlx(err))
265
            })
266
833
        }
267

            
268
722
        pub async fn list_transaction_tag_names(&self) -> Result<Vec<String>, ServerError> {
269
483
            self.list_tag_names(TagScope::Transaction).await
270
483
        }
271

            
272
904
        pub async fn list_transaction_tag_values(
273
904
            &self,
274
904
            tag_name: &str,
275
904
        ) -> Result<Vec<String>, ServerError> {
276
168
            self.list_tag_values_for(TagScope::Transaction, tag_name)
277
168
                .await
278
168
        }
279

            
280
        /// Split counterpart of `create_transaction_tag`; locks the split's
281
        /// owning transaction.
282
12998
        pub async fn create_split_tag(
283
12998
            &self,
284
12998
            split_id: Uuid,
285
12998
            name: String,
286
12998
            value: String,
287
12998
            description: Option<String>,
288
12998
        ) -> Result<Uuid, ServerError> {
289
12998
            self.attach_tag(TagOwner::Split(split_id), name, value, description)
290
12998
                .await
291
12998
        }
292

            
293
        /// Upsert-style set: replace any existing (split, tag_name) link with
294
        /// the (tag_name, tag_value) pair from `t`. Mirrors `set_account_tag`
295
        /// — script-friendly idempotent set semantics.
296
3104
        pub async fn set_split_tag(&self, split_id: Uuid, t: &Tag) -> Result<(), ServerError> {
297
1969
            let mut conn = self.get_connection().await?;
298
1969
            owner::write(&mut conn, TagOwner::Split(split_id), t, owner::set).await
299
1969
        }
300

            
301
        /// Companion to `set_split_tag` for transactions.
302
1008
        pub async fn set_transaction_tag(&self, tx_id: Uuid, t: &Tag) -> Result<(), ServerError> {
303
113
            let mut conn = self.get_connection().await?;
304
113
            owner::write(&mut conn, TagOwner::Transaction(tx_id), t, owner::set).await
305
113
        }
306

            
307
        /// Read all tags attached to a single split. Parallel to
308
        /// `get_transaction_tags`; the script-side `get-split-tag` native
309
        /// looks up by name in the returned vec.
310
5
        pub async fn get_split_tags(&self, split_id: Uuid) -> Result<Vec<Tag>, ServerError> {
311
5
            let mut conn = self.get_connection().await?;
312

            
313
5
            let tags = crate::split::tags_of_split(&mut conn, split_id)
314
5
                .await
315
                .map_err(|err| {
316
                    tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
317
                    ServerError::DB(crate::db::DBError::Sqlx(err))
318
                })?;
319

            
320
5
            Ok(tags)
321
5
        }
322

            
323
542
        pub async fn list_account_tag_names(&self) -> Result<Vec<String>, ServerError> {
324
323
            self.list_tag_names(TagScope::Account).await
325
323
        }
326

            
327
903
        pub async fn list_account_tag_values(
328
903
            &self,
329
903
            tag_name: &str,
330
903
        ) -> Result<Vec<String>, ServerError> {
331
167
            self.list_tag_values_for(TagScope::Account, tag_name).await
332
167
        }
333

            
334
541
        pub async fn list_commodity_tag_names(&self) -> Result<Vec<String>, ServerError> {
335
322
            self.list_tag_names(TagScope::Commodity).await
336
322
        }
337

            
338
902
        pub async fn list_commodity_tag_values(
339
902
            &self,
340
902
            tag_name: &str,
341
902
        ) -> Result<Vec<String>, ServerError> {
342
166
            self.list_tag_values_for(TagScope::Commodity, tag_name)
343
166
                .await
344
166
        }
345

            
346
1262
        pub async fn list_split_tag_names(&self) -> Result<Vec<String>, ServerError> {
347
645
            self.list_tag_names(TagScope::Split).await
348
645
        }
349

            
350
1804
        pub async fn list_split_tag_values(
351
1804
            &self,
352
1804
            tag_name: &str,
353
1804
        ) -> Result<Vec<String>, ServerError> {
354
332
            self.list_tag_values_for(TagScope::Split, tag_name).await
355
332
        }
356
    }
357

            
358
    #[cfg(test)]
359
    mod tag_tests;
360
}
361

            
362
#[cfg(test)]
363
mod test_support;