Skip to main content

server/
snapshot.rs

1//! A stored transaction read as one consistent snapshot.
2
3use std::collections::HashMap;
4
5use finance::price::Price;
6use finance::split::Split;
7use finance::tag::Tag;
8use finance::transaction::Transaction;
9use sqlx::Connection;
10use sqlx::types::Uuid;
11
12use crate::db::DBError;
13use crate::error::ServerError;
14use crate::split::split_tags_of;
15use crate::user::User;
16
17/// The header, tags, prices, splits and split tags of one transaction, all
18/// read in a single repeatable-read database transaction.
19#[derive(Debug)]
20pub struct TransactionSnapshot {
21    pub transaction: Transaction,
22    pub tags: Vec<Tag>,
23    pub prices: Vec<Price>,
24    pub splits: Vec<Split>,
25    pub split_tags: HashMap<Uuid, Vec<Tag>>,
26}
27
28pub(crate) fn db_error(err: sqlx::Error) -> ServerError {
29    tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
30    ServerError::DB(DBError::Sqlx(err))
31}
32
33impl User {
34    /// The transaction with everything attached to it, as of one instant;
35    /// `None` when it does not exist.
36    ///
37    /// # Errors
38    /// The connection or a query failing.
39    pub async fn transaction_snapshot(
40        &self,
41        tx_id: Uuid,
42    ) -> Result<Option<TransactionSnapshot>, ServerError> {
43        let mut conn = self.get_connection().await?;
44        let mut tx = conn
45            .begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
46            .await
47            .map_err(db_error)?;
48        let Some(row) = sqlx::query_file!("sql/select/transactions/by_id.sql", tx_id)
49            .fetch_optional(&mut *tx)
50            .await
51            .map_err(db_error)?
52        else {
53            tx.rollback().await.map_err(db_error)?;
54            return Ok(None);
55        };
56        let tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", tx_id)
57            .fetch_all(&mut *tx)
58            .await
59            .map_err(db_error)?;
60        let prices = sqlx::query_file!("sql/select/prices/by_transaction.sql", tx_id)
61            .fetch_all(&mut *tx)
62            .await
63            .map_err(db_error)?
64            .into_iter()
65            .map(|price| Price {
66                id: price.id,
67                date: price.price_date,
68                commodity_id: price.commodity_id,
69                currency_id: price.currency_id,
70                commodity_split: price.commodity_split_id,
71                currency_split: price.currency_split_id,
72                value_num: price.value_num,
73                value_denom: price.value_denom,
74            })
75            .collect();
76        let splits = sqlx::query_file_as!(Split, "sql/select/splits/by_transaction.sql", tx_id)
77            .fetch_all(&mut *tx)
78            .await
79            .map_err(db_error)?;
80        let split_tags = split_tags_of(&mut tx, &splits).await.map_err(db_error)?;
81        tx.rollback().await.map_err(db_error)?;
82        Ok(Some(TransactionSnapshot {
83            transaction: Transaction {
84                id: row.id,
85                post_date: row.post_date,
86                enter_date: row.enter_date,
87            },
88            tags,
89            prices,
90            splits,
91            split_tags,
92        }))
93    }
94}
95
96#[cfg(test)]
97#[path = "snapshot_tests.rs"]
98mod tests;