1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use crate::sqlite::SqliteConnection;

/// Sqlite transaction wrapper.
///
/// Transactions are automatically rolled back if this struct object is dropped and
/// the transaction was not committed.
pub struct Transaction<'a> {
    connection: &'a SqliteConnection,
    // An active transaction is one that has yet to be committed or rolled back.
    is_active: bool,
}

impl<'a> Transaction<'a> {
    const BEGIN_TRANSACTION: &'static str = "BEGIN TRANSACTION";
    const COMMIT_TRANSACTION: &'static str = "COMMIT TRANSACTION";
    const ROLLBACK_TRANSACTION: &'static str = "ROLLBACK TRANSACTION";

    /// Begin a new transaction.
    pub fn begin(connection: &'a SqliteConnection) -> Result<Self, sqlite::Error> {
        connection.execute(Self::BEGIN_TRANSACTION)?;
        Ok(Self {
            connection,
            is_active: true,
        })
    }

    /// Commit the transaction.
    pub fn commit(mut self) -> Result<(), sqlite::Error> {
        self.execute(Self::COMMIT_TRANSACTION)
    }

    /// Rollback the transaction.
    pub fn rollback(mut self) -> Result<(), sqlite::Error> {
        self.execute(Self::ROLLBACK_TRANSACTION)
    }

    fn execute(&mut self, command: &str) -> Result<(), sqlite::Error> {
        if self.is_active {
            self.is_active = false;
            self.connection.execute(command)?;
        }
        Ok(())
    }
}

impl Drop for Transaction<'_> {
    fn drop(&mut self) {
        // Unwrap should not happen here, otherwise it would mean that we have not handled
        // correctly the transaction "active" state or that the connection was closed.
        self.execute(Self::ROLLBACK_TRANSACTION).unwrap();
    }
}

#[cfg(test)]
mod tests {
    use anyhow::anyhow;
    use sqlite::Connection;

    use mithril_common::StdResult;

    use crate::sqlite::ConnectionExtensions;

    use super::*;

    fn init_database() -> SqliteConnection {
        let connection = Connection::open_thread_safe(":memory:").unwrap();
        connection
            .execute("create table query_test(text_data text not null primary key);")
            .unwrap();

        connection
    }

    fn get_number_of_rows(connection: &SqliteConnection) -> i64 {
        connection
            .query_single_cell("select count(*) from query_test", &[])
            .unwrap()
    }

    #[test]
    fn test_commit() {
        let connection = init_database();

        assert_eq!(0, get_number_of_rows(&connection));
        {
            let transaction = Transaction::begin(&connection).unwrap();
            connection
                .execute("insert into query_test(text_data) values ('row 1')")
                .unwrap();
            transaction.commit().unwrap();
        }
        assert_eq!(1, get_number_of_rows(&connection));
    }

    #[test]
    fn test_rollback() {
        let connection = init_database();

        assert_eq!(0, get_number_of_rows(&connection));
        {
            let transaction = Transaction::begin(&connection).unwrap();
            connection
                .execute("insert into query_test(text_data) values ('row 1')")
                .unwrap();
            transaction.rollback().unwrap();
        }
        assert_eq!(0, get_number_of_rows(&connection));
    }

    #[test]
    fn test_auto_rollback_when_dropping() {
        let connection = init_database();

        assert_eq!(0, get_number_of_rows(&connection));
        {
            let _transaction = Transaction::begin(&connection).unwrap();
            connection
                .execute("insert into query_test(text_data) values ('row 1')")
                .unwrap();
        }
        assert_eq!(0, get_number_of_rows(&connection));
    }

    #[test]
    fn test_auto_rollback_when_dropping_because_of_an_error() {
        fn failing_function() -> StdResult<()> {
            Err(anyhow!("This is an error"))
        }
        fn failing_function_that_insert_data(connection: &SqliteConnection) -> StdResult<()> {
            let transaction = Transaction::begin(connection).unwrap();
            connection
                .execute("insert into query_test(text_data) values ('row 1')")
                .unwrap();
            failing_function()?;
            transaction.commit().unwrap();
            Ok(())
        }

        let connection = init_database();

        assert_eq!(0, get_number_of_rows(&connection));
        let _err = failing_function_that_insert_data(&connection).unwrap_err();
        assert_eq!(0, get_number_of_rows(&connection));
    }

    #[test]
    fn test_drop_dont_panic_if_previous_commit_failed() {
        let connection = init_database();

        {
            let transaction = Transaction::begin(&connection).unwrap();
            connection
                .execute("insert into query_test(text_data) values ('row 1')")
                .unwrap();

            // Commiting make the transaction inactive thus make next operation fail
            connection.execute(Transaction::COMMIT_TRANSACTION).unwrap();
            transaction.commit().expect_err("Commit should have fail");

            // When going out of scope, drop is called and should not panic
        }
    }

    #[test]
    fn test_drop_dont_panic_if_previous_rollback_failed() {
        let connection = init_database();

        {
            let transaction = Transaction::begin(&connection).unwrap();
            connection
                .execute("insert into query_test(text_data) values ('row 1')")
                .unwrap();

            // Commiting make the transaction inactive thus make next operation fail
            connection.execute(Transaction::COMMIT_TRANSACTION).unwrap();
            transaction
                .rollback()
                .expect_err("Rollback should have fail");

            // When going out of scope, drop is called and should not panic
        }
    }
}