sqlx_repo/
ext.rs

1use sqlx::{Database, Error};
2use std::{borrow::Cow, future::Future};
3
4pub trait AcquireExt<D: Database> {
5    fn start_transaction(
6        &self,
7    ) -> impl Future<Output = Result<sqlx::Transaction<'_, D>, Error>> + Send + 'static;
8}
9
10impl AcquireExt<sqlx::Sqlite> for sqlx::Pool<sqlx::Sqlite> {
11    fn start_transaction(
12        &self,
13    ) -> impl Future<Output = Result<sqlx::Transaction<'_, sqlx::Sqlite>, Error>> + Send + 'static
14    {
15        let conn = self.acquire();
16
17        async move {
18            sqlx::Transaction::begin(conn.await?, Some(Cow::Borrowed("BEGIN IMMEDIATE"))).await
19        }
20    }
21}
22
23impl AcquireExt<sqlx::Postgres> for sqlx::Pool<sqlx::Postgres> {
24    fn start_transaction(
25        &self,
26    ) -> impl Future<Output = Result<sqlx::Transaction<'_, sqlx::Postgres>, Error>> + Send + 'static
27    {
28        let conn = self.acquire();
29
30        async move { sqlx::Transaction::begin(conn.await?, None).await }
31    }
32}
33
34impl AcquireExt<sqlx::MySql> for sqlx::Pool<sqlx::MySql> {
35    fn start_transaction(
36        &self,
37    ) -> impl Future<Output = Result<sqlx::Transaction<'_, sqlx::MySql>, Error>> + Send + 'static
38    {
39        let conn = self.acquire();
40
41        async move { sqlx::Transaction::begin(conn.await?, None).await }
42    }
43}