Skip to main content

sqlx_repo/
ext.rs

1use sqlx::{Database, Error, SqlStr};
2use std::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(SqlStr::from_static("BEGIN IMMEDIATE")))
19                .await
20        }
21    }
22}
23
24impl AcquireExt<sqlx::Postgres> for sqlx::Pool<sqlx::Postgres> {
25    fn start_transaction(
26        &self,
27    ) -> impl Future<Output = Result<sqlx::Transaction<'_, sqlx::Postgres>, Error>> + Send + 'static
28    {
29        let conn = self.acquire();
30
31        async move { sqlx::Transaction::begin(conn.await?, None).await }
32    }
33}
34
35impl AcquireExt<sqlx::MySql> for sqlx::Pool<sqlx::MySql> {
36    fn start_transaction(
37        &self,
38    ) -> impl Future<Output = Result<sqlx::Transaction<'_, sqlx::MySql>, Error>> + Send + 'static
39    {
40        let conn = self.acquire();
41
42        async move { sqlx::Transaction::begin(conn.await?, None).await }
43    }
44}