Skip to main content

sqlx_ext/
database.rs

1use std::{
2    any::{Any, TypeId},
3    cell::RefCell,
4    collections::HashMap,
5    fmt::Display,
6    future::Future,
7    pin::Pin,
8    str::FromStr,
9    sync::{Arc, Mutex as StdMutex, OnceLock},
10    task::{Context, Poll},
11};
12
13use sqlx::{
14    Connection, Database as SqlxDatabase, Pool, Transaction as SqlxNativeTransaction,
15    pool::PoolOptions,
16};
17use tokio::sync::Mutex;
18
19type GlobalPools = HashMap<TypeId, Box<dyn Any + Send + Sync>>;
20static GLOBAL_POOLS: OnceLock<StdMutex<GlobalPools>> = OnceLock::new();
21thread_local! { static DB_OVERRIDE: RefCell<Option<Box<dyn Any>>> = const { RefCell::new(None) }; }
22
23#[derive(Debug, thiserror::Error)]
24pub enum DbError {
25    #[error("database pool is not initialized for this SQLx backend")]
26    PoolNotInitialized,
27    #[error("global database pool is already initialized for this SQLx backend")]
28    GlobalPoolAlreadyInitialized,
29    #[error(
30        "transaction handle leaked outside its scope; do not retain Transaction or captured scope handles"
31    )]
32    TransactionLeaked,
33    #[error("transaction is already closed")]
34    TransactionClosed,
35    #[error("invalid database connection options: {0}")]
36    ConnectionOptions(String),
37    #[error("the current scope belongs to a different SQLx database backend")]
38    BackendScopeMismatch,
39    #[error(transparent)]
40    Sqlx(#[from] sqlx::Error),
41}
42
43pub enum DatabaseHandle<DB: SqlxDatabase> {
44    Pool(Arc<Pool<DB>>),
45    Transaction(Arc<SqlxTransaction<DB>>),
46}
47pub enum ConnectionRef<DB: SqlxDatabase> {
48    Pool(Arc<Pool<DB>>),
49    Transaction(Arc<SqlxTransaction<DB>>),
50}
51
52pub struct Database<DB: SqlxDatabase> {
53    pool: Arc<Pool<DB>>,
54}
55
56impl<DB> Database<DB>
57where
58    DB: SqlxDatabase + 'static,
59    Pool<DB>: Send + Sync,
60    <DB::Connection as Connection>::Options: FromStr,
61    <<DB::Connection as Connection>::Options as FromStr>::Err: Display,
62{
63    pub async fn connect(url: &str) -> Result<Self, DbError> {
64        Ok(Self {
65            pool: Arc::new(
66                PoolOptions::new()
67                    .connect_with(
68                        url.parse::<<DB::Connection as Connection>::Options>()
69                            .map_err(|e| DbError::ConnectionOptions(e.to_string()))?,
70                    )
71                    .await?,
72            ),
73        })
74    }
75    pub async fn init(url: &str) -> Result<(), DbError> {
76        Self::set_global(Self::connect(url).await?)
77    }
78    pub fn from_pool(pool: Pool<DB>) -> Self {
79        Self {
80            pool: Arc::new(pool),
81        }
82    }
83    pub fn set_global(database: Self) -> Result<(), DbError> {
84        let pools = GLOBAL_POOLS.get_or_init(|| StdMutex::new(HashMap::new()));
85        let mut pools = pools.lock().expect("global pool lock poisoned");
86        if pools.contains_key(&TypeId::of::<DB>()) {
87            return Err(DbError::GlobalPoolAlreadyInitialized);
88        }
89        pools.insert(TypeId::of::<DB>(), Box::new(database.pool));
90        Ok(())
91    }
92    /// Removes this backend's global pool. Intended for tests and deliberate
93    /// reconfiguration; existing cloned `Database` handles remain usable.
94    pub fn reset_global() {
95        if let Some(pools) = GLOBAL_POOLS.get() {
96            if let Ok(mut pools) = pools.lock() {
97                pools.remove(&TypeId::of::<DB>());
98            }
99        }
100    }
101    pub fn global() -> Result<Self, DbError> {
102        Ok(Self {
103            pool: global_pool::<DB>()?,
104        })
105    }
106    pub fn pool(&self) -> &Pool<DB> {
107        self.pool.as_ref()
108    }
109    /// Runs a transaction using the pool installed by [`Self::init`] or
110    /// [`Self::set_global`]. This is the application-service entry point when
111    /// services and repositories must not carry a `Database` field.
112    pub async fn transaction_global<T, F>(f: F) -> Result<T, DbError>
113    where
114        F: FnOnce() -> Pin<Box<dyn Future<Output = Result<T, DbError>> + Send>> + Send,
115        T: Send,
116    {
117        Self::global()?.transaction(|_| f()).await
118    }
119    pub async fn transaction<T, F>(&self, f: F) -> Result<T, DbError>
120    where
121        F: for<'a> FnOnce(
122                &'a Transaction<DB>,
123            )
124                -> Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + 'a>>
125            + Send,
126        T: Send,
127    {
128        if let Some(tx) = current_transaction_override::<DB>()? {
129            return f(&Transaction { inner: tx }).await;
130        }
131        let shared = Arc::new(SqlxTransaction::new(self.pool.begin().await?));
132        let outcome = {
133            let public = Transaction {
134                inner: Arc::clone(&shared),
135            };
136            with_connection_override(DatabaseHandle::Transaction(Arc::clone(&shared)), f(&public))
137                .await
138        };
139        let inner = Arc::try_unwrap(shared).map_err(|_| DbError::TransactionLeaked)?;
140        let tx = inner.take()?;
141        match outcome {
142            Ok(value) => {
143                tx.commit().await?;
144                Ok(value)
145            }
146            Err(error) => {
147                let _ = tx.rollback().await;
148                Err(error)
149            }
150        }
151    }
152}
153
154fn global_pool<DB: SqlxDatabase + 'static>() -> Result<Arc<Pool<DB>>, DbError> {
155    GLOBAL_POOLS
156        .get()
157        .and_then(|pools| {
158            pools
159                .lock()
160                .ok()?
161                .get(&TypeId::of::<DB>())
162                .and_then(|pool| pool.downcast_ref::<Arc<Pool<DB>>>().cloned())
163        })
164        .ok_or(DbError::PoolNotInitialized)
165}
166pub fn current_connection<DB: SqlxDatabase + 'static>() -> Result<ConnectionRef<DB>, DbError> {
167    if let Some(handle) = current_override_handle::<DB>()? {
168        return Ok(match handle {
169            DatabaseHandle::Pool(pool) => ConnectionRef::Pool(pool),
170            DatabaseHandle::Transaction(tx) => ConnectionRef::Transaction(tx),
171        });
172    }
173    Ok(ConnectionRef::Pool(global_pool::<DB>()?))
174}
175fn current_override_handle<DB: SqlxDatabase + 'static>()
176-> Result<Option<DatabaseHandle<DB>>, DbError> {
177    DB_OVERRIDE.with(|slot| {
178        let slot = slot.borrow();
179        match slot.as_ref() {
180            None => Ok(None),
181            Some(handle) => handle
182                .downcast_ref::<DatabaseHandle<DB>>()
183                .cloned()
184                .map(Some)
185                .ok_or(DbError::BackendScopeMismatch),
186        }
187    })
188}
189fn current_transaction_override<DB: SqlxDatabase + 'static>()
190-> Result<Option<Arc<SqlxTransaction<DB>>>, DbError> {
191    Ok(match current_override_handle::<DB>()? {
192        Some(DatabaseHandle::Transaction(transaction)) => Some(transaction),
193        Some(DatabaseHandle::Pool(_)) | None => None,
194    })
195}
196struct ResetDbOverride(Option<Box<dyn Any>>);
197impl Drop for ResetDbOverride {
198    fn drop(&mut self) {
199        DB_OVERRIDE.with(|slot| {
200            slot.replace(self.0.take());
201        });
202    }
203}
204fn install_db_override<DB: SqlxDatabase + 'static>(handle: &DatabaseHandle<DB>) -> ResetDbOverride {
205    ResetDbOverride(DB_OVERRIDE.with(|slot| slot.replace(Some(Box::new(clone_handle(handle))))))
206}
207pub struct ScopedOverrideFuture<DB: SqlxDatabase, F> {
208    handle: Option<DatabaseHandle<DB>>,
209    future: Pin<Box<F>>,
210}
211impl<DB: SqlxDatabase + 'static, F: Future> Future for ScopedOverrideFuture<DB, F> {
212    type Output = F::Output;
213    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
214        let this = self.get_mut();
215        let result = if let Some(handle) = this.handle.as_ref() {
216            let _reset = install_db_override(handle);
217            this.future.as_mut().poll(cx)
218        } else {
219            this.future.as_mut().poll(cx)
220        };
221        if result.is_ready() {
222            this.handle = None;
223        }
224        result
225    }
226}
227pub fn with_connection_override<DB: SqlxDatabase + 'static, F: Future>(
228    handle: DatabaseHandle<DB>,
229    future: F,
230) -> ScopedOverrideFuture<DB, F> {
231    ScopedOverrideFuture {
232        handle: Some(handle),
233        future: Box::pin(future),
234    }
235}
236
237fn clone_handle<DB: SqlxDatabase>(handle: &DatabaseHandle<DB>) -> DatabaseHandle<DB> {
238    match handle {
239        DatabaseHandle::Pool(pool) => DatabaseHandle::Pool(Arc::clone(pool)),
240        DatabaseHandle::Transaction(tx) => DatabaseHandle::Transaction(Arc::clone(tx)),
241    }
242}
243impl<DB: SqlxDatabase> Clone for DatabaseHandle<DB> {
244    fn clone(&self) -> Self {
245        clone_handle(self)
246    }
247}
248impl<DB: SqlxDatabase> Clone for ConnectionRef<DB> {
249    fn clone(&self) -> Self {
250        match self {
251            Self::Pool(pool) => Self::Pool(Arc::clone(pool)),
252            Self::Transaction(tx) => Self::Transaction(Arc::clone(tx)),
253        }
254    }
255}
256impl<DB: SqlxDatabase> Clone for Database<DB> {
257    fn clone(&self) -> Self {
258        Self {
259            pool: Arc::clone(&self.pool),
260        }
261    }
262}
263
264pub struct SqlxTransaction<DB: SqlxDatabase> {
265    inner: Mutex<Option<SqlxNativeTransaction<'static, DB>>>,
266}
267impl<DB: SqlxDatabase> SqlxTransaction<DB> {
268    fn new(tx: SqlxNativeTransaction<'static, DB>) -> Self {
269        Self {
270            inner: Mutex::new(Some(tx)),
271        }
272    }
273    pub(crate) async fn lock(
274        &self,
275    ) -> Result<tokio::sync::MutexGuard<'_, Option<SqlxNativeTransaction<'static, DB>>>, DbError>
276    {
277        let guard = self.inner.lock().await;
278        if guard.is_none() {
279            return Err(DbError::TransactionClosed);
280        }
281        Ok(guard)
282    }
283    fn take(self) -> Result<SqlxNativeTransaction<'static, DB>, DbError> {
284        self.inner.into_inner().ok_or(DbError::TransactionClosed)
285    }
286}
287pub struct Transaction<DB: SqlxDatabase> {
288    inner: Arc<SqlxTransaction<DB>>,
289}
290impl<DB: SqlxDatabase> Transaction<DB> {
291    pub fn is_same(&self, other: &Self) -> bool {
292        Arc::ptr_eq(&self.inner, &other.inner)
293    }
294}
295impl<DB: SqlxDatabase> Clone for Transaction<DB> {
296    fn clone(&self) -> Self {
297        Self {
298            inner: Arc::clone(&self.inner),
299        }
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306    use futures::task::noop_waker;
307    use sqlx::{Sqlite, sqlite::SqlitePoolOptions};
308    use std::sync::{Arc, Mutex};
309
310    struct TwoPoll(Arc<Mutex<usize>>);
311    impl Future for TwoPoll {
312        type Output = ();
313        fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
314            assert!(matches!(
315                current_connection::<Sqlite>(),
316                Ok(ConnectionRef::Pool(_))
317            ));
318            let mut polls = self.0.lock().unwrap();
319            *polls += 1;
320            if *polls == 1 {
321                Poll::Pending
322            } else {
323                Poll::Ready(())
324            }
325        }
326    }
327
328    #[tokio::test]
329    async fn override_survives_cross_thread_polls_and_is_restored() {
330        let pool = Arc::new(
331            SqlitePoolOptions::new()
332                .connect_lazy("sqlite::memory:")
333                .unwrap(),
334        );
335        let polls = Arc::new(Mutex::new(0));
336        let future = Box::pin(with_connection_override(
337            DatabaseHandle::Pool(pool),
338            TwoPoll(Arc::clone(&polls)),
339        ));
340        let future = std::thread::spawn(move || {
341            let waker = noop_waker();
342            let mut context = Context::from_waker(&waker);
343            let mut future = future;
344            assert!(future.as_mut().poll(&mut context).is_pending());
345            assert!(matches!(
346                current_connection::<Sqlite>(),
347                Err(DbError::PoolNotInitialized)
348            ));
349            future
350        })
351        .join()
352        .unwrap();
353        std::thread::spawn(move || {
354            let waker = noop_waker();
355            let mut context = Context::from_waker(&waker);
356            let mut future = future;
357            assert!(future.as_mut().poll(&mut context).is_ready());
358            assert!(matches!(
359                current_connection::<Sqlite>(),
360                Err(DbError::PoolNotInitialized)
361            ));
362        })
363        .join()
364        .unwrap();
365        assert_eq!(*polls.lock().unwrap(), 2);
366    }
367
368    #[tokio::test]
369    async fn global_pool_can_be_reset() {
370        Database::<Sqlite>::reset_global();
371        let pool = SqlitePoolOptions::new()
372            .connect_lazy("sqlite::memory:")
373            .unwrap();
374        Database::<Sqlite>::set_global(Database::from_pool(pool)).unwrap();
375        assert!(Database::<Sqlite>::global().is_ok());
376        Database::<Sqlite>::reset_global();
377        assert!(matches!(
378            Database::<Sqlite>::global(),
379            Err(DbError::PoolNotInitialized)
380        ));
381    }
382}