sqlx_model/
executer_option.rs

1use sqlx::Pool;
2use sqlx::{Database, Transaction};
3use std::borrow::BorrowMut;
4
5pub trait ExecutorOptionTransaction {
6    fn as_copy(&mut self) -> &mut Self;
7}
8
9impl<'t, DB> ExecutorOptionTransaction for Transaction<'t, DB>
10where
11    DB: Database,
12{
13    fn as_copy(&mut self) -> &mut Self {
14        self.borrow_mut()
15    }
16}
17
18pub trait ExecutorOptionPool {
19    fn as_copy(&self) -> &Self;
20}
21
22impl<DB> ExecutorOptionPool for Pool<DB>
23where
24    DB: Database,
25{
26    fn as_copy(&self) -> &Self {
27        self
28    }
29}
30
31#[macro_export]
32/// 对包含块代码中的链接变量选择事物或连接池
33/// @param $block 执行sql代码 里面可用 $execute 变量 多次使用 $execute.as_copy()
34/// @param $transaction Option 当存在时$block中 $execute 变量用此值
35/// @param $poll Option 不存在时 $execute 变量用此值
36/// @param $execute  $block块中用到的连接变量名
37macro_rules! executor_option {
38    ($block:block,$transaction:expr,$poll:expr,$execute:tt) => {
39        match $transaction {
40            Some($execute) => {
41                #[allow(unused_imports)]
42                use $crate::ExecutorOptionTransaction;
43                $block
44            }
45            None => {
46                #[allow(unused_imports)]
47                use $crate::ExecutorOptionPool;
48                let $execute = $poll;
49                $block
50            }
51        }
52    };
53}
54
55#[test]
56fn test_executor_option() {
57    let va: Option<i32> = None;
58    let vb = 1;
59    let a = executor_option!({ aa }, va, vb, aa);
60    assert!(a == 1);
61
62    let va: Option<i32> = Some(2);
63    let vb = 1;
64    let a = executor_option!({ aa }, va, vb, aa);
65    assert!(a == 2);
66}