rquery-orm 1.0.0

Lightweight SQL ORM for Rust with query-style (MSSQL + PostgreSQL).
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
use std::marker::PhantomData;

use std::sync::Arc;

use crate::db::DatabaseRef;
use crate::mapping::{Entity, FromRowWithPrefix};
use anyhow::Result;
use futures::TryStreamExt;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlaceholderStyle {
    AtP,
    Dollar,
}

#[derive(Clone, Debug, PartialEq)]
pub enum SqlParam {
    I32(i32),
    I64(i64),
    Bool(bool),
    Text(String),
    Uuid(uuid::Uuid),
    Decimal(rust_decimal::Decimal),
    DateTime(chrono::NaiveDateTime),
    Bytes(Vec<u8>),
    Null,
}

pub trait ToParam {
    fn to_param(self) -> SqlParam;
}

impl ToParam for i32 {
    fn to_param(self) -> SqlParam {
        SqlParam::I32(self)
    }
}
impl ToParam for i64 {
    fn to_param(self) -> SqlParam {
        SqlParam::I64(self)
    }
}
impl ToParam for bool {
    fn to_param(self) -> SqlParam {
        SqlParam::Bool(self)
    }
}
impl ToParam for String {
    fn to_param(self) -> SqlParam {
        SqlParam::Text(self)
    }
}
impl<'a> ToParam for &'a str {
    fn to_param(self) -> SqlParam {
        SqlParam::Text(self.to_string())
    }
}
impl ToParam for uuid::Uuid {
    fn to_param(self) -> SqlParam {
        SqlParam::Uuid(self)
    }
}
impl ToParam for rust_decimal::Decimal {
    fn to_param(self) -> SqlParam {
        SqlParam::Decimal(self)
    }
}
impl ToParam for chrono::NaiveDateTime {
    fn to_param(self) -> SqlParam {
        SqlParam::DateTime(self)
    }
}
impl ToParam for Vec<u8> {
    fn to_param(self) -> SqlParam {
        SqlParam::Bytes(self)
    }
}

impl<T: ToParam> ToParam for Option<T> {
    fn to_param(self) -> SqlParam {
        match self {
            Some(v) => v.to_param(),
            None => SqlParam::Null,
        }
    }
}

#[derive(Clone, Debug)]
pub enum Expr {
    Col(String),
    Param(SqlParam),
    Binary {
        left: Box<Expr>,
        op: &'static str,
        right: Box<Expr>,
    },
    Like {
        left: Box<Expr>,
        right: SqlParam,
    },
    InList {
        left: Box<Expr>,
        list: Vec<SqlParam>,
    },
    Group(Box<Expr>),
}

impl Expr {
    pub fn eq(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: "=",
            right: Box::new(rhs),
        }
    }
    pub fn ne(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: "<>",
            right: Box::new(rhs),
        }
    }
    pub fn gt(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: ">",
            right: Box::new(rhs),
        }
    }
    pub fn ge(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: ">=",
            right: Box::new(rhs),
        }
    }
    pub fn lt(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: "<",
            right: Box::new(rhs),
        }
    }
    pub fn le(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: "<=",
            right: Box::new(rhs),
        }
    }
    pub fn and(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: "AND",
            right: Box::new(rhs),
        }
    }
    pub fn or(self, rhs: Expr) -> Expr {
        Expr::Binary {
            left: Box::new(self),
            op: "OR",
            right: Box::new(rhs),
        }
    }
    pub fn like(self, pattern: Expr) -> Expr {
        match pattern {
            Expr::Param(p) => Expr::Like {
                left: Box::new(self),
                right: p,
            },
            other => panic!("like expects Expr::Param but received {:?}", other),
        }
    }
    pub fn in_list(self, list: Vec<Expr>) -> Expr {
        let mut ps = Vec::new();
        for e in list {
            match e {
                Expr::Param(p) => ps.push(p),
                other => panic!("in_list expects Expr::Param items but received {:?}", other),
            }
        }
        Expr::InList {
            left: Box::new(self),
            list: ps,
        }
    }
    pub fn group(self) -> Expr {
        Expr::Group(Box::new(self))
    }

    pub fn to_sql_with(&self, style: PlaceholderStyle, params: &mut Vec<SqlParam>) -> String {
        match self {
            Expr::Col(c) => c.clone(),
            Expr::Param(p) => {
                params.push(p.clone());
                let idx = params.len();
                match style {
                    PlaceholderStyle::AtP => format!("@P{}", idx),
                    PlaceholderStyle::Dollar => format!("${}", idx),
                }
            }
            Expr::Binary { left, op, right } => {
                let l = left.to_sql_with(style, params);
                let r = right.to_sql_with(style, params);
                if *op == "AND" || *op == "OR" {
                    format!("{} {} {}", l, op, r)
                } else {
                    format!("({} {} {})", l, op, r)
                }
            }
            Expr::Like { left, right } => {
                params.push(right.clone());
                let idx = params.len();
                let ph = match style {
                    PlaceholderStyle::AtP => format!("@P{}", idx),
                    PlaceholderStyle::Dollar => format!("${}", idx),
                };
                format!("({} LIKE {})", left.to_sql_with(style, params), ph)
            }
            Expr::InList { left, list } => {
                let mut phs = Vec::new();
                for p in list {
                    params.push(p.clone());
                    let idx = params.len();
                    phs.push(match style {
                        PlaceholderStyle::AtP => format!("@P{}", idx),
                        PlaceholderStyle::Dollar => format!("${}", idx),
                    });
                }
                format!(
                    "{} IN ({})",
                    left.to_sql_with(style, params),
                    phs.join(", ")
                )
            }
            Expr::Group(e) => format!("({})", e.to_sql_with(style, params)),
        }
    }
}

#[macro_export]
macro_rules! col {
    ($name:expr) => {
        $crate::query::Expr::Col($name.to_string())
    };
}

#[macro_export]
macro_rules! val {
    ($v:expr) => {
        $crate::query::Expr::Param($crate::query::ToParam::to_param($v))
    };
}

// Helper macro for column equality to reduce duplication in on! and condition!
#[macro_export]
macro_rules! __col_eq {
    // Compare two columns
    (($lt:ident :: $lf:ident), ($rt:ident :: $rf:ident)) => {
        $crate::query::Expr::Col(format!("{}.{}", $lt::TABLE, $lt::$lf))
            .eq($crate::query::Expr::Col(format!("{}.{}", $rt::TABLE, $rt::$rf)))
    };
    // Compare column to value
    (($lt:ident :: $lf:ident), $rv:expr) => {
        $crate::query::Expr::Col(format!("{}.{}", $lt::TABLE, $lt::$lf))
            .eq($crate::query::Expr::Param($crate::query::ToParam::to_param($rv)))
    };
}

#[macro_export]
macro_rules! on {
    ($lt:ident :: $lf:ident == $rt:ident :: $rf:ident) => {
        $crate::__col_eq!(($lt :: $lf), ($rt :: $rf))
    };
    ($lt:ident :: $lf:ident == $rv:expr) => {
        $crate::__col_eq!(($lt :: $lf), $rv)
    };
}

#[macro_export]
macro_rules! condition {
    ($l:literal == $rv:expr) => {{
        $crate::query::Expr::Col($l.to_string())
            .eq($crate::query::Expr::Param($crate::query::ToParam::to_param($rv)))
    }};
    ($lt:ident :: $lf:ident == $rt:ident :: $rf:ident) => {
        $crate::__col_eq!(($lt :: $lf), ($rt :: $rf))
    };
    ($lt:ident :: $lf:ident == $rv:expr) => {
        $crate::__col_eq!(($lt :: $lf), $rv)
    };
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JoinType {
    Inner,
    Left,
    Right,
    Full,
}

impl JoinType {
    fn to_sql(self) -> &'static str {
        match self {
            JoinType::Inner => "INNER JOIN",
            JoinType::Left => "LEFT JOIN",
            JoinType::Right => "RIGHT JOIN",
            JoinType::Full => "FULL JOIN",
        }
    }
}

pub struct DualQuery<T, U>
where
    T: Entity + FromRowWithPrefix,
    U: Entity + FromRowWithPrefix,
{
    style: PlaceholderStyle,
    db: Option<Arc<DatabaseRef>>,
    filters: Vec<Expr>,
    order_by: Option<String>,
    top: Option<i64>,
    join: Option<(JoinType, Expr)>,
    _t: PhantomData<T>,
    _u: PhantomData<U>,
}

impl<T, U> DualQuery<T, U>
where
    T: Entity + FromRowWithPrefix,
    U: Entity + FromRowWithPrefix,
{
    pub fn new(style: PlaceholderStyle) -> Self {
        Self {
            style,
            db: None,
            filters: Vec::new(),
            order_by: None,
            top: None,
            join: None,
            _t: PhantomData,
            _u: PhantomData,
        }
    }

    pub fn with_db(mut self, db: Arc<DatabaseRef>) -> Self {
        self.db = Some(db);
        self
    }

    pub fn Join(mut self, join_type: JoinType, on_expr: Expr) -> Self {
        self.join = Some((join_type, on_expr));
        self
    }

    pub fn Where(mut self, expr: Expr) -> Self {
        self.filters.push(expr);
        self
    }

    pub fn OrderBy(mut self, ob: &str) -> Self {
        self.order_by = Some(ob.to_string());
        self
    }

    pub fn Top(mut self, n: i64) -> Self {
        self.top = Some(n);
        self
    }

    pub fn to_sql(&self) -> (String, Vec<SqlParam>) {
        let mut params = Vec::new();
        let tname = T::table().name;
        let uname = U::table().name;
        let mut cols = Vec::new();
        for c in T::table().columns {
            cols.push(format!("{}.{} AS t_{}", tname, c.name, c.name));
        }
        for c in U::table().columns {
            cols.push(format!("{}.{} AS u_{}", uname, c.name, c.name));
        }
        let mut sql = String::new();
        match self.style {
            PlaceholderStyle::AtP => {
                if let Some(n) = self.top {
                    sql.push_str(&format!("SELECT TOP({}) {} FROM {}", n, cols.join(", "), tname));
                } else {
                    sql.push_str(&format!("SELECT {} FROM {}", cols.join(", "), tname));
                }
            }
            PlaceholderStyle::Dollar => {
                sql.push_str(&format!("SELECT {} FROM {}", cols.join(", "), tname));
            }
        }
        if let Some((jt, on)) = &self.join {
            sql.push(' ');
            sql.push_str(jt.to_sql());
            sql.push(' ');
            sql.push_str(uname);
            sql.push_str(" ON ");
            sql.push_str(&on.to_sql_with(self.style, &mut params));
        }
        if !self.filters.is_empty() {
            let mut it = self.filters.iter();
            if let Some(first) = it.next() {
                sql.push_str(" WHERE ");
                sql.push_str(&first.to_sql_with(self.style, &mut params));
                for f in it {
                    sql.push_str(" AND ");
                    sql.push_str(&f.to_sql_with(self.style, &mut params));
                }
            }
        }
        if let Some(ob) = &self.order_by {
            sql.push_str(" ORDER BY ");
            sql.push_str(ob);
        }
        if let Some(n) = self.top {
            if self.style == PlaceholderStyle::Dollar {
                sql.push_str(&format!(" LIMIT {}", n));
            }
        }
        (sql, params)
    }

    pub async fn to_list_async(self) -> Result<Vec<(T, U)>> {
        let db = self.db.clone().expect("database reference not set");
        let (sql, params) = self.to_sql();
        match db.as_ref() {
            DatabaseRef::Mssql(conn) => {
                let mut guard = conn.lock().await;
                let mut boxed: Vec<Box<dyn tiberius::ToSql + Send + Sync>> = Vec::new();
                for p in &params {
                    let b: Box<dyn tiberius::ToSql + Send + Sync> = match p {
                        SqlParam::I32(v) => Box::new(*v),
                        SqlParam::I64(v) => Box::new(*v),
                        SqlParam::Bool(v) => Box::new(*v),
                        SqlParam::Text(v) => Box::new(v.clone()),
                        SqlParam::Uuid(v) => Box::new(*v),
                        SqlParam::Decimal(v) => Box::new(v.to_string()),
                        SqlParam::DateTime(v) => Box::new(*v),
                        SqlParam::Bytes(v) => Box::new(v.clone()),
                        SqlParam::Null => Box::new(Option::<i32>::None),
                    };
                    boxed.push(b);
                }
                let refs: Vec<&dyn tiberius::ToSql> =
                    boxed.iter().map(|b| &**b as &dyn tiberius::ToSql).collect();
                let mut stream = guard.query(&sql, &refs[..]).await?;
                let mut out = Vec::new();
                while let Some(item) = stream.try_next().await? {
                    if let Some(row) = item.into_row() {
                        let left = T::from_row_ms_with(&row, "t")?;
                        let right = U::from_row_ms_with(&row, "u")?;
                        out.push((left, right));
                    }
                }
                Ok(out)
            }
            DatabaseRef::Postgres(pg) => {
                let mut boxed: Vec<Box<dyn tokio_postgres::types::ToSql + Send + Sync>> =
                    Vec::new();
                for p in &params {
                    let b: Box<dyn tokio_postgres::types::ToSql + Send + Sync> = match p {
                        SqlParam::I32(v) => Box::new(*v),
                        SqlParam::I64(v) => Box::new(*v),
                        SqlParam::Bool(v) => Box::new(*v),
                        SqlParam::Text(v) => Box::new(v.clone()),
                        SqlParam::Uuid(v) => Box::new(*v),
                        SqlParam::Decimal(v) => Box::new(v.to_string()),
                        SqlParam::DateTime(v) => Box::new(*v),
                        SqlParam::Bytes(v) => Box::new(v.clone()),
                        SqlParam::Null => Box::new(Option::<i32>::None),
                    };
                    boxed.push(b);
                }
                let refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
                    boxed.iter().map(|b| &**b as _).collect();
                let rows = pg.query(&sql, &refs[..]).await?;
                let mut out = Vec::new();
                for row in rows {
                    let left = T::from_row_pg_with(&row, "t")?;
                    let right = U::from_row_pg_with(&row, "u")?;
                    out.push((left, right));
                }
                Ok(out)
            }
        }
    }
}

struct JoinClause {
    join_type: JoinType,
    table: String,
    on: Expr,
}

#[allow(non_snake_case)]
pub struct Query<T>
where
    T: Entity + crate::mapping::FromRowNamed,
{
    table: String,
    style: PlaceholderStyle,
    db: Option<Arc<DatabaseRef>>,
    joins: Vec<JoinClause>,
    filters: Vec<Expr>,
    order_by: Option<String>,
    top: Option<i64>,
    _t: PhantomData<T>,
}

#[allow(non_snake_case)]
impl<T> Query<T>
where
    T: Entity + crate::mapping::FromRowNamed,
{
    pub fn new(table: &str, style: PlaceholderStyle) -> Self {
        Self {
            table: table.to_string(),
            style,
            db: None,
            joins: Vec::new(),
            filters: Vec::new(),
            order_by: None,
            top: None,
            _t: PhantomData,
        }
    }

    pub fn with_db(mut self, db: Arc<DatabaseRef>) -> Self {
        self.db = Some(db);
        self
    }

    pub fn Where(mut self, expr: Expr) -> Self {
        self.filters.push(expr);
        self
    }

    pub fn Join(mut self, join_type: JoinType, table: &str, on_expr: Expr) -> Self {
        self.joins.push(JoinClause {
            join_type,
            table: table.to_string(),
            on: on_expr,
        });
        self
    }

    pub fn OrderBy(mut self, ob: &str) -> Self {
        self.order_by = Some(ob.to_string());
        self
    }

    pub fn Top(mut self, n: i64) -> Self {
        self.top = Some(n);
        self
    }

    pub fn to_sql(&self) -> (String, Vec<SqlParam>) {
        let mut params = Vec::new();
        let mut sql = String::new();
        match self.style {
            PlaceholderStyle::AtP => {
                if let Some(n) = self.top {
                    sql.push_str(&format!("SELECT TOP({}) * FROM {}", n, self.table));
                } else {
                    sql.push_str(&format!("SELECT * FROM {}", self.table));
                }
            }
            PlaceholderStyle::Dollar => {
                sql.push_str(&format!("SELECT * FROM {}", self.table));
            }
        }
        for j in &self.joins {
            sql.push(' ');
            sql.push_str(j.join_type.to_sql());
            sql.push(' ');
            sql.push_str(&j.table);
            sql.push_str(" ON ");
            sql.push_str(&j.on.to_sql_with(self.style, &mut params));
        }
        if !self.filters.is_empty() {
            let mut it = self.filters.iter();
            if let Some(first) = it.next() {
                sql.push_str(" WHERE ");
                sql.push_str(&first.to_sql_with(self.style, &mut params));
                for f in it {
                    sql.push_str(" AND ");
                    sql.push_str(&f.to_sql_with(self.style, &mut params));
                }
            }
        }
        if let Some(ob) = &self.order_by {
            sql.push_str(" ORDER BY ");
            sql.push_str(ob);
        }
        if let Some(n) = self.top {
            if self.style == PlaceholderStyle::Dollar {
                sql.push_str(&format!(" LIMIT {}", n));
            }
        }
        (sql, params)
    }

    pub async fn to_list_async(self) -> Result<Vec<T>> {
        let db = self.db.clone().expect("database reference not set");
        let (sql, params) = self.to_sql();
        match db.as_ref() {
            DatabaseRef::Mssql(conn) => {
                let mut guard = conn.lock().await;
                let mut boxed: Vec<Box<dyn tiberius::ToSql + Send + Sync>> = Vec::new();
                for p in &params {
                    let b: Box<dyn tiberius::ToSql + Send + Sync> = match p {
                        SqlParam::I32(v) => Box::new(*v),
                        SqlParam::I64(v) => Box::new(*v),
                        SqlParam::Bool(v) => Box::new(*v),
                        SqlParam::Text(v) => Box::new(v.clone()),
                        SqlParam::Uuid(v) => Box::new(*v),
                        SqlParam::Decimal(v) => Box::new(v.to_string()),
                        SqlParam::DateTime(v) => Box::new(*v),
                        SqlParam::Bytes(v) => Box::new(v.clone()),
                        SqlParam::Null => Box::new(Option::<i32>::None),
                    };
                    boxed.push(b);
                }
                let refs: Vec<&dyn tiberius::ToSql> =
                    boxed.iter().map(|b| &**b as &dyn tiberius::ToSql).collect();
                let mut stream = guard.query(&sql, &refs[..]).await?;
                let mut out = Vec::new();
                while let Some(item) = stream.try_next().await? {
                    if let Some(row) = item.into_row() {
                        out.push(T::from_row_ms(&row)?);
                    }
                }
                Ok(out)
            }
            DatabaseRef::Postgres(pg) => {
                let mut boxed: Vec<Box<dyn tokio_postgres::types::ToSql + Send + Sync>> =
                    Vec::new();
                for p in &params {
                    let b: Box<dyn tokio_postgres::types::ToSql + Send + Sync> = match p {
                        SqlParam::I32(v) => Box::new(*v),
                        SqlParam::I64(v) => Box::new(*v),
                        SqlParam::Bool(v) => Box::new(*v),
                        SqlParam::Text(v) => Box::new(v.clone()),
                        SqlParam::Uuid(v) => Box::new(*v),
                        SqlParam::Decimal(v) => Box::new(v.to_string()),
                        SqlParam::DateTime(v) => Box::new(*v),
                        SqlParam::Bytes(v) => Box::new(v.clone()),
                        SqlParam::Null => Box::new(Option::<i32>::None),
                    };
                    boxed.push(b);
                }
                let refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
                    boxed.iter().map(|b| &**b as _).collect();
                let rows = pg.query(&sql, &refs[..]).await?;
                let mut out = Vec::new();
                for row in rows {
                    out.push(T::from_row_pg(&row)?);
                }
                Ok(out)
            }
        }
    }

    pub async fn to_single_async(self) -> Result<Option<T>> {
        let mut list = self.Top(1).to_list_async().await?;
        Ok(list.pop())
    }

    pub async fn ToDictionaryKeyIntAsync(
        self,
    ) -> anyhow::Result<std::collections::HashMap<i32, T>> {
        unimplemented!("execution not implemented");
    }

    pub async fn ToDictionaryKeyGuidAsync(
        self,
    ) -> anyhow::Result<std::collections::HashMap<uuid::Uuid, T>> {
        unimplemented!("execution not implemented");
    }

    pub async fn ToDictionaryKeyStringAsync(
        self,
    ) -> anyhow::Result<std::collections::HashMap<String, T>> {
        unimplemented!("execution not implemented");
    }
}