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
use std::ptr;

use futures_core::future::BoxFuture;
use libsqlite3_sys::{sqlite3_exec, SQLITE_OK};

use crate::error::Error;
use crate::executor::Executor;
use crate::sqlite::{Sqlite, SqliteConnection, SqliteError};
use crate::transaction::{
    begin_ansi_transaction_sql, commit_ansi_transaction_sql, rollback_ansi_transaction_sql,
    TransactionManager,
};

/// Implementation of [`TransactionManager`] for SQLite.
pub struct SqliteTransactionManager;

impl TransactionManager for SqliteTransactionManager {
    type Database = Sqlite;

    fn begin(conn: &mut SqliteConnection) -> BoxFuture<'_, Result<(), Error>> {
        Box::pin(async move {
            let depth = conn.transaction_depth;

            conn.execute(&*begin_ansi_transaction_sql(depth)).await?;
            conn.transaction_depth = depth + 1;

            Ok(())
        })
    }

    fn commit(conn: &mut SqliteConnection) -> BoxFuture<'_, Result<(), Error>> {
        Box::pin(async move {
            let depth = conn.transaction_depth;

            if depth > 0 {
                conn.execute(&*commit_ansi_transaction_sql(depth)).await?;
                conn.transaction_depth = depth - 1;
            }

            Ok(())
        })
    }

    fn rollback(conn: &mut SqliteConnection) -> BoxFuture<'_, Result<(), Error>> {
        Box::pin(async move {
            let depth = conn.transaction_depth;

            if depth > 0 {
                conn.execute(&*rollback_ansi_transaction_sql(depth)).await?;
                conn.transaction_depth = depth - 1;
            }

            Ok(())
        })
    }

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

        if depth > 0 {
            let query = rollback_ansi_transaction_sql(depth);
            let mut z_query = String::with_capacity(query.len() + 1);
            z_query.push_str(&query);
            z_query.push('\0');

            unsafe {
                // NOTE: this is a direct execution as a ROLLBACK is unlikely to block
                //       for any amount of time
                let status = sqlite3_exec(
                    conn.handle.as_ptr(),
                    z_query.as_ptr() as _,
                    None,
                    ptr::null_mut(),
                    ptr::null_mut(),
                );

                if status != SQLITE_OK {
                    panic!(
                        "error occurred while dropping a transaction: {}",
                        SqliteError::new(conn.handle.as_ptr())
                    );
                }
            }

            conn.transaction_depth = depth - 1;
        }
    }
}