rustorm 0.0.5

A simple ORM and code generator for rust
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
use dao::{Type, ToType};
use table::{Table, Column};
use std::collections::BTreeMap;
use database::Database;
use dao::DaoResult;
use dao::IsDao;
use dao::Dao;
use table::IsTable;
use writer::SqlFrag;

#[derive(Debug)]
#[derive(Clone)]
pub enum JoinType{
    CROSS,
    INNER,
    OUTER,
}
#[derive(Debug)]
#[derive(Clone)]
pub enum Modifier{
    LEFT,
    RIGHT,
    FULL,
}

#[derive(Debug)]
#[derive(Clone)]
pub struct Join{
    pub modifier:Option<Modifier>,
    pub join_type:JoinType,
    pub table_name:TableName,
    pub column1:Vec<String>,
    pub column2:Vec<String>
}
#[derive(Debug)]
#[derive(Clone)]
pub enum Direction{
    ASC,
    DESC,
}


////
/// Filter struct merged to query
/// 
#[derive(Debug)]
#[derive(Clone)]
pub enum Connector{
    And,
    Or
}

#[derive(Debug)]
#[derive(Clone)]
pub enum Equality{
    EQ, //EQUAL,
    NE, //NOT_EQUAL,
    LT, //LESS_THAN,
    LTE, //LESS_THAN_OR_EQUAL,
    GT, //GREATER_THAN,
    GTE, //GREATER_THAN_OR_EQUAL,
    IN,
    NOTIN,//NOT_IN,
    LIKE,
    NULL,
    NOTNULL,//NOT_NULL,
    ISNULL,//IS_NULL,
}

/// function in a sql statement
#[derive(Debug)]
#[derive(Clone)]
pub struct Function{
    pub function:String,
    pub params:Vec<Operand>,
}

/// Operands can be columns, functions, query or value types
#[derive(Debug)]
#[derive(Clone)]
pub enum Operand{
    ColumnName(ColumnName),
    TableName(TableName),
    Function(Function),
    Query(Query),
    Value(Type),
    Vec(Vec<Operand>),
}

/// expression has left operand,
/// equality and right operand
#[derive(Debug)]
#[derive(Clone)]
pub struct Condition{
    pub left_operand:Operand,
    pub equality:Equality,
    pub right_operand:Operand,
}

/// TODO: support for functions on columns
/// TODO: need to merge with Expr
#[derive(Debug)]
#[derive(Clone)]
pub struct Filter{
    pub connector:Connector,
    /// TODO: maybe renamed to LHS, supports functions and SQL
    pub condition: Condition,
    pub subfilters:Vec<Filter>
}

impl Filter{

    pub fn new(column:&str, equality:Equality, value:&ToType)->Self{
        let right_operand = Operand::Value(value.to_db_type());
        Filter{
            connector:Connector::And,
            condition: Condition{left_operand:
                        Operand::ColumnName(ColumnName::from_str(column)),
                        equality:equality,
                        right_operand:right_operand},
            subfilters:vec![],
        }
    }
    
    pub fn and(&mut self, column:&str, equality:Equality, value:&ToType)->&mut Self{
        let mut filter = Filter::new(column, equality, value);
        filter.connector = Connector::And;
        self.subfilters.push(filter);
        self
    }
    
    pub fn or(&mut self, column:&str, equality:Equality, value:&ToType)->&mut Self{
        let mut filter = Filter::new(column, equality, value);
        filter.connector = Connector::Or;
        self.subfilters.push(filter);
        self
    }
    
}

/// Could have been SqlAction
#[derive(Debug)]
#[derive(Clone)]
pub enum SqlType{
    //DML
    SELECT,
    INSERT,
    UPDATE,
    DELETE,
}

#[derive(Clone)]
#[derive(Debug)]
pub struct ColumnName{
    pub column:String,
    pub table:Option<String>,
    ////optional schema, if ever there are same tables resideing in  different schema/namespace
    pub schema:Option<String>,
    /// as rename
    pub rename:Option<String>
}

#[derive(Debug)]
#[derive(Clone)]
pub struct Field{
    /// the field
    pub operand:Operand,
    /// when renamed as field
    pub name:Option<String>,
}


impl ColumnName{

    fn from_column(column:&Column, table:&Table)->Self{
        ColumnName{
            column: column.name.to_string(),
            table: Some(table.name.to_string()),
            schema: Some(table.schema.to_string()),
            rename: None,
        }
    }
    
    fn from_str(column:&str)->Self{
        if column.contains("."){
            let splinters = column.split(".").collect::<Vec<&str>>();
            assert!(splinters.len() == 2, "There should only be 2 splinters");
            let table_split = splinters[0].to_string();
            let column_split = splinters[1].to_string();
            ColumnName{
                column:column_split.to_string(), 
                table:Some(table_split.to_string()), 
                schema:None,
                rename:None
            }
        } else {
            ColumnName{
                column:column.to_string(), 
                table:None, 
                schema:None,
                rename:None
            }
        }
    }
    
    fn rename(&self)->String{
        return format!("{}_{}", self.table.as_ref().unwrap(), self.column)
    }
    /// table name and column name
    pub fn complete_name(&self)->String{
        if self.table.is_some(){
            return format!("{}.{}", self.table.as_ref().unwrap(), self.column);
        }else{
            return self.column.to_string();
        }
    }
    /// includes the schema, table name and column name
    pub fn super_complete_name(&self)->String{
        if self.schema.is_some(){
            return format!("{}.{}", self.schema.as_ref().unwrap(), self.complete_name());
        }else{
            return self.complete_name();
        }
    }
    
}

impl PartialEq for ColumnName{
    fn eq(&self, other: &Self) -> bool{
        self.column == other.column
     }

    fn ne(&self, other: &Self) -> bool {
        self.column != other.column
    }
}


#[derive(Clone)]
#[derive(Debug)]
pub struct TableName{
    pub schema: String,
    pub name: String,
    pub column_names: Vec<ColumnName>,
}

impl TableName{
    
    fn from_table(table:&Table)->Self{
        TableName{
            schema:table.schema.to_string(),
            name: table.name.to_string(),
            column_names:vec![],
        }
    }

    pub fn complete_name(&self)->String{
        format!("{}.{}",self.schema, self.name)
    }
}

impl PartialEq for TableName{
    fn eq(&self, other: &Self) -> bool{
        self.name == other.name && self.schema == other.schema
     }

    fn ne(&self, other: &Self) -> bool {
        self.name != other.name || self.schema != other.schema
    }
}

#[derive(Debug)]
#[derive(Clone)]
pub struct Query{
    
    ///sql type determine which type of query to form, some fields are not applicable to other types of query
    pub sql_type:SqlType,
    
    /// whether to select the records distinct
    pub distinct:bool,
    
    pub declared_query: BTreeMap<String, Query>,

    ///fields can be functions, column sql query, and even columns
    /// TODO; merge enumerated column to this, add a builder for fields
    pub enumerated_fields:Vec<Field>,
    
    /// list of renamed columns whenever there is a conflict
    /// Vec(table, column, new_column_name)
    pub renamed_columns:BTreeMap<String, Vec<(String, String)>>,
    
    /// specify to use distinct ON set of columns 
    pub distinct_on_columns:Vec<String>,
    
    /// filter records, ~ where statement of the query
    pub filters:Vec<Filter>,
    
    /// joining multiple tables
    pub joins:Vec<Join>,
    
    /// ordering of the records via the columns specified
    pub order_by:Vec<(String, Direction)>,
    
    /// grouping columns to create an aggregate
    pub group_by: Vec<Operand>,
    
    /// having field
    pub having: Vec<Condition>,
    
    /// exclude the mention of the columns in the SQL query, useful when ignoring changes in update/insert records
    pub excluded_columns:Vec<ColumnName>,
    
    /// paging of records
    pub page:Option<usize>,
    
    /// size of a page
    pub page_size:Option<usize>,
    
    /// where the focus of values of column selection
    /// this is the table to insert to, update to delete, create, drop
    /// whe used in select, this is the 
    /// pub from_table:Option<TableName>,
    
    /// from field, where field can be a query, table, column, or function
    pub from:Option<Box<Field>>,
    
    /// The data values, used in bulk inserting, updating,
    pub values:Vec<Operand>,
    
    /// the returning clause of the query when supported,
    pub enumerated_returns: Vec<Field>,
}

impl Query{
    
    /// the default query is select
    pub fn new()->Self{
        Query{
            sql_type:SqlType::SELECT,
            distinct:false,
            declared_query: BTreeMap::new(),
            enumerated_fields: vec![],
            renamed_columns:BTreeMap::new(),
            distinct_on_columns: vec![],
            filters: vec![],
            joins: vec![],
            order_by: vec![],
            group_by: vec![],
            having: vec![],
            excluded_columns:vec![],
            page:None,
            page_size:None,
            from: None,
            values:vec![],
            enumerated_returns: vec![],
        }
    }
    
    pub fn select()->Self{
        let mut q = Query::new();
        q.sql_type = SqlType::SELECT;
        q
    }
    
    pub fn insert()->Self{
        let mut q = Query::new();
        q.sql_type = SqlType::INSERT;
        q
    }
    pub fn update()->Self{
        let mut q = Query::new();
        q.sql_type = SqlType::UPDATE;
        q
    }
    pub fn delete()->Self{
        let mut q = Query::new();
        q.sql_type = SqlType::DELETE;
        q
    }
    
    /// add DISTINCT ie: SELECT DISTINCT
    pub fn set_distinct(&mut self)->&mut Self{
        self.distinct = true;
        self
    }
    
    pub fn select_all(&mut self)->&mut Self{
        self.enumerate_column("*")
    }
    
    /// all enumerated columns shall be called from this
    /// any conflict of columns from some other table will be automatically renamed
    /// columns that are not conflicts from some other table,
    /// but is the other conflicting column is not explicityly enumerated will not be renamed
    /// 
    pub fn enumerate_column(&mut self, column:&str)->&mut Self{
        let column_name = ColumnName::from_str(column);
        let operand = Operand::ColumnName(column_name);
        let field = Field{operand:operand, name:None};
        self.enumerated_fields.push(field);
        self
    }
    
    
    pub fn enumerate_columns(&mut self, columns:Vec<&str>)->&mut Self{
        for c in columns{
            self.enumerate_column(c);
        }
        self
    }
    
    pub fn group_by(&mut self, columns:Vec<&str>)->&mut Self{
        for c in columns{
            let column_name = ColumnName::from_str(c);
            let operand = Operand::ColumnName(column_name);
            self.group_by.push(operand);
        }
        self
    }
    
    pub fn having(&mut self, column:&str, equality: Equality, value :&ToType)->&mut Self{
        let column_name = ColumnName::from_str(column);
        let left_operand = Operand::ColumnName(column_name);
        let cond = Condition{
            left_operand: left_operand,
            equality: equality,
            right_operand: Operand::Value(value.to_db_type())
        };
        self.having.push(cond);
        self
    }
    
    pub fn enumerate(&mut self, columns:Vec<&str>)->&mut Self{
        self.enumerate_columns(columns)
    }
    
    /// exclude columns when inserting/updating data
    /// also ignores the column when selecting records
    /// useful for manipulating thin records by excluding huge binary blobs such as images
    pub fn exclude_column(&mut self, column:&str)->&mut Self{
        let c = ColumnName::from_str(column);
        self.excluded_columns.push(c);
        self
    }
    pub fn exclude_columns(&mut self, columns:Vec<&str>)->&mut Self{
        for c in columns{
            self.exclude_column(c);
        }
        self
    }
    
    pub fn distinct_on_columns(&mut self, columns:&Vec<String>)->&mut Self{
        let columns = columns.clone();
        for c in columns{
            self.distinct_on_columns.push(c);
        }
        self
    }
    
    /// when paging multiple records
    pub fn set_page(&mut self, page:usize)->&mut Self{
        self.page = Some(page);
        self
    }
    
    /// the number of items retrieve per page
    pub fn set_page_size(&mut self, items:usize)->&mut Self{
        self.page_size = Some(items);
        self
    }

    /// the number of items retrieve per page
    pub fn limit(&mut self, limit:usize)->&mut Self{
        self.set_page_size(limit)
    }
    /// The base table where the resulting records will be retrieved from
    pub fn from_table(&mut self, table:&Table)->&mut Self{
        let table_name = TableName::from_table(table);
        let operand = Operand::TableName(table_name);
        let field = Field{ operand:operand, name: None};
        self.from_field(field)
    }
    
    /// A more terse way to write the query
    pub fn from<T: IsTable>(&mut self)->&mut Self{
        self.from_table(&T::table())
    }
    
    /// just an alias for from_table to make it terse for Insert queries
    pub fn into_table(&mut self, table:&Table)->&mut Self{
        self.sql_type = SqlType::INSERT;
        self.from_table(table)
    }
    
    pub fn into<T:IsTable>(&mut self)->&mut Self{
        self.into_table(&T::table())
    }
    
    /// if the database support CTE declareted query i.e WITH, 
    /// then this query will be declared
    /// if database doesn't support WITH queries, then this query will be 
    /// wrapped in the from_query
    /// build a builder for this
    pub fn declare_query(&mut self, query:Query, alias:&str)->&mut Self{
        self.declared_query.insert(alias.to_string(), query);
        self
    }
    
    /// a query to query from
    /// use WITH (query) t1 SELECT from t1 declaration in postgresql, sqlite
    /// use SELECT FROM (query) in oracle, mysql, others 
    /// alias of the table
    pub fn from_query(&mut self, query:Query, alias:&str)->&mut Self{
        let operand = Operand::Query(query);
        let field = Field{operand:operand, name:Some(alias.to_string())};
        self.from_field(field)
    }
    
    pub fn from_field(&mut self, field:Field)->&mut Self{
        self.from = Some(Box::new(field));
        self
    }
    
    pub fn get_from_table(&self)->Option<&TableName>{
        match self.from{
            Some(ref field) => {
                match field.operand{
                    Operand::TableName(ref table_name) => {
                        Some(table_name)
                     },
                    _ => None
                }
            },
            None => None,
        }
    }
    
    /// list down the columns of this table then add it to the enumerated list of columns
    pub fn enumerate_table_all_columns(&mut self, table: &Table)->&mut Self{
        for c in &table.columns{
            let column_name = ColumnName::from_column(c, table);
            let operand = Operand::ColumnName(column_name);
            let field = Field{operand:operand, name:None};
            self.enumerated_fields.push(field);
        }
        self
    }
    
    /// join a table on this query
    ///
    /// # Examples
    ///
    /// ```
    /// let mut q = Query::new();
    /// let join = Join{
    ///        modifier:Some(Modifier::LEFT),
    ///        join_type:Type::OUTER,
    ///        table:table,
    ///        column1:vec![column1],
    ///        column2:vec![column2]
    ///    };
    ///
    /// q.join(join);
    ///
    /// ```
    pub fn join(&mut self, join:Join)->&mut Self{
        self.joins.push(join);
        self
    }
    
    
    /// join a table on this query
    ///
    /// # Examples
    ///
    /// ```
    /// let mut q = Query::new();
    /// q.select_from_table("users");
    /// q.left_join("roles", "role_id", "role_id");
    ///
    /// ```
    
    pub fn left_join(&mut self, table:&Table, column1:&str, column2:&str)->&mut Self{
        let join = Join{
            modifier:Some(Modifier::LEFT),
            join_type:JoinType::OUTER,
            table_name: TableName::from_table(table),
            column1:vec![column1.to_string()],
            column2:vec![column2.to_string()]
        };
        self.join(join)
    }
    pub fn right_join(&mut self, table:&Table, column1:&str, column2:&str)->&mut Self{
        let join = Join{
            modifier:Some(Modifier::RIGHT),
            join_type:JoinType::OUTER,
            table_name: TableName::from_table(table),
            column1:vec![column1.to_string()],
            column2:vec![column2.to_string()]
        };
        self.join(join)
    }
    
    pub fn full_join(&mut self, table:&Table, column1:&str, column2:&str)->&mut Self{
        let join = Join{
            modifier:Some(Modifier::FULL),
            join_type:JoinType::OUTER,
            table_name: TableName::from_table(table),
            column1:vec![column1.to_string()],
            column2:vec![column2.to_string()]
        };
        self.join(join)
    }
    
    pub fn inner_join(&mut self, table:&Table, column1:&str, column2:&str)->&mut Self{
        let join  = Join{
            modifier:None,
            join_type:JoinType::INNER,
            table_name: TableName::from_table(table),
            column1:vec![column1.to_string()],
            column2:vec![column2.to_string()]
        };
        self.join(join)
    }
    
    ///ascending orderby of this column
    pub fn asc(&mut self, column:&str)->&mut Self{
        self.order_by.push((column.to_string(), Direction::ASC));
        self
    }
        ///ascending orderby of this column
    pub fn desc(&mut self, column:&str)->&mut Self{
        self.order_by.push((column.to_string(), Direction::DESC));
        self
    }
    
    
    pub fn rename(&mut self, table:&str, column:&str, new_column_name:&str)->&mut Self{
        if self.renamed_columns.get(table).is_some(){
            let mut list:&mut Vec<(String, String)> = self.renamed_columns.get_mut(table).unwrap();
            if list.contains(&(column.to_string(), new_column_name.to_string())){
                println!("This is already renamed");
            }else{
                println!("renamed {} to {}", column, new_column_name);
                list.push((column.to_string(), new_column_name.to_string()));
            }
        }
        else{
            self.renamed_columns.insert(table.to_string(), vec![(column.to_string(), new_column_name.to_string())]);
        }
        self
    }
    
    pub fn get_involved_tables(&self)->Vec<&TableName>{
        let mut tables = vec![];
        let from_table = self.get_from_table();
        if from_table.is_some(){
            tables.push(from_table.unwrap());
        }
        for j in &self.joins{
            if !tables.contains(&&j.table_name){
                tables.push(&j.table_name);
            }
        }
        tables
    }
    
    /// preprocess the missing fields of the query,
    /// such as mentioning the columns of the from_table
    /// enumerate the columns of the involved tables
    /// skipping those which are explicitly ignored
    /// the query will then be built and ready to be executed
    /// TODO: renamed conflicting enumerated columns
    /// if no enumerated fields and no excluded columns
    /// do a select all
    pub fn finalize(&mut self)->&mut Self{
         if self.excluded_columns.is_empty() 
            && self.enumerated_fields.is_empty(){
            self.select_all();
        }
        let excluded_columns = &self.excluded_columns.clone();
        for i in  excluded_columns{
            self.remove_from_enumerated(&i);
        }
        self
    }
    
    fn remove_from_enumerated(&mut self, column_name: &ColumnName)->&mut Self{
        fn index_of(enumerated_fields:&Vec<Field>, column: &ColumnName)->Option<usize>{
            let mut cnt = 0;
            for field in enumerated_fields{
                match field.operand{
                    Operand::ColumnName(ref column_name) => {
                        if column_name == column{
                            return Some(cnt);
                        }
                    },
                    _ => {},
                }
                cnt += 1;
            }
            None
        }
        let index = index_of(&self.enumerated_fields, column_name);
        if index.is_some(){
            self.enumerated_fields.remove(index.unwrap());
        }
        self
    }
    
    /// return the list of enumerated columns
    /// will be used for updating records
    pub fn get_enumerated_columns(&self)->Vec<&ColumnName>{
        let mut columns = vec![];
        for field in &self.enumerated_fields{
            match field.operand{
                Operand::ColumnName(ref column_name) => {
                      columns.push(column_name);
                },
                _ => {},
            }
        }
        columns
    }
    
    
    pub fn add_filter(&mut self, filter:Filter)->&mut Self{
        self.filters.push(filter);
        self
    }
    
    pub fn filter(&mut self, column:&str, equality:Equality, value:&ToType)->&mut Self{
        self.add_filter(Filter::new(column, equality, value))
    }
    
    pub fn add_value(&mut self, value:Operand)->&mut Self{
        self.values.push(value);
        self
    }
    
    pub fn value(&mut self, value:&ToType)->&mut Self{
        let operand = Operand::Value(value.to_db_type());
        self.add_value(operand)
    }
    
    pub fn enumerate_all_table_column_as_return(&mut self, table:&Table)->&mut Self{
         for c in &table.columns{
            let column_name = ColumnName::from_column(c, table);
            let operand = Operand::ColumnName(column_name);
            let field = Field{operand: operand, name:None};
            self.enumerated_returns.push(field);
        }
         self
    }
    pub fn returns(&mut self, columns: Vec<&str>)->&mut Self{
        for c in columns{
            self.enumerate_column_as_return(c);
        }
        self
    }
    
    pub fn enumerate_column_as_return(&mut self, column:&str)->&mut Self{
        let column_name = ColumnName::from_str(column);
        let operand = Operand::ColumnName(column_name);
        let field = Field{operand: operand, name:None};
        self.enumerated_returns.push(field);
        self
    }
    
    /// build the query only, not executed, useful when debugging
    pub fn build(&self, db: &Database)->SqlFrag{
        db.build_query(self)
    }
    
    /// expects a return, such as select, insert/update with returning clause
    fn execute_with_return(&mut self, db: &Database)->DaoResult{
        self.finalize();
        db.execute_with_return(self)
    }
    
       /// expects a return, such as select, insert/update with returning clause
    pub fn execute_with_one_return(&mut self, db: &Database)->Dao{
        self.finalize();
        db.execute_with_one_return(self)
    }
    
    /// delete, update without caring for the return
    pub fn execute(&mut self, db: &Database)->Result<usize, String>{
        self.finalize();
        db.execute(self)
    }
    
    /// execute the query, then convert the result
    pub fn collect<T: IsDao>(&mut self, db: &Database)->Vec<T>{
        let result = self.execute_with_return(db);
        T::from_dao_result(&result)
    }
    
    /// execute the query then collect only 1 record
    /// put a limit 1 if not already
    pub fn collect_one<T: IsDao>(&mut self, db: &Database)->T{
        if self.page_size.is_none(){
            self.limit(1);
        }
        let result = self.execute_with_return(db);
        let mut dao:Vec<T> = T::from_dao_result(&result);
        assert!(dao.len() == 1, "There should only be 1 returned record");
        dao.remove(0)
    }
}