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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! An argument for SQL expressions.

use std::fmt;

pub mod error;
pub mod from;
pub mod from_row;
pub mod try_into;

/// Enum to keep the different argument types.
#[derive(Clone, Debug, PartialEq)]
pub enum SqlArg {
    U64(u64),
    I64(i64),
    F64(f64),
    Str(String),
    Bool(bool),
    Null,
}

impl SqlArg {
    /// Build SQL string.
    pub fn to_sql_string(&self) -> String {
        match self {
            SqlArg::U64(t) => t.to_string(),
            SqlArg::I64(t) => t.to_string(),
            SqlArg::F64(t) => t.to_string(),
            SqlArg::Str(t) => format!("'{}'", t.replace("'", "''")),
            SqlArg::Bool(t) => String::from(if *t { "TRUE" } else { "FALSE" }),
            SqlArg::Null => "NULL".to_string(),
        }
    }
    /// Build Toql query string.
    pub fn to_query_string(&self) -> String {
        match self {
            SqlArg::U64(t) => t.to_string(),
            SqlArg::I64(t) => t.to_string(),
            SqlArg::F64(t) => t.to_string(),
            SqlArg::Str(t) => format!("'{}'", t.to_string()),
            SqlArg::Bool(t) => format!("{}", (if *t { 1 } else { 0 })),
            SqlArg::Null => "0".to_string(),
        }
    }

    /// Return i64 or None, if type mismatches.
    pub fn get_i64(&self) -> Option<i64> {
        if let Self::I64(v) = self {
            Some(v.to_owned())
        } else {
            None
        }
    }
    /// Return f64 or None, if type mismatches.
    pub fn get_f64(&self) -> Option<f64> {
        if let Self::F64(v) = self {
            Some(v.to_owned())
        } else {
            None
        }
    }
    /// Return bool or None, if type mismatches.
    pub fn get_bool(&self) -> Option<bool> {
        if let Self::Bool(v) = self {
            Some(v.to_owned())
        } else {
            None
        }
    }
    /// Return u64 or None, if type mismatches.
    pub fn get_u64(&self) -> Option<u64> {
        if let Self::U64(v) = self {
            Some(v.to_owned())
        } else {
            None
        }
    }
    /// Return str or None, if type mismatches.
    pub fn get_str(&self) -> Option<&str> {
        if let Self::Str(v) = self {
            Some(v)
        } else {
            None
        }
    }

    /// Returns true, if argument is null.
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }
    /// Returns true, if argument is string and matches other string.
    pub fn cmp_str(&self, other: &str) -> bool {
        if let Self::Str(v) = self {
            v == other
        } else {
            false
        }
    }
}

/// For user display
impl fmt::Display for SqlArg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            SqlArg::U64(t) => write!(f, "{}", t),
            SqlArg::I64(t) => write!(f, "{}", t),
            SqlArg::F64(t) => write!(f, "{}", t),
            SqlArg::Str(t) => write!(f, "{}", t),
            SqlArg::Bool(t) => write!(f, "{}", if *t { "True" } else { "False" }),
            SqlArg::Null => write!(f, "{}", "Null"),
        }
    }
}

/// Returns true, if list of arguments would be a valid key.
pub fn valid_key(args: &[SqlArg]) -> bool {
    let contains_zero_key = args.iter().any(|a| match a {
        SqlArg::U64(x) => x == &0,
        SqlArg::I64(x) => x == &0,
        SqlArg::Str(x) => x.is_empty(),
        SqlArg::Null => true,
        _ => false,
    });
    !contains_zero_key
}

#[cfg(test)]
mod test {
    use super::{valid_key, SqlArg};
    use std::convert::TryInto;

    #[test]
    fn convert_u64() {
        let a = SqlArg::from(1u64);
        let x = a.get_u64().unwrap();
        assert_eq!(x, 1u64);
        assert_eq!(a.to_string(), "1");
        assert_eq!(a.to_sql_string(), "1");
        assert_eq!(a.to_query_string(), "1");
        assert_eq!(a.cmp_str("1"), false);
        assert_eq!(1u64, a.try_into().unwrap());

        let a = SqlArg::from(&1u64);
        let x = a.get_u64().unwrap();
        assert_eq!(x, 1u64);
        assert_eq!(1u64, a.try_into().unwrap());

        let a = SqlArg::from(&Some(1u64));
        let x = a.get_u64().unwrap();
        assert_eq!(x, 1u64);
        assert_eq!(1u64, a.try_into().unwrap());
    }
    #[test]
    fn convert_i64() {
        let a = SqlArg::from(1i64);
        let x = a.get_i64().unwrap();
        assert_eq!(x, 1i64);
        assert_eq!(a.to_string(), "1");
        assert_eq!(a.to_sql_string(), "1");
        assert_eq!(a.to_query_string(), "1");
        assert_eq!(a.cmp_str("1"), false);
        assert_eq!(1i64, a.try_into().unwrap());

        let a = SqlArg::from(&1i64);
        let x = a.get_i64().unwrap();
        assert_eq!(x, 1i64);
        assert_eq!(1i64, a.try_into().unwrap());

        let a = SqlArg::from(&Some(1i64));
        let x = a.get_i64().unwrap();
        assert_eq!(x, 1i64);
        assert_eq!(1i64, a.try_into().unwrap());
    }
    #[test]
    fn convert_f64() {
        let a = SqlArg::from(1.0f64);
        let x = a.get_f64().unwrap();
        assert_eq!(x, 1f64);
        assert_eq!(a.to_string(), "1");
        assert_eq!(a.to_sql_string(), "1");
        assert_eq!(a.to_query_string(), "1");
        assert_eq!(a.cmp_str("1"), false);
        assert_eq!(1.0f64, a.try_into().unwrap());

        let a = SqlArg::from(&1.0f64);
        let x = a.get_f64().unwrap();
        assert_eq!(x, 1f64);
        assert_eq!(1.0f64, a.try_into().unwrap());

        let a = SqlArg::from(&Some(1.0f64));
        let x = a.get_f64().unwrap();
        assert_eq!(x, 1f64);
        assert_eq!(1.0f64, a.try_into().unwrap());
    }
    #[test]
    fn convert_str() {
        let a = SqlArg::from("1");
        let x = a.get_str().unwrap();
        assert_eq!(x, "1");
        assert_eq!(a.to_string(), "1");
        assert_eq!(a.to_sql_string(), "'1'");
        assert_eq!(a.to_query_string(), "'1'");
        assert_eq!(a.cmp_str("1"), true);
        let s: String = a.try_into().unwrap();
        assert_eq!("1", &s);

        let a = SqlArg::from(Some("1"));
        let x = a.get_str().unwrap();
        assert_eq!(x, "1");
        let s: String = a.try_into().unwrap();
        assert_eq!("1", &s);
    }
    #[test]
    fn convert_bool() {
        let a = SqlArg::from(true);
        let x = a.get_bool().unwrap();
        assert_eq!(x, true);
        assert_eq!(a.to_string(), "True");
        assert_eq!(a.to_query_string(), "1");
        assert_eq!(a.to_sql_string(), "TRUE");
        assert_eq!(a.cmp_str("true"), false);
        assert_eq!(true, a.try_into().unwrap());

        let a = SqlArg::from(false);
        let x = a.get_bool().unwrap();
        assert_eq!(x, false);
        assert_eq!(a.to_string(), "False");
        assert_eq!(a.to_query_string(), "0");
        assert_eq!(a.to_sql_string(), "FALSE");
        assert_eq!(false, a.try_into().unwrap());

        let a = SqlArg::from(&true);
        let x = a.get_bool().unwrap();
        assert_eq!(x, true);
        assert_eq!(true, a.try_into().unwrap());

        let a = SqlArg::from(Some(true));
        let x = a.get_bool().unwrap();
        assert_eq!(x, true);
        assert_eq!(true, a.try_into().unwrap());
    }
    #[test]
    fn convert_null() {
        let a = SqlArg::Null;
        assert_eq!(a.is_null(), true);
        assert_eq!(a.to_string(), "Null");
        assert_eq!(a.to_sql_string(), "NULL");
        assert_eq!(a.to_query_string(), "0");
        assert_eq!(a.cmp_str("null"), false);

        assert_eq!(a.get_u64().is_none(), true);
        assert_eq!(a.get_i64().is_none(), true);
        assert_eq!(a.get_f64().is_none(), true);
        assert_eq!(a.get_str().is_none(), true);
        assert_eq!(a.get_bool().is_none(), true);

        let a: SqlArg = SqlArg::from(Option::<u64>::None);
        assert_eq!(a.is_null(), true);
        assert_eq!(Option::<u64>::None, a.try_into().unwrap());
    }
    #[test]
    fn valid_keys() {
        // Good example
        let a = [SqlArg::from(1), SqlArg::from("2")];
        assert_eq!(valid_key(&a), true);

        // Zero value is invalid
        let a = [SqlArg::from(1), SqlArg::from(0)];
        assert_eq!(valid_key(&a), false);

        // Empty string is invalid (equals to 0 in SQL)
        let a = [SqlArg::from(1), SqlArg::from("")];
        assert_eq!(valid_key(&a), false);

        // NULL value is invalid (primary keys must not be nullable)
        let a = [SqlArg::from(1), SqlArg::Null];
        assert_eq!(valid_key(&a), false);

        // Float value is valid (but bad idea db design)
        let a = [SqlArg::from(1), SqlArg::from(1f64)];
        assert_eq!(valid_key(&a), true);

        // Boolean value is valid
        let a = [SqlArg::from(1), SqlArg::from(false)];
        assert_eq!(valid_key(&a), true);
    }
}