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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/// 实现用于转义变量的trait
pub trait SqlQuote<OUT>
where
    OUT: std::fmt::Display,
{
    fn sql_quote(&self) -> OUT;
}

/// 保留原样的变量,不自动转义,当为自定义SQL 不能当字符串串处理时使用
pub struct SqlExpr<T: std::fmt::Display>(pub T);
impl<T: std::fmt::Display> SqlQuote<String> for SqlExpr<T> {
    fn sql_quote(&self) -> String {
        format!("{}", &self.0)
    }
}
macro_rules! array_join_to_str {
    ($self:expr) => {
        $self
            .into_iter()
            .map(|e| format!("{}", e.sql_quote()))
            .collect::<Vec<String>>()
            .join(",")
    };
}
macro_rules! option_to_str {
    ($self:expr) => {
        match $self {
            Some(str) => str.sql_quote().to_string(),
            None => "NULL".to_string(),
        }
    };
}
//常用类型
macro_rules! sql_quote_self {
    ($in_type:ty) => {
        impl SqlQuote<$in_type> for $in_type {
            fn sql_quote(&self) -> $in_type {
                *self
            }
        }
    };
}
sql_quote_self!(i8);
sql_quote_self!(i16);
sql_quote_self!(i32);
sql_quote_self!(i64);
sql_quote_self!(i128);
sql_quote_self!(u8);
sql_quote_self!(u16);
sql_quote_self!(u32);
sql_quote_self!(u64);
sql_quote_self!(u128);
sql_quote_self!(f32);
sql_quote_self!(f64);
sql_quote_self!(usize);
sql_quote_self!(isize);
impl SqlQuote<String> for char {
    fn sql_quote(&self) -> String {
        if (*self) == '\'' {
            "'\\''".to_string()
        } else {
            format!("'{self}'")
        }
    }
}
impl SqlQuote<u8> for bool {
    fn sql_quote(&self) -> u8 {
        (*self) as u8
    }
}
impl SqlQuote<String> for &str {
    fn sql_quote(&self) -> String {
        format!("'{}'", self.replace('\'', "\\'"))
    }
}
impl SqlQuote<String> for String {
    fn sql_quote(&self) -> String {
        format!("'{}'", self.replace('\'', "\\'"))
    }
}
//OPTION<常用类型>
macro_rules! sql_quote_option {
    ($in_type:ty) => {
        impl SqlQuote<String> for Option<$in_type> {
            fn sql_quote(&self) -> String {
                option_to_str!(self)
            }
        }
    };
}
sql_quote_option!(i8);
sql_quote_option!(i16);
sql_quote_option!(i32);
sql_quote_option!(i64);
sql_quote_option!(i128);
sql_quote_option!(u8);
sql_quote_option!(u16);
sql_quote_option!(u32);
sql_quote_option!(u64);
sql_quote_option!(u128);
sql_quote_option!(f32);
sql_quote_option!(f64);
sql_quote_option!(usize);
sql_quote_option!(isize);
sql_quote_option!(bool);
sql_quote_option!(char);
sql_quote_option!(String);
sql_quote_option!(&i8);
sql_quote_option!(&i16);
sql_quote_option!(&i32);
sql_quote_option!(&i64);
sql_quote_option!(&i128);
sql_quote_option!(&u8);
sql_quote_option!(&u16);
sql_quote_option!(&u32);
sql_quote_option!(&u64);
sql_quote_option!(&u128);
sql_quote_option!(&f32);
sql_quote_option!(&f64);
sql_quote_option!(&usize);
sql_quote_option!(&isize);
sql_quote_option!(&bool);
sql_quote_option!(&char);
sql_quote_option!(&String);
sql_quote_option!(&str);

//Vec<常用类型> or [常用类型]
macro_rules! sql_quote_array {
    ($in_type:ty) => {
        impl SqlQuote<String> for Vec<$in_type> {
            fn sql_quote(&self) -> String {
                array_join_to_str!(self)
            }
        }
        impl SqlQuote<String> for &Vec<$in_type> {
            fn sql_quote(&self) -> String {
                array_join_to_str!(self)
            }
        }
        impl SqlQuote<String> for [$in_type] {
            fn sql_quote(&self) -> String {
                array_join_to_str!(self)
            }
        }
        impl SqlQuote<String> for &[$in_type] {
            fn sql_quote(&self) -> String {
                array_join_to_str!(self)
            }
        }
    };
}
sql_quote_array!(i8);
sql_quote_array!(i16);
sql_quote_array!(i32);
sql_quote_array!(i64);
sql_quote_array!(i128);
sql_quote_array!(u8);
sql_quote_array!(u16);
sql_quote_array!(u32);
sql_quote_array!(u64);
sql_quote_array!(u128);
sql_quote_array!(f32);
sql_quote_array!(f64);
sql_quote_array!(usize);
sql_quote_array!(isize);
sql_quote_array!(bool);
sql_quote_array!(&str);
sql_quote_array!(String);

#[macro_export]
/// 转义SQL生成,对字符串中的单引号加反斜杠
macro_rules! sql_format {
    ($fmt:expr) => {
        format!($fmt)
    };
    ($fmt:expr,$($argsname:tt=$argsval:expr),+$(,)?) => {
        format!($fmt,$($argsname=$argsval.sql_quote()) ,+)
    };
    ($fmt:expr,$($args:expr),+$(,)?) => {
        format!($fmt,$($args.sql_quote()),+)
    };
}
#[macro_export]
/// 根据vec或[]中是否存在元素来决定是否生成SQL字符串
/// 一般用在 in 语句生成
macro_rules! sql_array_str {
    ($fmt:expr,$val:expr) => {
        if $val.len() == 0 {
            $crate::SqlExpr("".to_string())
        } else {
            $crate::SqlExpr(format!($fmt, $val.sql_quote()))
        }
    };
}
#[macro_export]
/// 根据Option中是否是NONE来生成不同的SQL
macro_rules! sql_option_str {
    ($some_fmt:expr,$none_fmt:expr,$val:expr) => {
        if $val.is_none() {
            $crate::SqlExpr(format!($none_fmt, $val.sql_quote()))
        } else {
            $crate::SqlExpr(format!($some_fmt, $val.sql_quote()))
        }
    };
}

#[test]
fn test_sql_format_macro() {
    assert_eq!(sql_format!("{var_i32}", var_i32 = 1), "1");
    assert_eq!(sql_format!("{}", 1_i8), "1");

    let aa = || 1;
    assert_eq!(sql_format!("{}", aa()), "1");
    fn bb() -> i8 {
        1
    }
    assert_eq!(sql_format!("{}", bb()), "1");

    assert_eq!(sql_format!("{}", "1'1'1"), "'1\\'1\\'1'");
    assert_eq!(sql_format!("{}", "1'1'1".to_string()), "'1\\'1\\'1'");

    assert_eq!(sql_format!("{}", '\''), "'\\''");

    assert_eq!(
        sql_format!("{}", vec!["1", "2'2'2'2'"]),
        "'1','2\\'2\\'2\\'2\\''"
    );

    assert_eq!(
        sql_format!("{}", ["1", "2'2'2'2'"]),
        "'1','2\\'2\\'2\\'2\\''"
    );

    assert_eq!(
        sql_format!("{}", ["1".to_string(), "2'2'2'2'".to_string()]),
        "'1','2\\'2\\'2\\'2\\''"
    );

    assert_eq!(
        sql_format!("{}", vec!["1".to_string(), "2'2'2'2'".to_string()]),
        "'1','2\\'2\\'2\\'2\\''"
    );

    let a: [i8; 0] = [];
    assert_eq!(sql_format!("{}", sql_array_str!("ddd in ({})", a)), "");

    assert_eq!(
        sql_format!("{}", sql_array_str!("ddd in ({})", [1, 2])),
        "ddd in (1,2)"
    );

    assert_eq!(
        sql_format!("{}", sql_option_str!("a = {}", "{}", Some(1))),
        "a = 1"
    );

    let i: Option<i128> = None;
    assert_eq!(
        sql_format!("{}", sql_option_str!("{}", "a is {}", i)),
        "a is NULL"
    );

    assert_eq!(sql_format!("{}", SqlExpr("select 1 as a")), "select 1 as a");
}