antfly_embedded/
transactions.rs1use antfly_embedded_sys as sys;
20
21use crate::db::Database;
22use crate::error::Result;
23use crate::ffi::{borrow_slice, check};
24use crate::options::WriteIntent;
25
26pub type TxnId = [u8; 16];
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum TxnStatus {
32 Pending,
33 Committed,
34 Aborted,
35}
36
37impl TxnStatus {
38 fn from_u8(value: u8) -> TxnStatus {
39 match value {
40 1 => TxnStatus::Committed,
41 2 => TxnStatus::Aborted,
42 _ => TxnStatus::Pending,
43 }
44 }
45
46 fn as_u8(self) -> u8 {
47 match self {
48 TxnStatus::Pending => sys::ANTFLY_TXN_PENDING,
49 TxnStatus::Committed => sys::ANTFLY_TXN_COMMITTED,
50 TxnStatus::Aborted => sys::ANTFLY_TXN_ABORTED,
51 }
52 }
53}
54
55impl Database {
56 pub fn begin_transaction(
58 &self,
59 txn_id: TxnId,
60 timestamp_ns: u64,
61 participants: &[&str],
62 ) -> Result<()> {
63 self.with_handle(|handle| {
64 let c_participants: Vec<sys::antfly_slice> = participants
65 .iter()
66 .map(|p| borrow_slice(p.as_bytes()))
67 .collect();
68 let ptr = if c_participants.is_empty() {
69 std::ptr::null()
70 } else {
71 c_participants.as_ptr()
72 };
73 check(unsafe {
74 sys::antfly_db_begin_transaction_with_id(
75 handle,
76 &txn_id,
77 timestamp_ns,
78 ptr,
79 c_participants.len(),
80 )
81 })
82 })
83 }
84
85 pub fn write_transaction(&self, txn_id: TxnId, writes: &[WriteIntent]) -> Result<()> {
87 self.with_handle(|handle| {
88 let c_writes: Vec<sys::antfly_write_intent> = writes
89 .iter()
90 .map(|w| sys::antfly_write_intent {
91 key: borrow_slice(&w.key),
92 value: borrow_slice(&w.value),
93 is_delete: w.delete,
94 })
95 .collect();
96 let ptr = if c_writes.is_empty() {
97 std::ptr::null()
98 } else {
99 c_writes.as_ptr()
100 };
101 check(unsafe {
102 sys::antfly_db_write_transaction(
103 handle,
104 &txn_id,
105 ptr,
106 c_writes.len(),
107 std::ptr::null(),
108 0,
109 )
110 })
111 })
112 }
113
114 pub fn resolve_transaction(
116 &self,
117 txn_id: TxnId,
118 status: TxnStatus,
119 commit_version: u64,
120 ) -> Result<()> {
121 self.with_handle(|handle| {
122 check(unsafe {
123 sys::antfly_db_resolve_intents(handle, &txn_id, status.as_u8(), commit_version)
124 })
125 })
126 }
127
128 pub fn transaction_status(&self, txn_id: TxnId) -> Result<TxnStatus> {
130 self.with_handle(|handle| {
131 let mut status: u8 = 0;
132 check(unsafe { sys::antfly_db_get_transaction_status(handle, &txn_id, &mut status) })?;
133 Ok(TxnStatus::from_u8(status))
134 })
135 }
136
137 pub fn commit_version(&self, txn_id: TxnId) -> Result<u64> {
139 self.with_handle(|handle| {
140 let mut version: u64 = 0;
141 check(unsafe { sys::antfly_db_get_commit_version(handle, &txn_id, &mut version) })?;
142 Ok(version)
143 })
144 }
145}