server/
commodity_state.rs1use 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
12pub const STALE_COMMODITY: &str = "the commodity changed since it was loaded; reload it";
14
15#[derive(Debug, Clone)]
16pub struct StoredCommodity {
17 pub tags: Vec<Tag>,
19}
20
21impl StoredCommodity {
22 #[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
39pub(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 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}