sqlite3_ext/mutex.rs
1use crate::{ffi, Connection};
2use std::ops::Deref;
3
4impl Connection {
5 /// Locks the mutex associated with this database connection. If multiple SQLite APIs need to
6 /// be used and there is a chance that this Connection may be used from multiple threads, this
7 /// method should be used to lock the Connection to the calling thread. The returned mutex
8 /// guard will unlock the mutex when it is dropped, and derefs to the original connection.
9 ///
10 /// This method has no effect if SQLite is not operating in [serialized threading
11 /// mode](https://www.sqlite.org/threadsafe.html).
12 pub fn lock(&self) -> SQLiteMutexGuard<'_, Connection> {
13 let mutex = unsafe { ffi::sqlite3_db_mutex(self.as_mut_ptr()) };
14 unsafe { ffi::sqlite3_mutex_enter(mutex) };
15 SQLiteMutexGuard { mutex, data: self }
16 }
17}
18
19pub struct SQLiteMutexGuard<'a, T> {
20 mutex: *mut ffi::sqlite3_mutex,
21 data: &'a T,
22}
23
24impl<T> Drop for SQLiteMutexGuard<'_, T> {
25 fn drop(&mut self) {
26 unsafe { ffi::sqlite3_mutex_leave(self.mutex) }
27 }
28}
29
30impl<T> Deref for SQLiteMutexGuard<'_, T> {
31 type Target = T;
32
33 fn deref(&self) -> &T {
34 self.data
35 }
36}