1
use super::super::transaction_edit_tests::wait_for_blocked_on;
2
use super::*;
3
use crate::account_state::STALE_ACCOUNT;
4
use sqlx::Connection;
5

            
6
#[local_db_sqlx_test]
7
async fn test_a_change_committed_while_the_edit_waits_makes_it_stale(
8
    pool: PgPool,
9
) -> Result<(), anyhow::Error> {
10
    let fx = fixture().await?;
11
    let account = fx.account("Cash", None).await?;
12
    let loaded = fx.revision(account).await?;
13
    let mut conn = fx.user.get_connection().await?;
14
    let mut blocker = conn.begin().await?;
15
    lock_hierarchy(&mut blocker, fx.user.id).await?;
16

            
17
    let edit = fx.edit(account, "Other", None, vec![], loaded);
18
1
    let change = async {
19
1
        wait_for_blocked_on(&mut blocker, 1).await?;
20
1
        fx.set_tag(account, "type", "asset").await?;
21
1
        blocker.commit().await?;
22
1
        anyhow::Ok(())
23
1
    };
24
    let (edited, changed) = tokio::join!(edit, change);
25
    changed?;
26

            
27
    assert!(
28
        matches!(&edited, Err(CmdError::Args(m)) if m == STALE_ACCOUNT),
29
        "{edited:?}"
30
    );
31
    assert_eq!(
32
        pairs(&fx.stored(account).await?),
33
        [("name", "Cash"), ("type", "asset")]
34
    );
35
}
36

            
37
#[local_db_sqlx_test]
38
async fn test_opposing_edits_leave_no_cycle(pool: PgPool) -> Result<(), anyhow::Error> {
39
    let fx = fixture().await?;
40
    let a = fx.account("A", None).await?;
41
    let b = fx.account("B", None).await?;
42
    let (rev_a, rev_b) = (fx.revision(a).await?, fx.revision(b).await?);
43
    let mut conn = fx.user.get_connection().await?;
44
    let mut blocker = conn.begin().await?;
45
    lock_hierarchy(&mut blocker, fx.user.id).await?;
46

            
47
    let a_under_b = fx.edit(a, "A", Some(b), vec![], rev_a);
48
    let b_under_a = fx.edit(b, "B", Some(a), vec![], rev_b);
49
1
    let release = async {
50
1
        let waited = wait_for_blocked_on(&mut blocker, 2).await;
51
1
        blocker.commit().await?;
52
1
        waited
53
1
    };
54
    let (first, second, released) = tokio::join!(a_under_b, b_under_a, release);
55
    released?;
56

            
57
    assert_eq!(
58
        [first.is_ok(), second.is_ok()]
59
            .iter()
60
2
            .filter(|ok| **ok)
61
            .count(),
62
        1
63
    );
64
    let parents = [fx.stored(a).await?.parent, fx.stored(b).await?.parent];
65
    assert_eq!(
66
2
        parents.iter().filter(|p| p.is_some()).count(),
67
        1,
68
        "{parents:?}"
69
    );
70
}
71

            
72
#[local_db_sqlx_test]
73
async fn test_a_parent_deleted_while_the_edit_waits_is_parent_gone(
74
    pool: PgPool,
75
) -> Result<(), anyhow::Error> {
76
    let fx = fixture().await?;
77
    let parent = fx.account("Parent", None).await?;
78
    let account = fx.account("Cash", None).await?;
79
    let loaded = fx.revision(account).await?;
80
    let mut conn = fx.user.get_connection().await?;
81
    let mut blocker = conn.begin().await?;
82
    lock_hierarchy(&mut blocker, fx.user.id).await?;
83

            
84
    let edit = fx.edit(account, "Cash", Some(parent), vec![], loaded);
85
1
    let delete = async {
86
1
        wait_for_blocked_on(&mut blocker, 1).await?;
87
1
        sqlx::query("DELETE FROM account_tags WHERE account_id = $1")
88
1
            .bind(parent)
89
1
            .execute(&mut *blocker)
90
1
            .await?;
91
1
        sqlx::query("DELETE FROM accounts WHERE id = $1")
92
1
            .bind(parent)
93
1
            .execute(&mut *blocker)
94
1
            .await?;
95
1
        blocker.commit().await?;
96
1
        anyhow::Ok(())
97
1
    };
98
    let (edited, deleted) = tokio::join!(edit, delete);
99
    deleted?;
100

            
101
    assert!(
102
        matches!(&edited, Err(CmdError::ParentGone(id)) if *id == parent),
103
        "{edited:?}"
104
    );
105
    assert_eq!(fx.stored(account).await?.parent, None);
106
}
107

            
108
/// The tag set changes between the pre-lock read and the account row lock:
109
/// the attempt retries and the next one sees the changed revision.
110
#[local_db_sqlx_test]
111
async fn test_a_tag_linked_while_the_edit_waits_for_the_row_retries_into_stale(
112
    pool: PgPool,
113
) -> Result<(), anyhow::Error> {
114
    let fx = fixture().await?;
115
    let account = fx.account("Cash", None).await?;
116
    let loaded = fx.revision(account).await?;
117
    let mut conn = fx.user.get_connection().await?;
118
    let mut blocker = conn.begin().await?;
119
    sqlx::query("SELECT id FROM accounts WHERE id = $1 FOR NO KEY UPDATE")
120
        .bind(account)
121
        .fetch_one(&mut *blocker)
122
        .await?;
123

            
124
    let edit = fx.edit(account, "Cash", None, vec![], loaded);
125
1
    let link = async {
126
1
        wait_for_blocked_on(&mut blocker, 1).await?;
127
1
        let tag_id = Uuid::new_v4();
128
1
        sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, 'late', 'x')")
129
1
            .bind(tag_id)
130
1
            .execute(&mut *blocker)
131
1
            .await?;
132
1
        sqlx::query("INSERT INTO account_tags (account_id, tag_id) VALUES ($1, $2)")
133
1
            .bind(account)
134
1
            .bind(tag_id)
135
1
            .execute(&mut *blocker)
136
1
            .await?;
137
1
        blocker.commit().await?;
138
1
        anyhow::Ok(())
139
1
    };
140
    let (edited, linked) = tokio::join!(edit, link);
141
    linked?;
142

            
143
    assert!(
144
        matches!(&edited, Err(CmdError::Args(m)) if m == STALE_ACCOUNT),
145
        "{edited:?}"
146
    );
147
    assert_eq!(
148
        pairs(&fx.stored(account).await?),
149
        [("late", "x"), ("name", "Cash")]
150
    );
151
}