Skip to main content

server/
account_state.rs

1//! A stored account as the account-edit form holds it: its parent and every
2//! tag, the `name` tag 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 an account edit whose expected revision no longer matches.
13pub const STALE_ACCOUNT: &str = "the account changed since it was loaded; reload it";
14
15#[derive(Debug, Clone)]
16pub struct StoredAccount {
17    pub parent: Option<Uuid>,
18    /// Every tag of the account, sorted by name and value.
19    pub tags: Vec<Tag>,
20}
21
22impl StoredAccount {
23    /// Digest of the parent and the tags, the name tag included.
24    #[must_use]
25    pub fn revision(&self) -> String {
26        let tags = self.tags.iter().map(|tag| {
27            format!(
28                "tag {:?}",
29                (&tag.tag_name, &tag.tag_value, &tag.description)
30            )
31        });
32        hex_digest(
33            std::iter::once(format!("parent {:?}", self.parent))
34                .chain(tags)
35                .collect(),
36        )
37    }
38}
39
40/// The account as stored, `None` when the user has no such account.
41pub(crate) async fn read_account(
42    conn: &mut PgConnection,
43    account_id: Uuid,
44) -> Result<Option<StoredAccount>, sqlx::Error> {
45    let Some(row) = sqlx::query_file!("sql/select/accounts/by_id.sql", account_id)
46        .fetch_optional(&mut *conn)
47        .await?
48    else {
49        return Ok(None);
50    };
51    let mut tags: Vec<Tag> =
52        sqlx::query_file_as!(Tag, "sql/select/tags/by_account.sql", account_id)
53            .fetch_all(conn)
54            .await?;
55    tags.sort_by(|a, b| (&a.tag_name, &a.tag_value).cmp(&(&b.tag_name, &b.tag_value)));
56    Ok(Some(StoredAccount {
57        parent: row.parent,
58        tags,
59    }))
60}
61
62impl User {
63    /// The account's parent and tags as of one instant; `None` when the user
64    /// has no such account.
65    ///
66    /// # Errors
67    /// The connection or a query failing.
68    pub async fn account_snapshot(
69        &self,
70        account_id: Uuid,
71    ) -> Result<Option<StoredAccount>, ServerError> {
72        let mut conn = self.get_connection().await?;
73        let mut tx = conn
74            .begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
75            .await
76            .map_err(db_error)?;
77        let account = read_account(&mut tx, account_id).await.map_err(db_error)?;
78        tx.rollback().await.map_err(db_error)?;
79        Ok(account)
80    }
81}