ssql 0.2.0

Async ms sql server basic orm
Documentation
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use tiberius::ToSql;

/// Column Expression
pub struct ColExpr {
    pub(crate) table: &'static str,
    pub(crate) field: &'static str,
}

impl ColExpr {
    /// generate filter expression checking whether this column equals to a value.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("id")?.eq(&5)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id = 5`
    pub fn eq(self, other: &dyn ToSql) -> FilterExpr {
        self.expr_wrapper(ConditionVar::Eq(other))
    }

    /// generate filter expression checking whether this column not equals to a value.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("id")?.neq(&5)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id <> 5`
    pub fn neq(self, other: &dyn ToSql) -> FilterExpr {
        self.expr_wrapper(ConditionVar::Neq(other))
    }

    /// generate filter expression checking whether this column is less than a value.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.lt(&5)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id < 5`
    pub fn lt(self, other: &dyn ToSql) -> FilterExpr {
        self.expr_wrapper(ConditionVar::Lt(other))
    }

    /// generate filter expression checking whether this column is less or equal than a value.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.lt_eq(&5)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id <= 5`
    pub fn lt_eq(self, other: &dyn ToSql) -> FilterExpr {
        self.expr_wrapper(ConditionVar::LtEq(other))
    }

    /// generate filter expression checking whether this column is greater than a value.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.gt(&5)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id > 5`
    pub fn gt(self, other: &dyn ToSql) -> FilterExpr {
        self.expr_wrapper(ConditionVar::Gt(other))
    }

    /// generate filter expression checking whether this column is greater or equal than a value.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.gt_eq(&5)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id >= 5`
    pub fn gt_eq(self, other: &dyn ToSql) -> FilterExpr {
        self.expr_wrapper(ConditionVar::GtEq(other))
    }

    /// generate filter expression checking whether this column is null.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.is_null()
    /// )?;
    /// ```
    /// SQL: `**... WHERE person.email IS NULL**`
    pub fn is_null<'b>(self) -> FilterExpr<'b> {
        self.expr_wrapper(ConditionVar::IsNull)
    }

    /// generate filter expression checking whether this column is not null.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.is_not_null()
    /// )?;
    /// ```
    /// SQL: `... WHERE person.email IS NOT NULL`
    pub fn is_not_null<'b>(self) -> FilterExpr<'b> {
        self.expr_wrapper(ConditionVar::IsNotNull)
    }

    /// generate filter expression checking whether a char column contains a given str.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.contains("gmail")
    /// )?;
    /// ```
    /// SQL: `... WHERE person.email LIKE '%gmail%' `
    pub fn contains<'b>(self, other: &'b str) -> FilterExpr<'b> {
        self.expr_wrapper(ConditionVar::Contains(other))
    }

    /// generate filter expression checking whether a char column starts with a given str.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.startswith("john")
    /// )?;
    /// ```
    /// SQL: `... WHERE person.email LIKE 'john%' `
    pub fn startswith<'b>(self, other: &'b str) -> FilterExpr<'b> {
        self.expr_wrapper(ConditionVar::StarsWith(other))
    }

    /// generate filter expression checking whether a char column ends with a given str.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.endswith("gmail.com")
    /// )?;
    /// ```
    /// SQL: `... WHERE person.email LIKE '%gmail.com' `
    pub fn endswith<'b>(self, other: &'b str) -> FilterExpr<'b> {
        self.expr_wrapper(ConditionVar::EndsWith(other))
    }

    /// generate filter expression checking whether a value in a given list.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("id")?.is_in(&[3,4,5,6,7])
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id IN (3,4,5,6,7) `
    pub fn is_in(self, ls: &[impl ToSql]) -> FilterExpr {
        let v = ls.iter().map(|x| x as &dyn ToSql).collect();
        self.expr_wrapper(ConditionVar::IsIn(v))
    }

    /// generate filter expression checking whether a value in a given list.
    /// This method allows for providing different types of args.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.is_in_ref(&[&3, &"4", &5])
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id IN (3,'4',5) `
    pub fn is_in_ref<'b>(self, ls: &[&'b dyn ToSql]) -> FilterExpr<'b> {
        let v = ls.to_vec();
        self.expr_wrapper(ConditionVar::IsIn(v))
    }

    /// generate filter expression checking whether a value between a range.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("email")?.between(&3, &7)
    /// )?;
    /// ```
    /// SQL: `... WHERE person.id BETWEEN 3 AND 7 `
    pub fn between<'b>(self, start: &'b dyn ToSql, end: &'b dyn ToSql) -> FilterExpr<'b> {
        self.expr_wrapper(ConditionVar::Between((start, end)))
    }

    fn expr_wrapper(self, con: ConditionVar) -> FilterExpr {
        FilterExpr {
            col: self,
            con,
            or_cons: vec![],
        }
    }

    pub(crate) fn full_column_name(&self) -> String {
        format!("{}.{}", self.table, self.field)
    }
}

/// Filter expression used in [`query.filter`] method.
///
/// [`query.filter`]: struct.QueryBuilder.html#method.filter
pub struct FilterExpr<'b> {
    pub(crate) col: ColExpr,
    con: ConditionVar<'b>,
    or_cons: Vec<FilterExpr<'b>>,
}

impl<'b> FilterExpr<'b> {
    pub(crate) fn to_sql(&self, idx: &mut i32, query_params: &mut Vec<&'b dyn ToSql>) -> String {
        match self.or_cons.is_empty() {
            true => self.to_sql_wrapper(idx, query_params),
            false => {
                let tmp = self
                    .or_cons
                    .iter()
                    .chain([self])
                    .map(|x| x.to_sql_wrapper(idx, query_params))
                    .reduce(|cur, nxt| format!("{cur} OR {nxt}"))
                    .unwrap();
                format!("( {} )", tmp)
            }
        }
    }
    pub(crate) fn to_sql_wrapper(
        &self,
        idx: &mut i32,
        query_params: &mut Vec<&'b dyn ToSql>,
    ) -> String {
        match &self.con {
            ConditionVar::Eq(v)
            | ConditionVar::Neq(v)
            | ConditionVar::Gt(v)
            | ConditionVar::GtEq(v)
            | ConditionVar::Lt(v)
            | ConditionVar::LtEq(v) => {
                query_params.push(*v);
                *idx += 1;
                format!(
                    " {} {} @p{}",
                    self.col.full_column_name(),
                    self.con.to_sql_symbol(),
                    idx
                )
            }
            ConditionVar::IsNull | ConditionVar::IsNotNull => {
                format!(
                    "{} {}",
                    self.col.full_column_name(),
                    self.con.to_sql_symbol()
                )
            }
            ConditionVar::Contains(v) => {
                format!("{} LIKE '%{}%' ", self.col.full_column_name(), v)
            }
            ConditionVar::IsIn(v) => {
                let mut i = *idx;
                *idx += v.len() as i32;
                let cond_params = v
                    .iter()
                    .map(|_| {
                        i += 1;
                        format!("@p{}", i)
                    })
                    .reduce(|cur, nxt| format!("{},{}", cur, nxt))
                    .unwrap();
                query_params.extend(v);
                format!("{} IN ({})", self.col.full_column_name(), cond_params)
            }
            ConditionVar::Between((v1, v2)) => {
                *idx += 2;
                query_params.push(*v1);
                query_params.push(*v2);
                format!(
                    "{} BETWEEN @p{} AND @p{}",
                    self.col.full_column_name(),
                    *idx - 1,
                    idx
                )
            }
            ConditionVar::StarsWith(v) => {
                format!("{} LIKE '{}%' ", self.col.full_column_name(), v)
            }
            ConditionVar::EndsWith(v) => {
                format!("{} LIKE '%{}' ", self.col.full_column_name(), v)
            }
        }
    }

    /// supplement 'or' filters for current filter statement.
    /// ```no_run
    /// # use ssql::prelude::*;
    /// # #[derive(ORM)]
    /// # #[ssql(table = person)]
    /// # struct Person{
    /// #    id: i32,
    /// #    email: Option<String>,
    /// # }
    /// let query = Person::query().filter(
    ///     Person::col("id")?.is_in_ref(&[&3, &"4", &5])
    ///             .or(Person::col("id")?.gt(&20))
    /// )?
    ///  .filter(
    ///     Person::col("email")?.contains("gmail")
    /// )?;
    /// ```
    /// SQL: `... WHERE (person.id IN (3,'4',5) OR person.id > 20) AND person.email LIKE '%gmail%' `
    pub fn or(mut self, rhs: FilterExpr<'b>) -> Self {
        self.or_cons.push(rhs);
        self
    }
}

enum ConditionVar<'a> {
    Eq(&'a dyn ToSql),
    Neq(&'a dyn ToSql),
    Gt(&'a dyn ToSql),
    GtEq(&'a dyn ToSql),
    Lt(&'a dyn ToSql),
    LtEq(&'a dyn ToSql),
    IsNull,
    IsNotNull,
    IsIn(Vec<&'a dyn ToSql>),
    Contains(&'a str),
    StarsWith(&'a str),
    EndsWith(&'a str),
    Between((&'a dyn ToSql, &'a dyn ToSql)),
}

impl<'a> ConditionVar<'a> {
    fn to_sql_symbol(&self) -> &'static str {
        match self {
            ConditionVar::Eq(_) => "=",
            ConditionVar::Neq(_) => "<>",
            ConditionVar::Gt(_) => ">",
            ConditionVar::GtEq(_) => ">=",
            ConditionVar::Lt(_) => "<",
            ConditionVar::LtEq(_) => "<=",
            ConditionVar::IsNull => "is null",
            ConditionVar::IsNotNull => "is not null",
            ConditionVar::Contains(_) => "",
            ConditionVar::IsIn(_) => "",
            ConditionVar::Between(_) => "",
            ConditionVar::StarsWith(_) => "",
            ConditionVar::EndsWith(_) => "",
        }
    }
}