1
use super::split::SetSplitTag;
2
use super::transaction::{
3
    CreateTransaction, DeleteTransaction, SetTransactionTag, UpdateTransaction,
4
};
5
use super::{CmdResult, FinanceEntity, account::CreateAccount, commodity::CreateCommodity};
6
use crate::{db::install_test_pool, user::User};
7
use chrono::{TimeZone, Utc};
8
use finance::{price::Price, split::Split, tag::Tag};
9
use sqlx::PgPool;
10
use std::collections::HashMap;
11
use supp_macro::local_db_sqlx_test;
12
use tokio::sync::OnceCell;
13
use uuid::Uuid;
14

            
15
mod concurrency;
16
mod create_tags;
17
mod delete_protocol;
18
mod exhausted;
19
mod list_amounts;
20
mod lock_protocol;
21
mod lock_protocol_create;
22
mod lock_timeout;
23
pub(in crate::command) mod lock_wait;
24
mod orphans;
25
mod owner_protocol;
26
mod padded_note;
27
mod read_faults;
28
mod rename_tag;
29
mod rollback;
30
mod script_write_back;
31
mod set_tag;
32
mod tag_helpers;
33
mod tags;
34
mod trim;
35
mod write_back_protocol;
36

            
37
pub(super) use lock_wait::{
38
    hold_key, key_is_free, release_after, rename, rename_in_turn, steer_deadlock, wait_for_blocked,
39
    wait_for_blocked_on, wait_for_key_waiter,
40
};
41

            
42
static USER: OnceCell<User> = OnceCell::const_new();
43

            
44
125
pub(super) async fn setup() {
45
250
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
46
125
        .await;
47
125
}
48

            
49
pub(super) struct Fixture {
50
    pub(super) user: &'static User,
51
    pub(super) commodity: Uuid,
52
    pub(super) accounts: [Uuid; 2],
53
}
54

            
55
125
pub(super) async fn fixture() -> anyhow::Result<Fixture> {
56
125
    let user = USER.get().ok_or_else(|| anyhow::anyhow!("no user"))?;
57
125
    user.commit().await?;
58
125
    let Some(CmdResult::String(id)) = CreateCommodity::new()
59
125
        .symbol("TST".to_string())
60
125
        .name("Test".to_string())
61
125
        .user_id(user.id)
62
125
        .run()
63
125
        .await?
64
    else {
65
        anyhow::bail!("commodity");
66
    };
67
125
    let commodity = Uuid::parse_str(&id)?;
68
125
    let mut accounts = [Uuid::nil(); 2];
69
125
    for (slot, name) in accounts.iter_mut().zip(["A1", "A2"]) {
70
250
        let Some(CmdResult::Entity(FinanceEntity::Account(account))) = CreateAccount::new()
71
250
            .name(name.to_string())
72
250
            .user_id(user.id)
73
250
            .run()
74
250
            .await?
75
        else {
76
            anyhow::bail!("account");
77
        };
78
250
        *slot = account.id;
79
    }
80
125
    Ok(Fixture {
81
125
        user,
82
125
        commodity,
83
125
        accounts,
84
125
    })
85
125
}
86

            
87
impl Fixture {
88
460
    fn splits(&self, tx_id: Uuid, amount: i64) -> Vec<FinanceEntity> {
89
460
        self.splits_on(tx_id, amount, self.accounts)
90
460
    }
91

            
92
465
    pub(super) fn splits_on(
93
465
        &self,
94
465
        tx_id: Uuid,
95
465
        amount: i64,
96
465
        accounts: [Uuid; 2],
97
465
    ) -> Vec<FinanceEntity> {
98
465
        [(accounts[0], -amount), (accounts[1], amount)]
99
465
            .into_iter()
100
930
            .map(|(account_id, value_num)| {
101
930
                FinanceEntity::Split(Split {
102
930
                    id: Uuid::new_v4(),
103
930
                    tx_id,
104
930
                    account_id,
105
930
                    commodity_id: self.commodity,
106
930
                    value_num,
107
930
                    value_denom: 1,
108
930
                    reconcile_state: None,
109
930
                    reconcile_date: None,
110
930
                    lot_id: None,
111
930
                })
112
930
            })
113
            .collect()
114
465
    }
115

            
116
279
    pub(super) async fn create_tx(&self, note: Option<&str>) -> anyhow::Result<Uuid> {
117
279
        let tx_id = Uuid::new_v4();
118
279
        let now = Utc::now();
119
279
        let mut cmd = CreateTransaction::new()
120
279
            .user_id(self.user.id)
121
279
            .splits(self.splits(tx_id, 100))
122
279
            .id(tx_id)
123
279
            .post_date(now)
124
279
            .enter_date(now);
125
279
        if let Some(note) = note {
126
11
            cmd = cmd.note(note.to_string());
127
268
        }
128
279
        cmd.run().await?;
129
279
        Ok(tx_id)
130
279
    }
131

            
132
258
    pub(super) async fn tx_tags(&self, tx_id: Uuid) -> anyhow::Result<Vec<(String, String)>> {
133
258
        let mut conn = self.user.get_connection().await?;
134
258
        let mut tags: Vec<_> = sqlx::query_file!("sql/select/tags/by_transaction.sql", tx_id)
135
258
            .fetch_all(&mut *conn)
136
258
            .await?
137
            .into_iter()
138
822
            .map(|row| (row.tag_name, row.tag_value))
139
            .collect();
140
258
        tags.sort();
141
258
        Ok(tags)
142
258
    }
143

            
144
64
    pub(super) async fn split_ids(&self, tx_id: Uuid) -> anyhow::Result<Vec<Uuid>> {
145
64
        let mut conn = self.user.get_connection().await?;
146
64
        let mut ids: Vec<_> = sqlx::query_file!("sql/select/splits/by_transaction.sql", tx_id)
147
64
            .fetch_all(&mut *conn)
148
64
            .await?
149
            .into_iter()
150
118
            .map(|row| row.id)
151
            .collect();
152
64
        ids.sort();
153
64
        Ok(ids)
154
64
    }
155

            
156
49
    pub(super) async fn split_tag_values(&self, split_id: Uuid) -> anyhow::Result<Vec<String>> {
157
49
        let mut conn = self.user.get_connection().await?;
158
49
        Ok(sqlx::query_file!("sql/select/tags/by_split.sql", split_id)
159
49
            .fetch_all(&mut *conn)
160
49
            .await?
161
            .into_iter()
162
176
            .map(|row| row.tag_value)
163
            .collect())
164
49
    }
165

            
166
25
    async fn tag_rows_with_value(&self, value: &str) -> anyhow::Result<usize> {
167
25
        let mut conn = self.user.get_connection().await?;
168
25
        Ok(sqlx::query_file!("sql/select/tags/all.sql")
169
25
            .fetch_all(&mut *conn)
170
25
            .await?
171
            .iter()
172
117
            .filter(|row| row.tag_value == value)
173
            .count())
174
25
    }
175

            
176
9
    async fn transaction_count(&self, tx_id: Uuid) -> anyhow::Result<usize> {
177
9
        let mut conn = self.user.get_connection().await?;
178
        Ok(
179
9
            sqlx::query_file!("sql/select/transactions/by_id.sql", tx_id)
180
9
                .fetch_all(&mut *conn)
181
9
                .await?
182
                .len(),
183
        )
184
9
    }
185

            
186
1
    async fn price_count(&self, tx_id: Uuid) -> anyhow::Result<usize> {
187
1
        let mut conn = self.user.get_connection().await?;
188
        Ok(
189
1
            sqlx::query_file!("sql/select/prices/by_transaction.sql", tx_id)
190
1
                .fetch_all(&mut *conn)
191
1
                .await?
192
                .len(),
193
        )
194
1
    }
195
}
196

            
197
2573
pub(super) fn tag(name: &str, value: &str) -> Tag {
198
2573
    Tag {
199
2573
        id: Uuid::new_v4(),
200
2573
        tag_name: name.to_string(),
201
2573
        tag_value: value.to_string(),
202
2573
        description: None,
203
2573
    }
204
2573
}
205

            
206
386
pub(super) fn tag_map(tags: &[(&str, &str)]) -> HashMap<String, FinanceEntity> {
207
386
    tags.iter()
208
2018
        .map(|(n, v)| (format!("{n}={v}"), FinanceEntity::Tag(tag(n, v))))
209
        .collect()
210
386
}
211

            
212
363
pub(super) fn pair(name: &str, value: &str) -> (String, String) {
213
363
    (name.to_string(), value.to_string())
214
363
}
215

            
216
100
pub(super) fn first_split_id(splits: &[FinanceEntity]) -> anyhow::Result<Uuid> {
217
100
    match splits.first() {
218
100
        Some(FinanceEntity::Split(s)) => Ok(s.id),
219
        _ => anyhow::bail!("split"),
220
    }
221
100
}
222

            
223
pub(super) const ROUNDS: usize = 8;
224

            
225
490
pub(super) fn shared_tags() -> Vec<(&'static str, &'static str)> {
226
490
    vec![("a", "1"), ("b", "2"), ("c", "3"), ("d", "4"), ("e", "5")]
227
490
}
228

            
229
166
fn assert_no_deadlock<T, E: std::fmt::Debug>(result: &Result<T, E>) {
230
166
    if let Err(err) = result {
231
79
        let text = format!("{err:?}");
232
79
        assert!(!text.contains("deadlock"), "{text}");
233
79
        assert!(!text.contains("foreign key"), "{text}");
234
87
    }
235
166
}
236

            
237
/// Many tags sorted before "zz" keep the delete busy between dropping the
238
/// links and locking "zz", which widens the window for the racing set.
239
64
pub(super) fn lead_in_tags() -> Vec<(&'static str, &'static str)> {
240
64
    vec![
241
64
        ("a0", "v"),
242
64
        ("a1", "v"),
243
64
        ("a2", "v"),
244
64
        ("a3", "v"),
245
64
        ("a4", "v"),
246
64
        ("a5", "v"),
247
64
        ("a6", "v"),
248
64
        ("a7", "v"),
249
64
        ("a8", "v"),
250
64
        ("a9", "v"),
251
64
        ("zz", "v"),
252
    ]
253
64
}