sqlx_executor_alias_macro/
lib.rs

1//
2#[macro_export]
3macro_rules! mssql_executor_alias {
4    (
5        $pub:vis $name:ident
6    ) => {
7        $pub trait $name<'c>: sqlx::MssqlExecutor<'c> {}
8        impl<'c, T: sqlx::MssqlExecutor<'c>> $name<'c> for T {}
9    };
10}
11
12#[macro_export]
13macro_rules! mysql_executor_alias {
14    (
15        $pub:vis $name:ident
16    ) => {
17        $pub trait $name<'c>: sqlx::MySqlExecutor<'c> {}
18        impl<'c, T: sqlx::MySqlExecutor<'c>> $name<'c> for T {}
19    };
20}
21
22#[macro_export]
23macro_rules! postgres_executor_alias {
24    (
25        $pub:vis $name:ident
26    ) => {
27        $pub trait $name<'c>: sqlx::PgExecutor<'c> {}
28        impl<'c, T: sqlx::PgExecutor<'c>> $name<'c> for T {}
29    };
30}
31
32#[macro_export]
33macro_rules! sqlite_executor_alias {
34    (
35        $pub:vis $name:ident
36    ) => {
37        $pub trait $name<'c>: sqlx::SqliteExecutor<'c> {}
38        impl<'c, T: sqlx::SqliteExecutor<'c>> $name<'c> for T {}
39    };
40}
41
42#[cfg(test)]
43mod tests {
44
45    crate::postgres_executor_alias!(pub FooPgExecutor);
46    crate::sqlite_executor_alias!(pub FooSqliteExecutor);
47
48    use tokio::time::{timeout, Duration};
49
50    #[tokio::test]
51    async fn simple() {
52        //
53        async fn postgres_execute<'c, E: FooPgExecutor<'c>>(executor: E) {
54            let _ = sqlx::query("select 1").execute(executor).await;
55        }
56
57        let pool = sqlx::postgres::PgPoolOptions::new()
58            .connect_lazy("postgres://127.0.0.1:5432")
59            .expect("");
60        match timeout(Duration::from_millis(500), postgres_execute(&pool)).await {
61            Ok(_) => {}
62            Err(_) => {
63                eprintln!("timeout")
64            }
65        }
66
67        match timeout(Duration::from_millis(500), pool.acquire()).await {
68            Ok(Ok(mut conn)) => {
69                match timeout(Duration::from_millis(500), postgres_execute(conn.as_mut())).await {
70                    Ok(_) => {}
71                    Err(_) => {
72                        eprintln!("timeout")
73                    }
74                }
75            }
76            Ok(Err(_)) => {
77                eprintln!("acquire failed")
78            }
79            Err(_) => {
80                eprintln!("timeout")
81            }
82        }
83
84        //
85        #[allow(dead_code)]
86        async fn sqlite_execute<'c, E: FooSqliteExecutor<'c>>(executor: E) {
87            let _ = sqlx::query("select 1").execute(executor).await;
88        }
89    }
90}
91
92/*
93// Cannot be used in Transaction.
94pub trait FooPgExecutorOld: for<'c> sqlx::PgExecutor<'c> {}
95impl<T: for<'c> sqlx::PgExecutor<'c>> FooPgExecutorOld for T {}
96*/