1
//! A stored commodity as the commodity-edit form holds it: every tag, the
2
//! `symbol` and `name` tags among them, with the revision digesting them.
3

            
4
use finance::tag::Tag;
5
use sqlx::{Connection, PgConnection, types::Uuid};
6

            
7
use crate::error::ServerError;
8
use crate::logical::hex_digest;
9
use crate::snapshot::db_error;
10
use crate::user::User;
11

            
12
/// The error text of a commodity edit whose expected revision no longer matches.
13
pub const STALE_COMMODITY: &str = "the commodity changed since it was loaded; reload it";
14

            
15
#[derive(Debug, Clone)]
16
pub struct StoredCommodity {
17
    /// Every tag of the commodity, sorted by name and value.
18
    pub tags: Vec<Tag>,
19
}
20

            
21
impl StoredCommodity {
22
    /// Digest of the tags with their descriptions.
23
    #[must_use]
24
10460
    pub fn revision(&self) -> String {
25
10460
        hex_digest(
26
10460
            self.tags
27
10460
                .iter()
28
37140
                .map(|tag| {
29
37140
                    format!(
30
                        "tag {:?}",
31
37140
                        (&tag.tag_name, &tag.tag_value, &tag.description)
32
                    )
33
37140
                })
34
                .collect(),
35
        )
36
10460
    }
37
}
38

            
39
/// The commodity as stored, `None` when the user has no such commodity.
40
16417
pub(crate) async fn read_commodity(
41
16417
    conn: &mut PgConnection,
42
16417
    commodity_id: Uuid,
43
16417
) -> Result<Option<StoredCommodity>, sqlx::Error> {
44
4898
    if sqlx::query_file!("sql/select/commodities/by_id.sql", commodity_id)
45
4898
        .fetch_optional(&mut *conn)
46
4898
        .await?
47
        .is_none()
48
    {
49
163
        return Ok(None);
50
4735
    }
51
4735
    let mut tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_commodity.sql", commodity_id)
52
4735
        .fetch_all(conn)
53
4735
        .await?;
54
9368
    tags.sort_by(|a, b| (&a.tag_name, &a.tag_value).cmp(&(&b.tag_name, &b.tag_value)));
55
4735
    Ok(Some(StoredCommodity { tags }))
56
4898
}
57

            
58
impl User {
59
    /// The commodity's tags as of one instant; `None` when the user has no
60
    /// such commodity.
61
    ///
62
    /// # Errors
63
    /// The connection or a query failing.
64
12078
    pub async fn commodity_snapshot(
65
12078
        &self,
66
12078
        commodity_id: Uuid,
67
12078
    ) -> Result<Option<StoredCommodity>, ServerError> {
68
3265
        let mut conn = self.get_connection().await?;
69
3265
        let mut tx = conn
70
3265
            .begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
71
3265
            .await
72
3265
            .map_err(db_error)?;
73
3265
        let commodity = read_commodity(&mut tx, commodity_id)
74
3265
            .await
75
3265
            .map_err(db_error)?;
76
3265
        tx.rollback().await.map_err(db_error)?;
77
3265
        Ok(commodity)
78
3265
    }
79
}