Skip to main content

sea_orm_ffi/
transaction.rs

1use crate::{
2	backend::FfiBackend,
3	connection::{
4		ConnectionVTable, execute_impl, execute_unprepared_impl, query_all_impl,
5		query_one_impl
6	},
7	db_err::FfiDbErr,
8	exec_result::FfiExecResult,
9	proxy_row::{FfiOptionalProxyRow, FfiProxyRow},
10	result::FfiResult,
11	statement::FfiStatement,
12	string::StringPtr,
13	vec::VecPtr
14};
15use async_compat::Compat;
16use async_ffi::{BorrowingFfiFuture, FfiFuture, FutureExt};
17use async_trait::async_trait;
18use futures_util::future::FutureExt as _;
19use sea_orm::{
20	ConnectionTrait, DatabaseBackend, DatabaseTransaction, DbErr, ExecResult,
21	QueryResult, Statement
22};
23use std::{ffi::c_void, future::Future, mem::ManuallyDrop};
24
25/// Common safety documentation for [`TransactionPtr`] functions.
26macro_rules! doc_safety {
27	() => {
28		concat!(
29			"\n",
30			"# Safety\n",
31			"\n",
32			"This function is only safe to be called on the same side of the FFI ",
33			"boundary that was used to construct the connection pointer using the ",
34			"[`new`](TransactionPtr::new) function, or any binary that was compiled ",
35			"using the exact same dependencies and the exact same compiler and linker."
36		)
37	};
38}
39
40/// A pointer to [`DatabaseTransaction`].
41///
42/// This pointer must be treated as opaque on the side of the FFI boundary that did not
43/// create the pointer.
44#[repr(transparent)]
45struct TransactionPtr(*mut c_void);
46
47impl TransactionPtr {
48	fn new(inner: Box<DatabaseTransaction>) -> Self {
49		Self(Box::into_raw(inner) as _)
50	}
51
52	/// Access the data stored in this pointer
53	#[doc = doc_safety!()]
54	unsafe fn get(&self) -> &DatabaseTransaction {
55		let ptr: *mut DatabaseTransaction = self.0.cast();
56		&*ptr
57	}
58
59	/// Return the inner type this pointer points to.
60	#[doc = doc_safety!()]
61	#[allow(clippy::wrong_self_convention)] // well, `Drop` only gives `&mut Self`
62	unsafe fn into_inner(&mut self) -> Box<DatabaseTransaction> {
63		let ptr: *mut DatabaseTransaction = self.0.cast();
64		Box::from_raw(ptr)
65	}
66}
67
68/// The FFI callback type that is called when an [`FfiTransaction`] is [drop]ped.
69type DropTransaction = extern "C" fn(&mut TransactionPtr);
70
71/// Drop the transaction that this pointer points to.
72#[doc = doc_safety!()]
73extern "C" fn drop_transaction(ptr: &mut TransactionPtr) {
74	drop(unsafe { ptr.into_inner() });
75}
76
77/// The FFI callback type that is called when
78/// [`commit()`](FfiTransaction::commit)
79/// is called on [`FfiTransaction`].
80type CommitTransaction =
81	extern "C" fn(&mut TransactionPtr) -> FfiFuture<FfiResult<(), FfiDbErr>>;
82
83/// FFI callback for [`commit()`](FfiTransaction::commit).
84#[doc = doc_safety!()]
85extern "C" fn commit_transaction(
86	ptr: &mut TransactionPtr
87) -> FfiFuture<FfiResult<(), FfiDbErr>> {
88	let conn = unsafe { ptr.into_inner() };
89	Compat::new(async move { conn.commit().await.map_err(Into::into).into() }).into_ffi()
90}
91
92/// FFI callback for [`rollback()`](FfiTransaction::rollback).
93#[doc = doc_safety!()]
94extern "C" fn rollback_transaction(
95	ptr: &mut TransactionPtr
96) -> FfiFuture<FfiResult<(), FfiDbErr>> {
97	let conn = unsafe { ptr.into_inner() };
98	Compat::new(async move { conn.rollback().await.map_err(Into::into).into() })
99		.into_ffi()
100}
101
102/// FFI callback for [`get_database_backend()`](ConnectionTrait::get_database_backend).
103#[doc = doc_safety!()]
104extern "C" fn get_database_backend(ptr: &TransactionPtr) -> FfiBackend {
105	unsafe { ptr.get() }.get_database_backend().into()
106}
107
108/// FFI callback for [`execute()`](ConnectionTrait::execute).
109#[doc = doc_safety!()]
110extern "C" fn execute(
111	ptr: &TransactionPtr,
112	stmt: FfiStatement
113) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>> {
114	execute_impl(unsafe { ptr.get() }, stmt)
115}
116
117/// FFI callback for [`execute_unprepared()`](ConnectionTrait::execute_unprepared).
118#[doc = doc_safety!()]
119extern "C" fn execute_unprepared(
120	ptr: &TransactionPtr,
121	sql: StringPtr
122) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>> {
123	execute_unprepared_impl(unsafe { ptr.get() }, sql)
124}
125
126/// FFI callback for [`query_one()`](ConnectionTrait::query_one).
127#[doc = doc_safety!()]
128extern "C" fn query_one(
129	ptr: &TransactionPtr,
130	stmt: FfiStatement
131) -> BorrowingFfiFuture<'_, FfiResult<FfiOptionalProxyRow, FfiDbErr>> {
132	query_one_impl(unsafe { ptr.get() }, stmt)
133}
134
135/// FFI callback for [`query_all()`](ConnectionTrait::query_all).
136#[doc = doc_safety!()]
137extern "C" fn query_all(
138	ptr: &TransactionPtr,
139	stmt: FfiStatement
140) -> BorrowingFfiFuture<'_, FfiResult<VecPtr<FfiProxyRow>, FfiDbErr>> {
141	query_all_impl(unsafe { ptr.get() }, stmt)
142}
143
144/// FFI callback for [`is_mock_connection()`](ConnectionTrait::is_mock_connection).
145#[doc = doc_safety!()]
146extern "C" fn is_mock_connection(ptr: &TransactionPtr) -> bool {
147	unsafe { ptr.get() }.is_mock_connection()
148}
149
150/// An FFI-safe implementation of [`sea-orm`'s](sea_orm) [`DatabaseTransaction`].
151///
152/// Note that there is no FFI-safe way to use
153/// [`TransactionTrait`](sea_orm::TransactionTrait). Use the [`FfiConnection::begin()`]
154/// or [`FfiConnection::transaction()`] methods instead.
155#[repr(C)]
156pub struct FfiTransaction {
157	ptr: TransactionPtr,
158	drop: DropTransaction,
159	commit: CommitTransaction,
160	rollback: CommitTransaction,
161	vtable: ConnectionVTable<TransactionPtr>
162}
163
164impl FfiTransaction {
165	pub(crate) fn new(inner: Box<DatabaseTransaction>) -> Self {
166		Self {
167			ptr: TransactionPtr::new(inner),
168			drop: drop_transaction,
169			commit: commit_transaction,
170			rollback: rollback_transaction,
171			vtable: ConnectionVTable {
172				backend: get_database_backend,
173				execute,
174				execute_unprepared,
175				query_one,
176				query_all,
177				is_mock_connection
178			}
179		}
180	}
181
182	pub fn commit(self) -> impl Future<Output = Result<(), DbErr>> + Send {
183		let mut this = ManuallyDrop::new(self);
184		(this.commit)(&mut this.ptr)
185			.map(|res: FfiResult<(), FfiDbErr>| res.into_result().map_err(Into::into))
186	}
187
188	pub fn rollback(self) -> impl Future<Output = Result<(), DbErr>> + Send {
189		let mut this = ManuallyDrop::new(self);
190		(this.commit)(&mut this.ptr)
191			.map(|res: FfiResult<(), FfiDbErr>| res.into_result().map_err(Into::into))
192	}
193}
194
195impl Drop for FfiTransaction {
196	fn drop(&mut self) {
197		(self.drop)(&mut self.ptr)
198	}
199}
200
201// Safety: The Box'ed `DatabaseTransaction` is `Send` and `Sync`,
202// and the other types are just extern "C" fn pointers.
203unsafe impl Send for TransactionPtr {}
204unsafe impl Sync for TransactionPtr {}
205unsafe impl Send for FfiTransaction {}
206unsafe impl Sync for FfiTransaction {}
207
208#[async_trait]
209impl ConnectionTrait for FfiTransaction {
210	fn get_database_backend(&self) -> DatabaseBackend {
211		self.vtable.get_database_backend(&self.ptr)
212	}
213
214	async fn execute(&self, stmt: Statement) -> Result<ExecResult, DbErr> {
215		self.vtable.execute(&self.ptr, stmt).await
216	}
217
218	async fn execute_unprepared(&self, sql: &str) -> Result<ExecResult, DbErr> {
219		self.vtable.execute_unprepared(&self.ptr, sql).await
220	}
221
222	async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, DbErr> {
223		self.vtable.query_one(&self.ptr, stmt).await
224	}
225
226	async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, DbErr> {
227		self.vtable.query_all(&self.ptr, stmt).await
228	}
229
230	fn is_mock_connection(&self) -> bool {
231		self.vtable.is_mock_connection(&self.ptr)
232	}
233}