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

use cdbc::error::Error;
use cdbc::executor::Executor;
use crate::connection::Waiting;
use crate::protocol::text::Query;
use crate::{MySql, MySqlConnection};
use cdbc::transaction::{
    begin_ansi_transaction_sql, commit_ansi_transaction_sql, rollback_ansi_transaction_sql,
    TransactionManager,
};

/// Implementation of [`TransactionManager`] for MySQL.
pub struct MySqlTransactionManager;

impl TransactionManager for MySqlTransactionManager {
    type Database = MySql;

    fn begin(conn: &mut MySqlConnection) ->  Result<(), Error> {
            let depth = conn.transaction_depth;
            conn.execute(&*begin_ansi_transaction_sql(depth))?;
            conn.transaction_depth = depth + 1;

            Ok(())
    }

    fn commit(conn: &mut MySqlConnection) ->  Result<(), Error> {
            let depth = conn.transaction_depth;
            if depth > 0 {
                conn.execute(&*commit_ansi_transaction_sql(depth))?;
                conn.transaction_depth = depth - 1;
            }
            Ok(())
    }

    fn rollback(conn: &mut MySqlConnection) ->  Result<(), Error> {
            let depth = conn.transaction_depth;
            if depth > 0 {
                conn.execute(&*rollback_ansi_transaction_sql(depth))?;
                conn.transaction_depth = depth - 1;
            }
            Ok(())
    }

    fn start_rollback(conn: &mut MySqlConnection) {
        let depth = conn.transaction_depth;

        if depth > 0 {
            conn.stream.waiting.push_back(Waiting::Result);
            conn.stream.sequence_id = 0;
            conn.stream
                .write_packet(Query(&*rollback_ansi_transaction_sql(depth)));

            conn.transaction_depth = depth - 1;
        }
    }
}