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

/// 实现用于转义变量的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! sql_quote_self {
    ($in_type:ty) => {
        impl SqlQuote<$in_type> for $in_type{
            fn sql_quote(&self)->$in_type{*self}
        }
    };
}
macro_rules! sql_quote_vec {
    ($in_type:ty) => {
        impl SqlQuote<String> for $in_type
        {
            fn sql_quote(&self)->String{
                self.into_iter().map(|e|{
                    format!("{}",e.sql_quote())
                }).collect::<Vec<String>>()
                .join(",")
            }
        }
        impl SqlQuote<String> for &$in_type
        {
            fn sql_quote(&self)->String{
                self.into_iter().map(|e|{
                    format!("{}",e.sql_quote())
                }).collect::<Vec<String>>()
                .join(",")
            }
        }
    };
}


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("'", "\\'"))
    }
}
impl SqlQuote<String> for Option<String>{
    fn sql_quote(&self)->String{
        match self {
            Some(str)=>{
                format!("'{}'",str.replace("'", "\\'"))
            }
            None=>{
                "None".to_string()
            }
        }
    }
}




macro_rules! sql_quote_array {
    ($in_type:ty) => {
        sql_quote_vec!(Vec<$in_type>);
        sql_quote_vec!([$in_type]);
    };
}

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 {SqlExpr("".to_string())}
        else {SqlExpr(format!($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 as 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!("{}",SqlExpr("select 1 as a")),"select 1 as a");
}