1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::borrow::BorrowMut;
use std::borrow::Borrow;
use sqlx::Pool;
use sqlx::{Database, Transaction};




pub trait ExecutorOptionTransaction {
    fn as_copy(&mut self)->&mut Self;
}

impl<'t,DB> ExecutorOptionTransaction for Transaction<'t,DB> where
DB: Database, {
    fn as_copy(&mut self)->&mut Self {
        self.borrow_mut()
    }
}

pub trait ExecutorOptionPool {
    fn as_copy(&self)->&Self;
}

impl<DB> ExecutorOptionPool for Pool<DB> where
DB: Database, {
    fn as_copy(&self)->&Self {
        self.borrow()
    }
}



#[macro_export]
/// 对包含块代码中的链接变量选择事物或连接池
/// @param $block 执行sql代码 里面可用 $execute 变量 多次使用 $execute.as_copy()
/// @param $transaction Option 当存在时$block中 $execute 变量用此值
/// @param $poll Option 不存在时 $execute 变量用此值
/// @param $execute  $block块中用到的连接变量名
macro_rules! executor_option {
    ($block:block,$transaction:expr,$poll:expr,$execute:tt)=>{
        match $transaction {
            Some($execute)=>{
                #[allow(unused_imports)]
                use $crate::ExecutorOptionTransaction;
                $block
            }
            None=>{
                #[allow(unused_imports)]
                use $crate::ExecutorOptionPool;
                let $execute=$poll;
                $block
            }
        }
    };
}



#[test]
fn test_executor_option(){
    let va:Option<i32>=None;
    let vb=1;
    let a=executor_option!({
        aa
    },va,vb,aa);
    assert!(a==1);
    
    let va:Option<i32>=Some(2);
    let vb=1;
    let a=executor_option!({
        aa
    },va,vb,aa);
    assert!(a==2);

}