1
use crate::error::{FinanceError, TagError};
2
use sqlx::{Connection, PgConnection, types::Uuid};
3
use supp_macro::Builder;
4

            
5
#[derive(Debug, Clone, sqlx::FromRow, Builder)]
6
#[builder(error_kind = "TagError")]
7
pub 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.
15
9448414
pub fn normalize<'a>(name: &'a str, value: &'a str) -> (&'a str, &'a str) {
16
9448414
    (name.trim(), value.trim())
17
9448414
}
18

            
19
impl Tag {
20
    /// A tag needs a non-blank name and value.
21
2224973
    pub fn is_blank(&self) -> bool {
22
2224973
        let (name, value) = self.normalized();
23
2224973
        name.is_empty() || value.is_empty()
24
2224973
    }
25

            
26
    /// Whether the trimmed name is `name`.
27
81559
    pub fn is_named(&self, name: &str) -> bool {
28
81559
        self.normalized().0 == name
29
81559
    }
30

            
31
    /// The trimmed `(name, value)` this tag is stored under.
32
7705347
    pub fn normalized(&self) -> (&str, &str) {
33
7705347
        normalize(&self.tag_name, &self.tag_value)
34
7705347
    }
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
788268
    pub async fn commit<E>(&self, conn: &mut E) -> Result<Uuid, FinanceError>
48
788268
    where
49
788268
        E: Connection<Database = sqlx::Postgres>,
50
788268
    {
51
788268
        if self.is_blank() {
52
193
            return Err(TagError::Build("blank tag name or value".to_string()).into());
53
788075
        }
54
788075
        let (name, value) = self.normalized();
55
788075
        let mut tr = conn.begin().await?;
56

            
57
788075
        let row = sqlx::query_file!(
58
788075
            "sql/tag_insert.sql",
59
            &self.id,
60
            name,
61
            value,
62
            self.description
63
        )
64
788075
        .fetch_one(&mut *tr)
65
788075
        .await?;
66
788075
        tr.commit().await?;
67

            
68
788075
        Ok(row.id)
69
788268
    }
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.
74
72773
pub async fn insert_split_tags(
75
72773
    conn: &mut PgConnection,
76
72773
    split_tags: &[(Uuid, Tag)],
77
72773
) -> Result<(), FinanceError> {
78
72773
    for (split_id, tag) in split_tags {
79
186418
        let tag_id = tag.commit(conn).await?;
80
186418
        sqlx::query_file!("sql/split_tag_set.sql", split_id, tag_id)
81
186418
            .execute(&mut *conn)
82
186418
            .await?;
83
    }
84
72582
    Ok(())
85
72773
}
86

            
87
#[cfg(test)]
88
mod 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
2
    async fn setup() {
97
2
        CONTEXT
98
2
            .get_or_init(|| async {
99
                #[cfg(feature = "testlog")]
100
2
                crate::test_logging::init();
101
4
            })
102
2
            .await;
103
2
    }
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
1
    async fn test_tag_builder() -> anyhow::Result<()> {
155
1
        setup().await;
156
1
        let build = Tag::builder().id(Uuid::new_v4()).build();
157
1
        assert!(build.is_err());
158
1
        let build = Tag::builder()
159
1
            .id(Uuid::new_v4())
160
1
            .tag_name("name")
161
1
            .tag_value("type")
162
1
            .build();
163

            
164
1
        assert!(build.is_ok());
165
2
        Ok(())
166
1
    }
167
}
168

            
169
#[cfg(test)]
170
#[path = "tag_trim_tests.rs"]
171
mod trim_tests;