Skip to main content

finance/
tag.rs

1use crate::error::{FinanceError, TagError};
2use sqlx::{Connection, PgConnection, types::Uuid};
3use supp_macro::Builder;
4
5#[derive(Debug, Clone, sqlx::FromRow, Builder)]
6#[builder(error_kind = "TagError")]
7pub struct Tag {
8    pub id: Uuid,
9    pub tag_name: String,
10    pub tag_value: String,
11    pub description: Option<String>,
12}
13
14/// The stored form of a tag name and value: trimmed.
15pub fn normalize<'a>(name: &'a str, value: &'a str) -> (&'a str, &'a str) {
16    (name.trim(), value.trim())
17}
18
19impl Tag {
20    /// A tag needs a non-blank name and value.
21    pub fn is_blank(&self) -> bool {
22        let (name, value) = self.normalized();
23        name.is_empty() || value.is_empty()
24    }
25
26    /// Whether the trimmed name is `name`.
27    pub fn is_named(&self, name: &str) -> bool {
28        self.normalized().0 == name
29    }
30
31    /// The trimmed `(name, value)` this tag is stored under.
32    pub fn normalized(&self) -> (&str, &str) {
33        normalize(&self.tag_name, &self.tag_value)
34    }
35
36    /// Upsert this tag and return the canonical row id.
37    ///
38    /// Tag identity is `(tag_name, tag_value)`. When a row with the same pair
39    /// already exists, its id is returned and the description is refreshed
40    /// only if a non-NULL one was supplied. The returned id may differ from
41    /// `self.id`; callers linking the tag to an entity must use the returned
42    /// canonical id.
43    ///
44    /// Conflicts only on `(tag_name, tag_value)`: committing an existing id
45    /// with a different pair violates `tags_pkey`. Tag rows are shared and
46    /// never edited in place.
47    pub async fn commit<E>(&self, conn: &mut E) -> Result<Uuid, FinanceError>
48    where
49        E: Connection<Database = sqlx::Postgres>,
50    {
51        if self.is_blank() {
52            return Err(TagError::Build("blank tag name or value".to_string()).into());
53        }
54        let (name, value) = self.normalized();
55        let mut tr = conn.begin().await?;
56
57        let row = sqlx::query_file!(
58            "sql/tag_insert.sql",
59            &self.id,
60            name,
61            value,
62            self.description
63        )
64        .fetch_one(&mut *tr)
65        .await?;
66        tr.commit().await?;
67
68        Ok(row.id)
69    }
70}
71
72/// Upsert each tag and link it to its split on `conn`, which must already be
73/// inside the caller's database transaction.
74pub async fn insert_split_tags(
75    conn: &mut PgConnection,
76    split_tags: &[(Uuid, Tag)],
77) -> Result<(), FinanceError> {
78    for (split_id, tag) in split_tags {
79        let tag_id = tag.commit(conn).await?;
80        sqlx::query_file!("sql/split_tag_set.sql", split_id, tag_id)
81            .execute(&mut *conn)
82            .await?;
83    }
84    Ok(())
85}
86
87#[cfg(test)]
88mod tag_tests {
89    use super::*;
90    use sqlx::PgPool;
91    use tokio::sync::OnceCell;
92
93    /// Context for keeping environment intact
94    static CONTEXT: OnceCell<()> = OnceCell::const_new();
95
96    async fn setup() {
97        CONTEXT
98            .get_or_init(|| async {
99                #[cfg(feature = "testlog")]
100                crate::test_logging::init();
101            })
102            .await;
103    }
104
105    #[sqlx::test(migrations = "../migrations")]
106    async fn test_tag_store(pool: PgPool) -> anyhow::Result<()> {
107        setup().await;
108        let mut conn = pool.acquire().await?;
109
110        let tag = Tag {
111            id: Uuid::new_v4(),
112            tag_name: "Category".to_string(),
113            tag_value: "test".to_string(),
114            description: None,
115        };
116
117        sqlx::query!(
118            "INSERT INTO tags (id, tag_name, tag_value, description) \
119		      VALUES ($1, $2, $3, $4)",
120            &tag.id,
121            &tag.tag_name,
122            &tag.tag_value,
123            tag.description
124        )
125        .execute(&mut *conn)
126        .await?;
127
128        let result = sqlx::query!("SELECT id, tag_value FROM tags WHERE tag_name = 'Category'")
129            .fetch_one(&mut *conn)
130            .await?;
131
132        assert_eq!(tag.id, result.id);
133        assert_eq!(tag.tag_value, "test".to_string());
134
135        let tag2 = Tag {
136            id: Uuid::new_v4(),
137            tag_name: "Cat2".to_string(),
138            ..tag
139        };
140        let mut conn = pool.acquire().await?;
141        tag2.commit(&mut *conn).await?;
142        let mut conn = pool.acquire().await?;
143        let result = sqlx::query!("SELECT id, tag_value FROM tags WHERE tag_name = 'Cat2'")
144            .fetch_one(&mut *conn)
145            .await?;
146
147        assert_eq!(tag2.id, result.id);
148        assert_eq!(tag2.tag_value, "test".to_string());
149
150        Ok(())
151    }
152
153    #[tokio::test]
154    async fn test_tag_builder() -> anyhow::Result<()> {
155        setup().await;
156        let build = Tag::builder().id(Uuid::new_v4()).build();
157        assert!(build.is_err());
158        let build = Tag::builder()
159            .id(Uuid::new_v4())
160            .tag_name("name")
161            .tag_value("type")
162            .build();
163
164        assert!(build.is_ok());
165        Ok(())
166    }
167}
168
169#[cfg(test)]
170#[path = "tag_trim_tests.rs"]
171mod trim_tests;