Skip to main content

server/
tag.rs

1pub(crate) mod artifact;
2pub(crate) mod lock;
3pub(crate) mod owned;
4
5pub 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    fn db_err(err: sqlx::Error) -> ServerError {
24        tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
25        ServerError::DB(crate::db::DBError::Sqlx(err))
26    }
27
28    pub(crate) mod links;
29    mod owner;
30    mod remove;
31    mod rename;
32
33    use owner::TagOwner;
34
35    pub(crate) async fn lock_account(
36        conn: &mut sqlx::PgConnection,
37        account_id: Uuid,
38    ) -> Result<(), sqlx::Error> {
39        sqlx::query_file!("sql/select/accounts/by_id_locked.sql", account_id)
40            .fetch_one(conn)
41            .await?;
42        Ok(())
43    }
44
45    fn new_tag(
46        name: String,
47        value: String,
48        description: Option<String>,
49    ) -> Result<Tag, ServerError> {
50        let (tag_name, tag_value) = normalize(&name, &value);
51        if tag_name.is_empty() || tag_value.is_empty() {
52            return Err(ServerError::Creation);
53        }
54        Ok(Tag {
55            id: Uuid::new_v4(),
56            tag_name: tag_name.to_string(),
57            tag_value: tag_value.to_string(),
58            description: description.filter(|text| !text.is_empty()),
59        })
60    }
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    pub(crate) async fn delete_tag_if_orphaned(
65        conn: &mut sqlx::PgConnection,
66        tag_id: Uuid,
67    ) -> Result<(), sqlx::Error> {
68        sqlx::query_file!("sql/select/tags/lock_by_id.sql", tag_id)
69            .fetch_optional(&mut *conn)
70            .await?;
71        let is_orphaned = sqlx::query_file!("sql/check/tags/is_orphaned.sql", tag_id)
72            .fetch_one(&mut *conn)
73            .await?
74            .is_orphaned
75            .unwrap_or(false);
76        if is_orphaned {
77            sqlx::query_file!("sql/delete/tags/by_id.sql", tag_id)
78                .execute(&mut *conn)
79                .await?;
80        }
81        Ok(())
82    }
83
84    impl User {
85        pub async fn create_tag(
86            &self,
87            name: String,
88            value: String,
89            description: Option<String>,
90        ) -> Result<Uuid, ServerError> {
91            let tag = new_tag(name, value, description)?;
92            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            tag.commit(&mut *conn).await.map_err(|err| {
98                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
99                ServerError::Finance(err)
100            })
101        }
102
103        pub async fn list_tags(&self) -> Result<Vec<Tag>, ServerError> {
104            let mut conn = self.get_connection().await?;
105
106            let tags = sqlx::query_file_as!(Tag, "sql/select/tags/all.sql")
107                .fetch_all(&mut *conn)
108                .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            Ok(tags)
115        }
116
117        /// Replace the tag, refusing with [`ServerError::StaleTag`] when it no
118        /// longer matches `revision`, checked under the key lock.
119        pub async fn update_tag(
120            &self,
121            id: Uuid,
122            revision: &str,
123            name: String,
124            value: String,
125            description: Option<String>,
126        ) -> Result<(), ServerError> {
127            let tag = new_tag(name, value, description)?;
128            let mut conn = self.get_connection().await?;
129            let mut tries = Tries::default();
130            while tries
131                .step(Attempt::of(
132                    rename::rename(&mut conn, id, revision, &tag).await,
133                    ServerError::is_retryable,
134                    std::convert::identity,
135                ))?
136                .is_none()
137            {}
138            Ok(())
139        }
140
141        pub async fn get_transaction_tags(&self, tx_id: Uuid) -> Result<Vec<Tag>, ServerError> {
142            let mut conn = self.get_connection().await?;
143
144            let tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &tx_id)
145                .fetch_all(&mut *conn)
146                .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            Ok(tags)
153        }
154
155        /// Upsert the tag and link it to the transaction in one DB
156        /// transaction, owner locked first.
157        pub async fn create_transaction_tag(
158            &self,
159            tx_id: Uuid,
160            name: String,
161            value: String,
162            description: Option<String>,
163        ) -> Result<Uuid, ServerError> {
164            self.attach_tag(TagOwner::Transaction(tx_id), name, value, description)
165                .await
166        }
167
168        async fn attach_tag(
169            &self,
170            owner: TagOwner,
171            name: String,
172            value: String,
173            description: Option<String>,
174        ) -> Result<Uuid, ServerError> {
175            let tag = new_tag(name, value, description)?;
176            let mut conn = self.get_connection().await?;
177            owner::write(&mut conn, owner, &tag, owner::attach).await
178        }
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        pub async fn delete_tag(&self, id: Uuid) -> Result<bool, ServerError> {
190            let mut conn = self.get_connection().await?;
191            let mut tries = Tries::default();
192            loop {
193                let attempt = Attempt::of(
194                    remove::remove(&mut conn, id).await,
195                    lock::is_retryable,
196                    db_err,
197                );
198                if let Some(existed) = tries.step(attempt)? {
199                    return Ok(existed);
200                }
201            }
202        }
203
204        pub async fn list_tag_names(&self, scope: TagScope) -> Result<Vec<String>, ServerError> {
205            let mut conn = self.get_connection().await?;
206            let result = match scope {
207                TagScope::Transaction => sqlx::query_file!("sql/select/tags/transaction/names.sql")
208                    .fetch_all(&mut *conn)
209                    .await
210                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
211                TagScope::Account => sqlx::query_file!("sql/select/tags/account/names.sql")
212                    .fetch_all(&mut *conn)
213                    .await
214                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
215                TagScope::Commodity => sqlx::query_file!("sql/select/tags/commodity/names.sql")
216                    .fetch_all(&mut *conn)
217                    .await
218                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
219                TagScope::Split => sqlx::query_file!("sql/select/tags/split/names.sql")
220                    .fetch_all(&mut *conn)
221                    .await
222                    .map(|rows| rows.into_iter().map(|r| r.tag_name).collect::<Vec<_>>()),
223            };
224            result.map_err(|err| {
225                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
226                ServerError::DB(crate::db::DBError::Sqlx(err))
227            })
228        }
229
230        pub async fn list_tag_values_for(
231            &self,
232            scope: TagScope,
233            tag_name: &str,
234        ) -> Result<Vec<String>, ServerError> {
235            let mut conn = self.get_connection().await?;
236            let result = match scope {
237                TagScope::Transaction => {
238                    sqlx::query_file!("sql/select/tags/transaction/values_by_name.sql", tag_name)
239                        .fetch_all(&mut *conn)
240                        .await
241                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
242                }
243                TagScope::Account => {
244                    sqlx::query_file!("sql/select/tags/account/values_by_name.sql", tag_name)
245                        .fetch_all(&mut *conn)
246                        .await
247                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
248                }
249                TagScope::Commodity => {
250                    sqlx::query_file!("sql/select/tags/commodity/values_by_name.sql", tag_name)
251                        .fetch_all(&mut *conn)
252                        .await
253                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
254                }
255                TagScope::Split => {
256                    sqlx::query_file!("sql/select/tags/split/values_by_name.sql", tag_name)
257                        .fetch_all(&mut *conn)
258                        .await
259                        .map(|rows| rows.into_iter().map(|r| r.tag_value).collect::<Vec<_>>())
260                }
261            };
262            result.map_err(|err| {
263                tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
264                ServerError::DB(crate::db::DBError::Sqlx(err))
265            })
266        }
267
268        pub async fn list_transaction_tag_names(&self) -> Result<Vec<String>, ServerError> {
269            self.list_tag_names(TagScope::Transaction).await
270        }
271
272        pub async fn list_transaction_tag_values(
273            &self,
274            tag_name: &str,
275        ) -> Result<Vec<String>, ServerError> {
276            self.list_tag_values_for(TagScope::Transaction, tag_name)
277                .await
278        }
279
280        /// Split counterpart of `create_transaction_tag`; locks the split's
281        /// owning transaction.
282        pub async fn create_split_tag(
283            &self,
284            split_id: Uuid,
285            name: String,
286            value: String,
287            description: Option<String>,
288        ) -> Result<Uuid, ServerError> {
289            self.attach_tag(TagOwner::Split(split_id), name, value, description)
290                .await
291        }
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        pub async fn set_split_tag(&self, split_id: Uuid, t: &Tag) -> Result<(), ServerError> {
297            let mut conn = self.get_connection().await?;
298            owner::write(&mut conn, TagOwner::Split(split_id), t, owner::set).await
299        }
300
301        /// Companion to `set_split_tag` for transactions.
302        pub async fn set_transaction_tag(&self, tx_id: Uuid, t: &Tag) -> Result<(), ServerError> {
303            let mut conn = self.get_connection().await?;
304            owner::write(&mut conn, TagOwner::Transaction(tx_id), t, owner::set).await
305        }
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        pub async fn get_split_tags(&self, split_id: Uuid) -> Result<Vec<Tag>, ServerError> {
311            let mut conn = self.get_connection().await?;
312
313            let tags = crate::split::tags_of_split(&mut conn, split_id)
314                .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            Ok(tags)
321        }
322
323        pub async fn list_account_tag_names(&self) -> Result<Vec<String>, ServerError> {
324            self.list_tag_names(TagScope::Account).await
325        }
326
327        pub async fn list_account_tag_values(
328            &self,
329            tag_name: &str,
330        ) -> Result<Vec<String>, ServerError> {
331            self.list_tag_values_for(TagScope::Account, tag_name).await
332        }
333
334        pub async fn list_commodity_tag_names(&self) -> Result<Vec<String>, ServerError> {
335            self.list_tag_names(TagScope::Commodity).await
336        }
337
338        pub async fn list_commodity_tag_values(
339            &self,
340            tag_name: &str,
341        ) -> Result<Vec<String>, ServerError> {
342            self.list_tag_values_for(TagScope::Commodity, tag_name)
343                .await
344        }
345
346        pub async fn list_split_tag_names(&self) -> Result<Vec<String>, ServerError> {
347            self.list_tag_names(TagScope::Split).await
348        }
349
350        pub async fn list_split_tag_values(
351            &self,
352            tag_name: &str,
353        ) -> Result<Vec<String>, ServerError> {
354            self.list_tag_values_for(TagScope::Split, tag_name).await
355        }
356    }
357
358    #[cfg(test)]
359    mod tag_tests;
360}
361
362#[cfg(test)]
363mod test_support;