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
use std::borrow::Cow;
use futures_core::future::BoxFuture;
use crate::error::Error;
use crate::executor::Executor;
use crate::mssql::protocol::packet::PacketType;
use crate::mssql::protocol::sql_batch::SqlBatch;
use crate::mssql::{Mssql, MssqlConnection};
use crate::transaction::TransactionManager;
pub struct MssqlTransactionManager;
impl TransactionManager for MssqlTransactionManager {
type Database = Mssql;
fn begin(conn: &mut MssqlConnection) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(async move {
let depth = conn.stream.transaction_depth;
let query = if depth == 0 {
Cow::Borrowed("BEGIN TRAN ")
} else {
Cow::Owned(format!("SAVE TRAN _sqlx_savepoint_{}", depth))
};
conn.execute(&*query).await?;
conn.stream.transaction_depth = depth + 1;
Ok(())
})
}
fn commit(conn: &mut MssqlConnection) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(async move {
let depth = conn.stream.transaction_depth;
if depth > 0 {
if depth == 1 {
conn.execute("COMMIT TRAN").await?;
}
conn.stream.transaction_depth = depth - 1;
}
Ok(())
})
}
fn rollback(conn: &mut MssqlConnection) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(async move {
let depth = conn.stream.transaction_depth;
if depth > 0 {
let query = if depth == 1 {
Cow::Borrowed("ROLLBACK TRAN")
} else {
Cow::Owned(format!("ROLLBACK TRAN _sqlx_savepoint_{}", depth - 1))
};
conn.execute(&*query).await?;
conn.stream.transaction_depth = depth - 1;
}
Ok(())
})
}
fn start_rollback(conn: &mut MssqlConnection) {
let depth = conn.stream.transaction_depth;
if depth > 0 {
let query = if depth == 1 {
Cow::Borrowed("ROLLBACK TRAN")
} else {
Cow::Owned(format!("ROLLBACK TRAN _sqlx_savepoint_{}", depth - 1))
};
conn.stream.pending_done_count += 1;
conn.stream.write_packet(
PacketType::SqlBatch,
SqlBatch {
transaction_descriptor: conn.stream.transaction_descriptor,
sql: &*query,
},
);
conn.stream.transaction_depth = depth - 1;
}
}
}