Lines
100 %
Functions
Branches
use crate::error::{FinanceError, TagError};
use sqlx::{Connection, PgConnection, types::Uuid};
use supp_macro::Builder;
#[derive(Debug, Clone, sqlx::FromRow, Builder)]
#[builder(error_kind = "TagError")]
pub struct Tag {
pub id: Uuid,
pub tag_name: String,
pub tag_value: String,
pub description: Option<String>,
}
/// The stored form of a tag name and value: trimmed.
pub fn normalize<'a>(name: &'a str, value: &'a str) -> (&'a str, &'a str) {
(name.trim(), value.trim())
impl Tag {
/// A tag needs a non-blank name and value.
pub fn is_blank(&self) -> bool {
let (name, value) = self.normalized();
name.is_empty() || value.is_empty()
/// Whether the trimmed name is `name`.
pub fn is_named(&self, name: &str) -> bool {
self.normalized().0 == name
/// The trimmed `(name, value)` this tag is stored under.
pub fn normalized(&self) -> (&str, &str) {
normalize(&self.tag_name, &self.tag_value)
/// Upsert this tag and return the canonical row id.
///
/// Tag identity is `(tag_name, tag_value)`. When a row with the same pair
/// already exists, its id is returned and the description is refreshed
/// only if a non-NULL one was supplied. The returned id may differ from
/// `self.id`; callers linking the tag to an entity must use the returned
/// canonical id.
/// Conflicts only on `(tag_name, tag_value)`: committing an existing id
/// with a different pair violates `tags_pkey`. Tag rows are shared and
/// never edited in place.
pub async fn commit<E>(&self, conn: &mut E) -> Result<Uuid, FinanceError>
where
E: Connection<Database = sqlx::Postgres>,
{
if self.is_blank() {
return Err(TagError::Build("blank tag name or value".to_string()).into());
let mut tr = conn.begin().await?;
let row = sqlx::query_file!(
"sql/tag_insert.sql",
&self.id,
name,
value,
self.description
)
.fetch_one(&mut *tr)
.await?;
tr.commit().await?;
Ok(row.id)
/// Upsert each tag and link it to its split on `conn`, which must already be
/// inside the caller's database transaction.
pub async fn insert_split_tags(
conn: &mut PgConnection,
split_tags: &[(Uuid, Tag)],
) -> Result<(), FinanceError> {
for (split_id, tag) in split_tags {
let tag_id = tag.commit(conn).await?;
sqlx::query_file!("sql/split_tag_set.sql", split_id, tag_id)
.execute(&mut *conn)
Ok(())
#[cfg(test)]
mod tag_tests {
use super::*;
use sqlx::PgPool;
use tokio::sync::OnceCell;
/// Context for keeping environment intact
static CONTEXT: OnceCell<()> = OnceCell::const_new();
async fn setup() {
CONTEXT
.get_or_init(|| async {
#[cfg(feature = "testlog")]
crate::test_logging::init();
})
.await;
#[sqlx::test(migrations = "../migrations")]
async fn test_tag_store(pool: PgPool) -> anyhow::Result<()> {
setup().await;
let mut conn = pool.acquire().await?;
let tag = Tag {
id: Uuid::new_v4(),
tag_name: "Category".to_string(),
tag_value: "test".to_string(),
description: None,
};
sqlx::query!(
"INSERT INTO tags (id, tag_name, tag_value, description) \
VALUES ($1, $2, $3, $4)",
&tag.id,
&tag.tag_name,
&tag.tag_value,
tag.description
let result = sqlx::query!("SELECT id, tag_value FROM tags WHERE tag_name = 'Category'")
.fetch_one(&mut *conn)
assert_eq!(tag.id, result.id);
assert_eq!(tag.tag_value, "test".to_string());
let tag2 = Tag {
tag_name: "Cat2".to_string(),
..tag
tag2.commit(&mut *conn).await?;
let result = sqlx::query!("SELECT id, tag_value FROM tags WHERE tag_name = 'Cat2'")
assert_eq!(tag2.id, result.id);
assert_eq!(tag2.tag_value, "test".to_string());
#[tokio::test]
async fn test_tag_builder() -> anyhow::Result<()> {
let build = Tag::builder().id(Uuid::new_v4()).build();
assert!(build.is_err());
let build = Tag::builder()
.id(Uuid::new_v4())
.tag_name("name")
.tag_value("type")
.build();
assert!(build.is_ok());
#[path = "tag_trim_tests.rs"]
mod trim_tests;