sea-orm-ffi 0.1.3

Compatibility layer for Sea-ORM when crossing a Rust-to-Rust FFI boundary
Documentation
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use crate::{
	FfiTransaction,
	backend::FfiBackend,
	db_err::FfiDbErr,
	exec_result::FfiExecResult,
	proxy_row::{FfiOptionalProxyRow, FfiProxyRow},
	result::FfiResult,
	statement::FfiStatement,
	string::StringPtr,
	vec::VecPtr
};
use async_compat::Compat;
use async_ffi::{BorrowingFfiFuture, FutureExt as _};
use async_trait::async_trait;
use futures_util::future::{BoxFuture, FutureExt as _};
use sea_orm::{
	ConnectionTrait, DatabaseBackend, DatabaseTransaction, DbErr, ExecResult,
	QueryResult, Statement, TransactionTrait
};
use std::{ffi::c_void, future::Future};

/// Common safety documentation for [`ConnectionPtr`] functions.
macro_rules! doc_safety {
	() => {
		concat!(
			"\n",
			"# Safety\n",
			"\n",
			"This function is only safe to be called on the same side of the FFI ",
			"boundary that was used to construct the connection pointer using the ",
			"[`new`](ConnectionPtr::new) function, or any binary that was compiled ",
			"using the exact same dependencies and the exact same compiler and linker."
		)
	};
}

/// Unfortunately, [`TransactionTrait`] is not `dyn`-compatible. Therefore, we extract
/// the `begin()` function and add it to this trait explicitly.
pub trait SeaOrmConnection: ConnectionTrait + Send + Sync {
	fn begin(&self) -> BoxFuture<'_, Result<DatabaseTransaction, DbErr>>;
}

impl<T> SeaOrmConnection for T
where
	T: ConnectionTrait + TransactionTrait + Send + Sync
{
	fn begin(&self) -> BoxFuture<'_, Result<DatabaseTransaction, DbErr>> {
		TransactionTrait::begin(self)
	}
}

/// Boxed [`SeaOrmConnection`].
///
/// We cannot directly move a `*mut dyn SeaOrmConnection` over an FFI boundary as this
/// type is not FFI safe. It a so called _fat pointer_, which means that it doesn't
/// have a guaranteed memory layout, even if we ignore the `SeaOrmConnection` part of
/// the pointer.
///
/// Therefore, we pass pointers to this struct instead. While this is technically a
/// pointer to a pointer, the devil is, as always, in the detail: A pointer to this
/// struct is a _thin pointer_, so we get a _thin pointer_ to a _fat pointer_. And a
/// _thin pointer_ can be casted to and from a `*mut c_void`, and that is an FFI-safe
/// pointer. Dereferencing that pointer is of course only safe if the memory layout
/// is equivalent, so the part of the FFI boundary that did not create the pointer
/// must treat it is opaque.
struct BoxedConnection(Box<dyn SeaOrmConnection + Send + Sync>);

/// A pointer to `dyn SeaOrmConnection`.
///
/// This pointer must be treated as opaque on the side of the FFI boundary that did not
/// create the pointer.
#[repr(transparent)]
struct ConnectionPtr(*mut c_void);

impl ConnectionPtr {
	fn new(inner: Box<dyn SeaOrmConnection + Send + Sync>) -> Self {
		Self(Box::into_raw(Box::new(BoxedConnection(inner))) as _)
	}

	/// Access the data stored in this pointer
	#[doc = doc_safety!()]
	unsafe fn get(&self) -> &(dyn SeaOrmConnection + Send + Sync) {
		let ptr: *mut BoxedConnection = self.0.cast();
		&*(&*ptr).0
	}

	/// Return the inner type this pointer points to.
	#[doc = doc_safety!()]
	#[allow(clippy::wrong_self_convention)] // well, `Drop` only gives `&mut Self`
	unsafe fn into_inner(&mut self) -> Box<dyn SeaOrmConnection + Send + Sync> {
		let ptr: *mut BoxedConnection = self.0.cast();
		(*Box::from_raw(ptr)).0
	}
}

/// The FFI callback type that is called when an [`FfiConnection`] is [drop]ped.
type DropConnection = extern "C" fn(&mut ConnectionPtr);

/// Drop the connection that this pointer points to.
#[doc = doc_safety!()]
extern "C" fn drop_connection(ptr: &mut ConnectionPtr) {
	drop(unsafe { ptr.into_inner() });
}

/// The FFI callback type that is called when
/// [`begin()`](FfiConnection::begin)
/// is called on [`FfiConnection`].
type BeginTransaction =
	extern "C" fn(
		&ConnectionPtr
	) -> BorrowingFfiFuture<'_, FfiResult<FfiTransaction, FfiDbErr>>;

/// FFI callback for [`begin()`](FfiConnection::begin).
#[doc = doc_safety!()]
extern "C" fn begin_transaction(
	ptr: &ConnectionPtr
) -> BorrowingFfiFuture<'_, FfiResult<FfiTransaction, FfiDbErr>> {
	let conn = unsafe { ptr.get() };
	Compat::new(async move {
		conn.begin()
			.await
			.map(FfiTransaction::new)
			.map_err(Into::into)
			.into()
	})
	.into_ffi()
}

/// The FFI callback type that is called when
/// [`get_database_backend()`](ConnectionTrait::get_database_backend)
/// is called on [`FfiConnection`].
type GetDatabaseBackend<Ptr> = extern "C" fn(&Ptr) -> FfiBackend;

/// FFI callback for [`get_database_backend()`](ConnectionTrait::get_database_backend).
#[doc = doc_safety!()]
extern "C" fn get_database_backend(ptr: &ConnectionPtr) -> FfiBackend {
	unsafe { ptr.get() }.get_database_backend().into()
}

/// The FFI callback type that is called when
/// [`execute()`](ConnectionTrait::execute)
/// is called on [`FfiConnection`].
type Execute<Ptr> =
	extern "C" fn(
		&Ptr,
		FfiStatement
	) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>>;

/// FFI callback implementation for [`query_one()`](ConnectionTrait::query_one).
pub(crate) fn execute_impl<C>(
	conn: &C,
	stmt: FfiStatement
) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>>
where
	C: ConnectionTrait + Send + Sync + ?Sized
{
	Compat::new(async move {
		conn.execute(stmt.into())
			.await
			.map(|exec_result| {
				FfiExecResult::new(conn.get_database_backend(), exec_result)
			})
			.map_err(Into::into)
			.into()
	})
	.into_ffi()
}

/// FFI callback for [`execute()`](ConnectionTrait::execute).
#[doc = doc_safety!()]
extern "C" fn execute(
	ptr: &ConnectionPtr,
	stmt: FfiStatement
) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>> {
	execute_impl(unsafe { ptr.get() }, stmt)
}

/// The FFI callback type that is called when
/// [`execute()`](ConnectionTrait::execute)
/// is called on [`FfiConnection`].
type ExecuteUnprepared<Ptr> =
	extern "C" fn(
		&Ptr,
		StringPtr
	) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>>;

/// FFI callback implementation for [`execute_unprepared()`](ConnectionTrait::execute_unprepared).
pub(crate) fn execute_unprepared_impl<C>(
	conn: &C,
	sql: StringPtr
) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>>
where
	C: ConnectionTrait + Send + Sync + ?Sized
{
	Compat::new(async move {
		conn.execute_unprepared(sql.as_str())
			.await
			.map(|exec_result| {
				FfiExecResult::new(conn.get_database_backend(), exec_result)
			})
			.map_err(Into::into)
			.into()
	})
	.into_ffi()
}

/// FFI callback for [`execute_unprepared()`](ConnectionTrait::execute_unprepared).
#[doc = doc_safety!()]
extern "C" fn execute_unprepared(
	ptr: &ConnectionPtr,
	sql: StringPtr
) -> BorrowingFfiFuture<'_, FfiResult<FfiExecResult, FfiDbErr>> {
	execute_unprepared_impl(unsafe { ptr.get() }, sql)
}

/// The FFI callback type that is called when
/// [`query_one()`](ConnectionTrait::query_one)
/// is called on [`FfiConnection`].
type QueryOne<Ptr> =
	extern "C" fn(
		&Ptr,
		FfiStatement
	) -> BorrowingFfiFuture<'_, FfiResult<FfiOptionalProxyRow, FfiDbErr>>;

/// FFI callback implementation for [`query_one()`](ConnectionTrait::query_one).
pub(crate) fn query_one_impl<C>(
	conn: &C,
	stmt: FfiStatement
) -> BorrowingFfiFuture<'_, FfiResult<FfiOptionalProxyRow, FfiDbErr>>
where
	C: ConnectionTrait + Send + Sync + ?Sized
{
	Compat::new(async move {
		conn.query_one(stmt.into())
			.await
			.map(Into::into)
			.map_err(Into::into)
			.into()
	})
	.into_ffi()
}

/// FFI callback for [`query_one()`](ConnectionTrait::query_one).
#[doc = doc_safety!()]
extern "C" fn query_one(
	ptr: &ConnectionPtr,
	stmt: FfiStatement
) -> BorrowingFfiFuture<'_, FfiResult<FfiOptionalProxyRow, FfiDbErr>> {
	query_one_impl(unsafe { ptr.get() }, stmt)
}

/// The FFI callback type that is called when
/// [`query_all()`](ConnectionTrait::query_all)
/// is called on [`FfiConnection`].
type QueryAll<Ptr> =
	extern "C" fn(
		&Ptr,
		FfiStatement
	) -> BorrowingFfiFuture<'_, FfiResult<VecPtr<FfiProxyRow>, FfiDbErr>>;

/// FFI callback implementation for [`query_all()`](ConnectionTrait::query_all).
pub(crate) fn query_all_impl<C>(
	conn: &C,
	stmt: FfiStatement
) -> BorrowingFfiFuture<'_, FfiResult<VecPtr<FfiProxyRow>, FfiDbErr>>
where
	C: ConnectionTrait + Send + Sync + ?Sized
{
	Compat::new(async move {
		conn.query_all(stmt.into())
			.await
			.map(|rows| {
				rows.into_iter()
					.map(Into::into)
					.collect::<Vec<FfiProxyRow>>()
					.into()
			})
			.map_err(Into::into)
			.into()
	})
	.into_ffi()
}

/// FFI callback for [`query_all()`](ConnectionTrait::query_all).
#[doc = doc_safety!()]
extern "C" fn query_all(
	ptr: &ConnectionPtr,
	stmt: FfiStatement
) -> BorrowingFfiFuture<'_, FfiResult<VecPtr<FfiProxyRow>, FfiDbErr>> {
	query_all_impl(unsafe { ptr.get() }, stmt)
}

/// The FFI callback type that is called when
/// [`is_mock_connection()`](ConnectionTrait::is_mock_connection)
/// is called on [`FfiConnection`].
type IsMockConnection<Ptr> = extern "C" fn(&Ptr) -> bool;

/// FFI callback for [`is_mock_connection()`](ConnectionTrait::is_mock_connection).
#[doc = doc_safety!()]
extern "C" fn is_mock_connection(ptr: &ConnectionPtr) -> bool {
	unsafe { ptr.get() }.is_mock_connection()
}

#[repr(C)]
pub(crate) struct ConnectionVTable<Ptr> {
	pub(crate) backend: GetDatabaseBackend<Ptr>,
	pub(crate) execute: Execute<Ptr>,
	pub(crate) execute_unprepared: ExecuteUnprepared<Ptr>,
	pub(crate) query_one: QueryOne<Ptr>,
	pub(crate) query_all: QueryAll<Ptr>,
	pub(crate) is_mock_connection: IsMockConnection<Ptr>
}

/// An FFI-safe implementation of [`sea-orm`'s](sea_orm) [`ConnectionTrait`].
///
/// See the [crate level documentation](crate) for more details.
#[repr(C)]
pub struct FfiConnection {
	ptr: ConnectionPtr,
	drop: DropConnection,
	begin: BeginTransaction,
	vtable: ConnectionVTable<ConnectionPtr>
}

impl FfiConnection {
	pub fn new(inner: Box<dyn SeaOrmConnection + Send + Sync>) -> Self {
		Self {
			ptr: ConnectionPtr::new(inner),
			drop: drop_connection,
			begin: begin_transaction,
			vtable: ConnectionVTable {
				backend: get_database_backend,
				execute,
				execute_unprepared,
				query_one,
				query_all,
				is_mock_connection
			}
		}
	}

	pub fn begin(
		&self
	) -> impl Future<Output = Result<FfiTransaction, DbErr>> + Send + '_ {
		(self.begin)(&self.ptr).map(|res| res.into_result().map_err(Into::into))
	}
}

impl Drop for FfiConnection {
	fn drop(&mut self) {
		(self.drop)(&mut self.ptr)
	}
}

// Safety: The Box'ed `dyn Connection` has `+ Send` and `+ Sync` bounds,
// and the other types are just extern "C" fn pointers.
unsafe impl Send for ConnectionPtr {}
unsafe impl Sync for ConnectionPtr {}
unsafe impl<Ptr> Send for ConnectionVTable<Ptr> {}
unsafe impl<Ptr> Sync for ConnectionVTable<Ptr> {}
unsafe impl Send for FfiConnection {}
unsafe impl Sync for FfiConnection {}

impl<Ptr> ConnectionVTable<Ptr> {
	pub(crate) fn get_database_backend(&self, ptr: &Ptr) -> DatabaseBackend {
		(self.backend)(ptr).into()
	}

	pub(crate) async fn execute(
		&self,
		ptr: &Ptr,
		stmt: Statement
	) -> Result<ExecResult, DbErr> {
		(self.execute)(ptr, stmt.into())
			.await
			.map(Into::into)
			.map_err(Into::into)
			.into()
	}

	pub(crate) async fn execute_unprepared(
		&self,
		ptr: &Ptr,
		sql: &str
	) -> Result<ExecResult, DbErr> {
		// TODO we could introduce a StrPtr and not allocate here
		//      but I assume the number of calls to unprepared statements is quite low
		let sql: String = sql.into();

		(self.execute_unprepared)(ptr, sql.into())
			.await
			.map(Into::into)
			.map_err(Into::into)
			.into()
	}

	pub(crate) async fn query_one(
		&self,
		ptr: &Ptr,
		stmt: Statement
	) -> Result<Option<QueryResult>, DbErr> {
		(self.query_one)(ptr, stmt.into())
			.await
			.map(Into::into)
			.map_err(Into::into)
			.into()
	}

	pub(crate) async fn query_all(
		&self,
		ptr: &Ptr,
		stmt: Statement
	) -> Result<Vec<QueryResult>, DbErr> {
		(self.query_all)(ptr, stmt.into())
			.await
			.map(|rows| rows.into_vec().into_iter().map(Into::into).collect())
			.map_err(Into::into)
			.into()
	}

	pub(crate) fn is_mock_connection(&self, ptr: &Ptr) -> bool {
		(self.is_mock_connection)(ptr)
	}
}

#[async_trait]
impl ConnectionTrait for FfiConnection {
	fn get_database_backend(&self) -> DatabaseBackend {
		self.vtable.get_database_backend(&self.ptr)
	}

	async fn execute(&self, stmt: Statement) -> Result<ExecResult, DbErr> {
		self.vtable.execute(&self.ptr, stmt).await
	}

	async fn execute_unprepared(&self, sql: &str) -> Result<ExecResult, DbErr> {
		self.vtable.execute_unprepared(&self.ptr, sql).await
	}

	async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, DbErr> {
		self.vtable.query_one(&self.ptr, stmt).await
	}

	async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, DbErr> {
		self.vtable.query_all(&self.ptr, stmt).await
	}

	fn is_mock_connection(&self) -> bool {
		self.vtable.is_mock_connection(&self.ptr)
	}
}