1
//! A stored transaction read as one consistent snapshot.
2

            
3
use std::collections::HashMap;
4

            
5
use finance::price::Price;
6
use finance::split::Split;
7
use finance::tag::Tag;
8
use finance::transaction::Transaction;
9
use sqlx::Connection;
10
use sqlx::types::Uuid;
11

            
12
use crate::db::DBError;
13
use crate::error::ServerError;
14
use crate::split::split_tags_of;
15
use 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)]
20
pub 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

            
28
pub(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

            
33
impl 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
65342
    pub async fn transaction_snapshot(
40
65342
        &self,
41
65342
        tx_id: Uuid,
42
65342
    ) -> Result<Option<TransactionSnapshot>, ServerError> {
43
22307
        let mut conn = self.get_connection().await?;
44
22305
        let mut tx = conn
45
22305
            .begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
46
22305
            .await
47
22305
            .map_err(db_error)?;
48
22305
        let Some(row) = sqlx::query_file!("sql/select/transactions/by_id.sql", tx_id)
49
22305
            .fetch_optional(&mut *tx)
50
22305
            .await
51
22305
            .map_err(db_error)?
52
        else {
53
968
            tx.rollback().await.map_err(db_error)?;
54
968
            return Ok(None);
55
        };
56
21337
        let tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", tx_id)
57
21337
            .fetch_all(&mut *tx)
58
21337
            .await
59
21337
            .map_err(db_error)?;
60
21337
        let prices = sqlx::query_file!("sql/select/prices/by_transaction.sql", tx_id)
61
21337
            .fetch_all(&mut *tx)
62
21337
            .await
63
21337
            .map_err(db_error)?
64
            .into_iter()
65
            .map(|price| Price {
66
14285
                id: price.id,
67
14285
                date: price.price_date,
68
14285
                commodity_id: price.commodity_id,
69
14285
                currency_id: price.currency_id,
70
14285
                commodity_split: price.commodity_split_id,
71
14285
                currency_split: price.currency_split_id,
72
14285
                value_num: price.value_num,
73
14285
                value_denom: price.value_denom,
74
14285
            })
75
            .collect();
76
21337
        let splits = sqlx::query_file_as!(Split, "sql/select/splits/by_transaction.sql", tx_id)
77
21337
            .fetch_all(&mut *tx)
78
21337
            .await
79
21337
            .map_err(db_error)?;
80
21337
        let split_tags = split_tags_of(&mut tx, &splits).await.map_err(db_error)?;
81
21337
        tx.rollback().await.map_err(db_error)?;
82
21337
        Ok(Some(TransactionSnapshot {
83
21337
            transaction: Transaction {
84
21337
                id: row.id,
85
21337
                post_date: row.post_date,
86
21337
                enter_date: row.enter_date,
87
21337
            },
88
21337
            tags,
89
21337
            prices,
90
21337
            splits,
91
21337
            split_tags,
92
21337
        }))
93
22307
    }
94
}
95

            
96
#[cfg(test)]
97
#[path = "snapshot_tests.rs"]
98
mod tests;