Skip to main content

server/
commodity_state.rs

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
4use finance::tag::Tag;
5use sqlx::{Connection, PgConnection, types::Uuid};
6
7use crate::error::ServerError;
8use crate::logical::hex_digest;
9use crate::snapshot::db_error;
10use crate::user::User;
11
12/// The error text of a commodity edit whose expected revision no longer matches.
13pub const STALE_COMMODITY: &str = "the commodity changed since it was loaded; reload it";
14
15#[derive(Debug, Clone)]
16pub struct StoredCommodity {
17    /// Every tag of the commodity, sorted by name and value.
18    pub tags: Vec<Tag>,
19}
20
21impl StoredCommodity {
22    /// Digest of the tags with their descriptions.
23    #[must_use]
24    pub fn revision(&self) -> String {
25        hex_digest(
26            self.tags
27                .iter()
28                .map(|tag| {
29                    format!(
30                        "tag {:?}",
31                        (&tag.tag_name, &tag.tag_value, &tag.description)
32                    )
33                })
34                .collect(),
35        )
36    }
37}
38
39/// The commodity as stored, `None` when the user has no such commodity.
40pub(crate) async fn read_commodity(
41    conn: &mut PgConnection,
42    commodity_id: Uuid,
43) -> Result<Option<StoredCommodity>, sqlx::Error> {
44    if sqlx::query_file!("sql/select/commodities/by_id.sql", commodity_id)
45        .fetch_optional(&mut *conn)
46        .await?
47        .is_none()
48    {
49        return Ok(None);
50    }
51    let mut tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_commodity.sql", commodity_id)
52        .fetch_all(conn)
53        .await?;
54    tags.sort_by(|a, b| (&a.tag_name, &a.tag_value).cmp(&(&b.tag_name, &b.tag_value)));
55    Ok(Some(StoredCommodity { tags }))
56}
57
58impl 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    pub async fn commodity_snapshot(
65        &self,
66        commodity_id: Uuid,
67    ) -> Result<Option<StoredCommodity>, ServerError> {
68        let mut conn = self.get_connection().await?;
69        let mut tx = conn
70            .begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
71            .await
72            .map_err(db_error)?;
73        let commodity = read_commodity(&mut tx, commodity_id)
74            .await
75            .map_err(db_error)?;
76        tx.rollback().await.map_err(db_error)?;
77        Ok(commodity)
78    }
79}