rustorm 0.7.0

An ORM for rust
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
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
use query::Operand;
use query::operand::ToOperand;
use dao::ToValue;
use database::Database;
use dao::DaoResult;
use dao::IsDao;
use dao::Dao;
use writer::SqlFrag;
use database::DbError;
use database::BuildMode;
use query::ColumnName;
use query::column_name::ToColumnName;
use query::{TableName, ToTableName};
use query::{Filter, Equality};
//use query::QueryBuilder;
use query::Function;
use query::Join;
use query::Order;
use query::Field;
use query::SourceField;
use query::{QuerySource, ToSourceField};
use table::Column;
use query::IsTable;
use std::convert::From;


pub enum Query{
    Select(Select),
    Insert(Insert),
    Update(Update),
    Delete(Delete),
}

pub trait IsQuery{
    /// build the query only, not executed, useful when debugging
    fn build(&mut self, db: &Database) -> SqlFrag;

    /// Warning: don't use this in production
    fn debug_build(&mut self, db: &Database) -> SqlFrag;

}


/// Query Error
pub enum Error {
    NoTableSpecified(String),
    NoColumnSpecified(String),
    SqlError(String),
}



#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Default)]
#[derive(Clone)]
pub struct Range {
    pub limit: Option<usize>,
    pub offset: Option<usize>,
}

impl Range {
    pub fn new() -> Self {
        Range {
            limit: None,
            offset: None,
        }
    }

    pub fn set_limit(&mut self, limit: usize) {
        self.limit = Some(limit);
    }
    pub fn set_offset(&mut self, offset: usize) {
        self.offset = Some(offset);
    }
}


#[derive(Debug)]
#[derive(Clone)]
pub struct DeclaredQuery{
    pub name: String,
    pub fields: Vec<String>,
    pub query: Select,
    pub is_recursive: bool
}


#[derive(Debug)]
#[derive(Clone)]
pub struct Select {
    /// whether to select the records distinct
    pub distinct: bool,

    /// whether to enumate all columns in involved models
    pub enumerate_all: bool,

    pub declared_query: Vec<DeclaredQuery>,

    /// fields can be functions, column sql query, and even columns
    pub enumerated_fields: Vec<Field>,

    /// specify to use distinct ON set of columns
    pub distinct_on_columns: Vec<String>,

    /// 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, or function
    pub from: Vec<SourceField>,

    /// joining multiple tables
    pub joins: Vec<Join>,

    /// filter records, ~ where statement of the query
    pub filters: Vec<Filter>,

    /// ordering of the records via the columns specified
    pub order_by: Vec<Order>,

    /// grouping columns to create an aggregate
    pub group_by: Vec<Operand>,

    /// having field,
    pub having: Vec<Filter>,

    /// exclude the mention of the columns in the SQL query, useful when ignoring changes in update/insert records
    pub excluded_columns: Vec<ColumnName>,

    /// caters both limit->offset and page->page_size
    /// setting page and page_size can not interchange the order
    pub range: Range,
    /// 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>,

    /// enable query stats
    pub enable_query_stat: bool,
}

impl Select {
    /// the default query is select
    pub fn new() -> Self {
        Select{
            distinct: false,
            enumerate_all: false,
            declared_query: vec![],
            enumerated_fields: vec![],
            distinct_on_columns: vec![],
            filters: vec![],
            joins: vec![],
            order_by: vec![],
            group_by: vec![],
            having: vec![],
            excluded_columns: vec![],
            range: Range::new(),
            from: vec![],
            values: vec![],
            enumerated_returns: vec![],
            enable_query_stat: true,
        }
    }


    pub fn enumerate_all(&mut self) {
        self.enumerate_all = true;
    }

    pub fn all() -> Self {
        let mut q = Self::new();
        q.column_star();
        q
    }

    fn column_star(&mut self){
        self.column("*");
    }

    fn enumerate<C>(&mut self, column_name: C) where C: Into<ColumnName>{
        let operand = Operand::ColumnName(column_name.into());
        let field = Field {
            operand: operand,
            name: None,
        };
        self.enumerated_fields.push(field);
    }

    /// 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 column(&mut self, column: &str) {
        let column_name = ColumnName::from(column);
        self.enumerate(column_name);
    }


    pub fn columns(&mut self, columns: Vec<&str>) {
        for c in columns {
            self.column(c);
        }
    }


    /// 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) {
        let c = ColumnName::from(column);
        self.excluded_columns.push(c);
    }
    pub fn exclude_columns(&mut self, columns: Vec<&str>) {
        for c in columns {
            self.exclude_column(c);
        }
    }

    pub fn distinct_on_columns(&mut self, columns: &Vec<String>) {
        let columns = columns.clone();
        for c in columns {
            self.distinct_on_columns.push(c);
        }
    }

    pub fn value(&mut self, value: &ToValue) {
        let value = value.to_db_type();
        self.values.push(Operand::Value(value));
    }

    pub fn set_limit(&mut self, limit: usize) {
        self.range.set_limit(limit);
    }
    pub fn set_offset(&mut self, offset: usize) {
        self.range.set_offset(offset);
    }

    pub fn get_range(&self) -> Range {
        self.range.to_owned()
    }

    /// enumerate only the columns that is coming from this table
    /// this will invalidate enumerate_all
    pub fn only_from(&mut self, table: &ToTableName) {
        self.enumerate_all = false;
        self.enumerate_from_table(&table.to_table_name());
    }



    /// 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: Select, alias: &str) {
        let sf = SourceField {
            source: QuerySource::Query(query),
            rename: Some(alias.to_owned()),
        };
        self.from.push(sf);
    }

    pub fn from(&mut self, to_source_field: &ToSourceField) {
        self.from.append(&mut to_source_field.to_source_field());
    }

    pub fn table(&mut self, to_source_field: &ToSourceField) {
        self.from(to_source_field);
    }
    /// returns the first table in the from clause
    pub fn get_from_table(&self) -> Option<TableName> {
        for fr in &self.from {
            match &fr.source {
                &QuerySource::TableName(ref table_name) => {
                    return Some(table_name.to_owned());
                }
                _ => {} 
            }
        }
        None
    }


    /// get the indexes of the fields that matches the the column name
    fn match_fields_indexes(&self, column: &str) -> Vec<usize> {
        let mut indexes = vec![];
        let mut cnt = 0;
        for field in &self.enumerated_fields {
            if let Operand::ColumnName(ref column_name) = field.operand {
                if column_name.column == column {
                    indexes.push(cnt);
                }
            }
            cnt += 1;
        }
        indexes
    }

    /// take the enumerated field that is a column that matched the name
    fn rename_fields(&mut self, column: &str) {
        let matched_indexes = self.match_fields_indexes(column);
        for index in matched_indexes {
            let field = self.enumerated_fields.remove(index);//remove it
            let field = field.rename(); //rename it
            self.enumerated_fields.insert(index, field); //insert it back to the same location
        }
    }

    pub fn get_involved_tables(&self) -> Vec<TableName> {
        let mut tables = vec![];
        let from_table = self.get_from_table();
        if let Some(from) = from_table {
            tables.push(from.clone());
        }
        for j in &self.joins {
            if !tables.contains(&&j.table_name) {
                tables.push(j.table_name.clone());
            }
        }
        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
    /// if no enumerated fields and no excluded columns
    /// do a select all
    pub fn finalize(&mut self) -> &Self {

        let involved_models = self.get_involved_tables();
        if involved_models.len() > 1 {
            // enumerate all columns when there is a join
            if self.enumerate_all {
                self.enumerate_involved_tables_columns(&involved_models);
            }
            self.rename_conflicting_columns(); // rename an enumerated columns that conflicts
        }
        let excluded_columns = &self.excluded_columns.clone();
        for i in excluded_columns {
            self.remove_from_enumerated(&i);
        }
        if self.excluded_columns.is_empty() && self.enumerated_fields.is_empty() {
            self.column_star();
        }
        self
    }

    fn enumerate_involved_tables_columns(&mut self, involved_models: &Vec<TableName>) {
        for m in involved_models {
            for c in &m.columns {
                self.enumerate(c.clone());
            }
        }
    }

    pub fn enumerate_from_table(&mut self, table: &TableName) {
        for c in &table.columns {
            self.enumerate(c.clone());
        }
    }

    fn get_renamed_fields(&self) -> Vec<&Field> {
        let mut renamed = vec![];
        for field in &self.enumerated_fields {
            if field.name.is_some() {
                renamed.push(field);
            }
        }
        renamed
    }

    /// return the list of renamed columns, used in dao conversion to struc types
    pub fn get_renamed_columns(&self) -> Vec<(ColumnName, String)> {
        let mut renamed_columns = vec![];
        let renamed_fields = self.get_renamed_fields();
        for field in &renamed_fields {
            if let Operand::ColumnName(ref column_name) = field.operand {
                if let Some(ref rename) = field.name {
                    renamed_columns.push((column_name.clone(), rename.to_owned()));
                }
            }
        }
        renamed_columns
    }

    /// determine which columns are conflicting and rename it accordingly
    /// rename only the columns that are in the enumerated list
    fn get_conflicting_columns(&self) -> Vec<String> {
        let mut conflicts = vec![];
        let enumerated_columns = self.get_enumerated_columns();
        for c in &enumerated_columns {
            for d in &enumerated_columns {
                if c != d && c.is_conflicted(d) {
                    conflicts.push(c.column.to_owned());
                }
            }
        }
        conflicts
    }
    /// rename the fields that has a conflicting column
    fn rename_conflicting_columns(&mut self) {
        let conflicts = self.get_conflicting_columns();
        for c in conflicts {
            self.rename_fields(&c);
        }
    }

    /// used by removed_from_enumerated
    fn index_of_field(&self, column: &ColumnName) -> Option<usize> {
        let mut cnt = 0;
        for field in &self.enumerated_fields {
            if let Operand::ColumnName(ref column_name) = field.operand {
                if column_name == column {
                    return Some(cnt);
                }
            }
            cnt += 1;
        }
        None
    }

    fn remove_from_enumerated(&mut self, column_name: &ColumnName) {
        let index = self.index_of_field(column_name);
        if let Some(idx) = index {
            self.enumerated_fields.remove(idx);
        }
    }

    /// 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 {
            if let Operand::ColumnName(ref column_name) = field.operand {
                columns.push(column_name);
            }
        }
        columns
    }


    pub fn add_filter(&mut self, filter: &Filter) {
        self.filters.push(filter.clone());
    }
    pub fn add_filters(&mut self, filters: &Vec<Filter>) {
        self.filters.extend_from_slice(filters)
    }

    /// column = value
    pub fn filter_eq(&mut self, column: &str, value: &ToValue) {
        self.add_filter(&Filter::new(column, Equality::EQ, value));
    }
    /// column < value
    pub fn filter_lt(&mut self, column: &str, value: &ToValue) {
        self.add_filter(&Filter::new(column, Equality::LT, value));
    }
    /// column <= value
    pub fn filter_lte(&mut self, column: &str, value: &ToValue) {
        self.add_filter(&Filter::new(column, Equality::LTE, value));
    }

    /// column > value
    pub fn filter_gt(&mut self, column: &str, value: &ToValue) {
        self.add_filter(&Filter::new(column, Equality::GT, value));
    }
    /// column <= value
    pub fn filter_gte(&mut self, column: &str, value: &ToValue) {
        self.add_filter(&Filter::new(column, Equality::GTE, value));
    }


    pub fn return_all(&mut self) {
        self.enumerate_column_as_return("*");
    }

    pub fn returns(&mut self, columns: Vec<&str>) {
        for c in columns {
            self.enumerate_column_as_return(c);
        }
    }

    pub fn enumerate_column_as_return(&mut self, column: &str) {
        let column_name = ColumnName::from(column);
        let operand = Operand::ColumnName(column_name);
        let field = Field {
            operand: operand,
            name: None,
        };
        self.enumerated_returns.push(field);
    }


    /// retrieve a generic types, type is unknown at runtime
    /// expects a return, such as select, insert/update with returning clause
    pub fn retrieve(&mut self, db: &Database) -> Result<DaoResult, DbError> {
        self.finalize();
        db.execute_with_return(self)
    }

    /// expects a return, such as select, insert/update with returning clause
    /// no casting of data to structs is done
    /// This is used when retrieving multiple models in 1 query, then casting the records to its equivalent structs
    pub fn retrieve_one(&mut self, db: &Database) -> Result<Option<Dao>, DbError> {
        self.finalize();
        db.execute_with_one_return(self)
    }


    /// execute the query, then convert the result
    pub fn collect<T: IsDao + IsTable>(&mut self, db: &Database) -> Result<Vec<T>, DbError> {
        let result = try!(self.retrieve(db));
        Ok(result.cast())
    }

    /// execute the query then collect only 1 record
    pub fn collect_one<T: IsDao + IsTable>(&mut self, db: &Database) -> Result<T, DbError> {
        let result = try!(self.retrieve(db));
        match result.cast_one() {
            Some(res) => Ok(res),
            None => Err(DbError::new("No entry to collect found.")),
        }
    }
}

impl IsQuery for Select{
    
    fn build(&mut self, db: &Database) -> SqlFrag{
        self.finalize();
        db.build_select(self, &BuildMode::Standard) 
    }
    
    fn debug_build(&mut self, db: &Database) -> SqlFrag{
        self.finalize();
        db.build_select(self, &BuildMode::Debug) 
    }
}
 
 pub enum Data{
    Values(Vec<Operand>),
    Query(Select),
 }

pub struct Insert{
    pub into: TableName,
    pub columns: Vec<ColumnName>,
    pub data: Data,
    pub return_columns: Vec<ColumnName>
}

impl Insert{
    
    pub fn into(table: &ToTableName) -> Self{
        Insert{
            into: table.to_table_name(),
            columns: vec![],
            data: Data::Values(vec![]),
            return_columns: vec![]
        }
    }

    pub fn columns(&mut self, columns: Vec<&str>){
        for c in columns{
            self.column(c);
        }
    }

    pub fn column(&mut self, column: &str){
        self.columns.push(column.to_column_name())
    }

    pub fn values(&mut self, operands: Vec<&ToOperand>){
        for op in operands{
            self.value(op); 
        }
    }
    
    pub fn value(&mut self, operand: &ToOperand){
        match self.data{
            Data::Values(ref mut values) => {
                (*values).push(operand.to_operand());
            },
            Data::Query(_) => panic!("can not add value to query")
        }
    }

    pub fn return_columns(&mut self, columns: Vec<&str>){
        self.return_columns.clear();
        for c in columns{
            self.return_column(c);
        }
    }

    fn return_column(&mut self, column: &str){
        self.return_columns.push(column.to_column_name());
    }

    pub fn return_all(&mut self){
        self.return_columns(vec!["*"]);
    }

    pub fn debug_build(&mut self, db: &Database) -> SqlFrag {
        db.build_insert(&self, &BuildMode::Debug)
    }

    pub fn insert<D: IsDao>(&mut self, db: &Database) -> Result<D, DbError>{
        let result = db.insert(self);
        match result{
            Ok(res) => Ok(D::from_dao(&res)),
            Err(e) => Err(e),
        }
    }

    /// set a value of a column when inserting/updating records
    pub fn set(&mut self, column: &str, value: &ToValue) {
        self.column(&column);
        self.value(&Operand::Value(value.to_db_type()));
    }
}

pub struct Update{
    pub table: TableName,
    pub columns: Vec<ColumnName>,
    pub values: Vec<Operand>,
    pub filters: Vec<Filter>,
    pub return_columns: Vec<ColumnName>
}

impl Update{
    
    pub fn table(table: &ToTableName) -> Self{
        Update{
            table: table.to_table_name(),
            columns: vec![],
            values: vec![],
            filters: vec![],
            return_columns: vec![],
        }
    }

    pub fn add_filter(&mut self, filter: &Filter){
        self.filters.push(filter.clone());
    }

    pub fn add_filters(&mut self, filters: &Vec<Filter>){
        self.filters.extend_from_slice(filters);
    }
    
    pub fn columns(&mut self, columns: &Vec<ColumnName>){
        self.columns = columns.to_owned();
    }

    pub fn value(&mut self, operand: &ToOperand){
        self.values.push(operand.to_operand());
    }

    pub fn return_all(&mut self){
        self.return_columns = vec![ColumnName::from("*")];
    }

    pub fn column(&mut self, column: &ToColumnName){
        self.columns.push(column.to_column_name());
    }

    /// set a value of a column when inserting/updating records
    pub fn set(&mut self, column: &str, value: &ToValue) {
        self.column(&column);
        self.value(&Operand::Value(value.to_db_type()));
    }
    pub fn update<D: IsDao>(&mut self, db: &Database) -> Result<D, DbError>{
        let result = db.update(self);
        match result{
            Ok(res) => Ok(D::from_dao(&res)),
            Err(e) => Err(e),
        }
    }
}

pub struct Delete{
    pub from_table: TableName,
    pub filters: Vec<Filter>
}

impl Delete{

    pub fn from(table: &ToTableName) -> Self{
        Delete{
            from_table: table.to_table_name(),
            filters: vec![]
        }
    }

    pub fn add_filter(&mut self, filter: &Filter){
        self.filters.push(filter.clone())
    }
    pub fn add_filters(&mut self, filter: Vec<Filter>){
        self.filters.extend(filter)
    }

    pub fn execute(&self, db: &Database) -> Result<usize, DbError> {
        db.delete(self)
    }
}

impl IsQuery for Delete{
    fn build(&mut self, db: &Database) -> SqlFrag{
        db.build_delete(self, &BuildMode::Standard)
    }

    fn debug_build(&mut self, db: &Database) -> SqlFrag {
        db.build_delete(self, &BuildMode::Debug)
    }
}

pub struct CreateTable{
    pub table: TableName,
    pub column: Vec<Column>
}

pub struct DropTable{
    pub table: TableName,
    pub force: bool,
}

pub struct CreateSchema{
    pub schema: String,
}

pub struct DropSchema{
    pub schema: String,
    pub force: bool
}

pub struct CreateFunction{
    pub function: Function
}

//TODO: add/drop index
// on update, on delete, on insert
pub struct AlterTable{
    pub table: String,
}

pub enum TableOrColumn{
    Table(TableName),
    Column(ColumnName)
}

pub struct Comment{
    pub target: TableOrColumn,
    pub comment: String
}

pub struct CopyTable{
    pub table: String,
    pub dao: Vec<Operand>
}


pub struct CreateExtension{
    pub extension: String,
}