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
use std::collections::BTreeMap;
use uuid::Uuid;
use chrono::datetime::DateTime;
use chrono::naive::date::NaiveDate;
use chrono::naive::time::NaiveTime;
use chrono::naive::datetime::NaiveDateTime;
use chrono::offset::utc::UTC;
use std::fmt;
use query::ColumnName;
use table::IsTable;
use rustc_serialize::{Encodable,Encoder};
use rustc_serialize::json::{ToJson, Json};

#[derive(Debug)]
#[derive(Clone)]
#[derive(PartialEq)]
///supported generic datatypes for an ORM
pub enum Type{
    Bool,
    I8,
    I16,
    I32,
    I64,
    U8,
    U16,
    U32,
    U64,
    F32,
    F64,
    String,
    VecU8,
    Object,
    Json,
    Uuid,
    DateTime,
    NaiveDate,
    NaiveTime,
    NaiveDateTime,
}


#[derive(Debug)]
#[derive(Clone)]
#[derive(PartialEq)]
///supported generic datatypes for an ORM
pub enum Value{
    Bool(bool),
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    F32(f32),
    F64(f64),
    String(String),
    VecU8(Vec<u8>),
    Object(BTreeMap<String, Value>),
    Json(Json),
    Uuid(Uuid),
    DateTime(DateTime<UTC>),
    NaiveDate(NaiveDate),
    NaiveTime(NaiveTime),
    NaiveDateTime(NaiveDateTime),
    Null,
}


/// custom implementation for value encoding to json,
/// does not include unnecessary enum variants fields.
impl Encodable for Value{
    
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        match *self {
            Value::Bool(ref x) => x.encode(s),
            Value::I8(ref x) => x.encode(s),
            Value::I16(ref x) => x.encode(s),
            Value::I32(ref x) => x.encode(s),
            Value::I64(ref x) => x.encode(s),
            Value::U8(ref x) => x.encode(s),
            Value::U16(ref x) => x.encode(s),
            Value::U32(ref x) => x.encode(s),
            Value::U64(ref x) => x.encode(s),
            Value::F32(ref x) => x.encode(s),
            Value::F64(ref x) => x.encode(s),
            Value::String(ref x) => x.encode(s),
            Value::VecU8(ref x) => x.encode(s),
            Value::Uuid(ref x) => x.encode(s),
            Value::DateTime(ref x) => {
                println!("encoding date time: {}", x.to_rfc3339());
                x.to_rfc3339().encode(s)
            },
            Value::NaiveDate(ref x) => x.encode(s),
            Value::NaiveTime(ref x) => x.encode(s),
            Value::NaiveDateTime(ref x) => x.encode(s),
            Value::Object(ref x) => x.encode(s),
            Value::Json(ref x) => x.encode(s),
            Value::Null => s.emit_nil(),
        }
    }
}
impl ToJson for Value{
    
    fn to_json(&self) -> Json{
                match *self {
            Value::Bool(ref x) => x.to_json(),
            Value::I8(ref x) => x.to_json(),
            Value::I16(ref x) => x.to_json(),
            Value::I32(ref x) => x.to_json(),
            Value::I64(ref x) => x.to_json(),
            Value::U8(ref x) => x.to_json(),
            Value::U16(ref x) => x.to_json(),
            Value::U32(ref x) => x.to_json(),
            Value::U64(ref x) => x.to_json(),
            Value::F32(ref x) => x.to_json(),
            Value::F64(ref x) => x.to_json(),
            Value::String(ref x) => x.to_json(),
            Value::VecU8(ref x) => x.to_json(),
            Value::Uuid(ref x) => x.to_hyphenated_string().to_json(),
            Value::DateTime(ref x) => x.to_rfc3339().to_json(),
//            Value::NaiveDate(ref x) => x.to_json(),
//            Value::NaiveTime(ref x) => x.to_json(),
//            Value::NaiveDateTime(ref x) => x.to_json(),
            Value::Object(ref x) => x.to_json(),
            Value::Json(ref x) => x.clone(),
            Value::Null => Json::Null,
             _ => panic!("unsupported/unexpected type! {:?}", self),
        }
    }
}


impl fmt::Display for Value{
    
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Value::Bool(ref x) => write!(f, "'{}'", x),
            Value::I8(ref x) => write!(f, "'{}'", x),
            Value::I16(ref x) => write!(f, "'{}'", x),
            Value::I32(ref x) => write!(f, "'{}'", x),
            Value::I64(ref x) => write!(f, "'{}'", x),
            Value::U8(ref x) => write!(f, "'{}'", x),
            Value::U16(ref x) => write!(f, "'{}'", x),
            Value::U32(ref x) => write!(f, "'{}'", x),
            Value::U64(ref x) => write!(f, "'{}'", x),
            Value::String(ref x) => write!(f, "'{}'", x),
            Value::VecU8(ref x) => write!(f, "'{:?}'", x),
            Value::Uuid(ref x) => write!(f, "'{}'", x),
            Value::DateTime(ref x) => write!(f, "'{}'", x),
            Value::NaiveDate(ref x) => write!(f, "'{}'", x),
            Value::NaiveTime(ref x) => write!(f, "'{}'", x),
            Value::NaiveDateTime(ref x) => write!(f, "'{}'", x),
            Value::Object(ref x) => write!(f, "'{:?}'", x),
            Value::Json(ref x) => write!(f, "'{:?}'", x),
            Value::Null => write!(f, "'nil'"),
            _ => panic!("unsupported/unexpected type! {:?}", self),
        }
    }
}


/// trait for converting dao to model
/// sized and clonable
pub trait IsDao{
    
    /// convert dao to an instance of the corresponding struct of the model
    /// taking into considerating the renamed columns
    fn from_dao(dao: &Dao)->Self;
    
    /// convert from an instance of the struct to a dao representation
    /// to be saved into the database
    fn to_dao(&self)->Dao;
}

/// Ignore Column are columns that are redundant when displaying as API results
pub trait ToCompact{
    
    /// list of redundant fields that will be removed when doing a compact serialization
    fn redundant_fields(&self)->Vec<&str>;
    
    /// compact BTreeMap represetation
    fn compact_map(&self)->BTreeMap<String, Value>;
    
    /// compact dao representation
    fn compact_dao(&self)->Dao;
    
    /// compact dao representation
    fn compact_json(&self)->Json;
}

/// meta result of a query useful when doing complex query, and also with paging
/// TODO: good name: DaoRows
#[derive(Debug)]
pub struct DaoResult{
    pub dao: Vec<Dao>,
    ///renamed columns for each table
    /// ie. product => [(name, product_name),..];
    pub renamed_columns: Vec< (ColumnName, String) >, 
    
    /// the total number of records
    pub total:Option<usize>,
    /// page of the query
    pub page: Option<usize>,
    /// page size
    pub page_size: Option<usize>,
}

/// a serializable array of dao to be serialized to json request
#[derive(RustcEncodable)]
pub struct SerDaoResult{
    pub dao: Vec<Dao>,
    pub total:Option<usize>,
    pub page: Option<usize>,
    pub page_size: Option<usize>,
}

impl SerDaoResult{
    
    pub fn from_dao_result(daoresult: DaoResult)->Self{
        SerDaoResult{
            dao: daoresult.dao,
            total: daoresult.total,
            page: daoresult.page,
            page_size: daoresult.page_size
        }
    }
}

impl Encodable for DaoResult{
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>{
        self.dao.encode(s)
    }
}

impl DaoResult{
    /// get the list of renamed column name in matching table name
    fn get_renamed_columns(&self, table:&str)->Vec< (String, String) >{
        let mut columns = vec![];
        for &(ref col, ref rename) in &self.renamed_columns{
            if col.table.is_some(){
                if col.table.as_ref().unwrap() == table{
                    columns.push( (col.column.to_owned(), rename.to_owned()) );
                }
            }
        }
        columns
    }
    
    /// cast the dao to the specific struct instance
    /// do not include if non nullable parts contains null
    pub fn cast<T:IsTable+IsDao>(&self)->Vec<T>{
        let table = T::table();
        let non_nulls = table.non_nullable_columns();
        let mut obj = vec![];
        let renamed_columns = self.get_renamed_columns(&table.name);
        for dao in &self.dao{
            let mut dao_clone = dao.clone();
            dao_clone.correct_renamed_columns(&renamed_columns);
            if dao_clone.all_has_values(&non_nulls){
                let p = T::from_dao(&dao_clone);
                obj.push(p);
            }
        }
        obj
    }
    
    pub fn cast_one<T:IsTable+IsDao>(&self)->Option<T>{
        let mut casted = self.cast::<T>();
        if casted.len() < 1{
            return None;
        }
        assert!(casted.len() == 1);
        Some(casted.remove(0))
    }
}

#[derive(Debug, Clone)]
/// TODO: optimization, used enum types for the key values
/// This will save allocation of string to enum keys which is a few bytes, int 
pub struct Dao{
    pub values:BTreeMap<String, Value>,
}

/// custom Encoder for Dao,
/// decodes directly the content of `values`, instead of `values` as field of this `Dao` struct
impl Encodable for Dao{
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>{
        self.values.encode(s)
    }
}

//impl Decodable for Dao{
//    
//    fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>{
//        d.read_map()
//    }
//}
impl ToJson for Dao{
    
    fn to_json(&self) -> Json{
        let mut btree = BTreeMap::new();
        for (key, value) in &self.values{
            btree.insert(key.to_owned(), value.to_json());
        }
        Json::Object(btree)
    }
    
}

impl Dao{

    pub fn new()->Self{
        Dao{values:BTreeMap::new()}
    }
    
    pub fn set(&mut self, column: &str, value:&ToValue){
        self.values.insert(column.to_owned(), value.to_db_type());
    }
    
    /// set to null the value of this column
    pub fn set_null(&mut self, column: &str){
        self.set_value(column, Value::Null);
    }
    
    pub fn set_value(&mut self, column: &str, value:Value){
        self.values.insert(column.to_owned(), value);
    }
    pub fn get_value(&self, column: &str)->Value{
        let value = self.values.get(column);
        match value{
            Some(value) => value.clone(),
            None => panic!("No such value for {}", column),
        }
    }
    /// take the value and remove the content 
    pub fn remove<T>(&mut self, column: &str) -> T where T: FromValue{
        let value = self.values.remove(column).unwrap();
        FromValue::from_type(value)
    }

    /// take the value but not removing the content
    pub fn get<T>(&self, column: &str) -> T where T: FromValue{
        let value = self.values.get(column).unwrap();
        FromValue::from_type(value.clone())
    }
    /// get optional value
    pub fn get_opt<T>(&self, column: &str) -> Option<T> where T: FromValue{
        let value = self.values.get(column);
        if value.is_some(){
            let v = value.as_ref().unwrap().clone();
            match v{
                &Value::Null => None,
                _ => Some(FromValue::from_type(v.clone()))
            }
        }else{
            None
        }
    }
    
    /// get a reference of the type
    pub fn as_ref(&self, column: &str)->&Value{
        self.values.get(column).unwrap()
    }
    
    
    fn correct_renamed_columns(&mut self, renamed_columns:&Vec<(String, String)>){
        for &(ref column, ref rename) in renamed_columns{
            let value = self.get_value(rename);
            self.set_value(&column, value);
        }
    }
    
    fn all_has_values(&self, non_nulls: &Vec<String>)->bool{
        for column in non_nulls{
            let value = self.values.get(column);
            if value.is_none(){
                return false;
            }
            if value.is_some(){
                let v = value.as_ref().unwrap().clone();
                match v{
                    &Value::Null => return false,
                    _ => ()
                };
            }
        }
        true
    }
    
    
    pub fn as_map(&self)->&BTreeMap<String, Value>{
        &self.values
    }
}


/// rename to ToValue
pub trait ToValue{
    fn to_db_type(&self)->Value;
}

impl ToValue for Value {
    fn to_db_type(&self)->Value{
        self.clone()
    }
}

impl ToValue for (){
    fn to_db_type(&self)->Value{
        Value::Null
    }
}

impl ToValue for bool{
    fn to_db_type(&self)->Value{
        Value::Bool(self.clone())
    }
}

/// signed INTs
impl ToValue for i8{
    fn to_db_type(&self)->Value{
        Value::I8(self.clone())
    }
}

impl ToValue for i16{
    fn to_db_type(&self)->Value{
        Value::I16(self.clone())
    }
}
impl ToValue for i32{
    fn to_db_type(&self)->Value{
        Value::I32(self.clone())
    }
}

impl ToValue for i64{
    fn to_db_type(&self)->Value{
        Value::I64(self.clone())
    }
}
/// unsigned INTs
impl ToValue for u8{
    fn to_db_type(&self)->Value{
        Value::U8(self.clone())
    }
}

impl ToValue for u16{
    fn to_db_type(&self)->Value{
        Value::U16(self.clone())
    }
}
impl ToValue for u32{
    fn to_db_type(&self)->Value{
        Value::U32(self.clone())
    }
}

impl ToValue for u64{
    fn to_db_type(&self)->Value{
        Value::U64(self.clone())
    }
}

impl ToValue for f32{
    fn to_db_type(&self)->Value{
        Value::F32(self.clone())
    }
}

impl ToValue for f64{
    fn to_db_type(&self)->Value{
        Value::F64(self.clone())
    }
}

impl <'a>ToValue for &'a str{
    fn to_db_type(&self)->Value{
        Value::String(self.to_string())
    }
}

impl ToValue for String{
    fn to_db_type(&self)->Value{
        Value::String(self.clone())
    }
}

impl ToValue for Uuid{
    fn to_db_type(&self)->Value{
        Value::Uuid(self.clone())
    }
}

impl ToValue for DateTime<UTC>{
    fn to_db_type(&self)->Value{
        Value::DateTime(self.clone())
    }
}

impl ToValue for NaiveDate{
    fn to_db_type(&self)->Value{
        Value::NaiveDate(self.clone())
    }
}

impl ToValue for NaiveTime{
    fn to_db_type(&self)->Value{
        Value::NaiveTime(self.clone())
    }
}
impl ToValue for NaiveDateTime{
    fn to_db_type(&self)->Value{
        Value::NaiveDateTime(self.clone())
    }
}

///
///
///
///
///
///
///
///
///
///
///
///
///
pub trait FromValue{
    fn from_type(ty:Value)->Self;
}

impl FromValue for bool{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::Bool(x) => x,
            _ => panic!("error!"),
        }
    }
}

impl FromValue for i8{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::I8(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for i16{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::I16(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for i32{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::I32(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for i64{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::I64(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for u8{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::U8(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for u16{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::U16(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for u32{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::U32(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for u64{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::U64(x) => x,
            _ => panic!("error!"),
        }
    }
}

impl FromValue for f32{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::F32(x) => x,
            _ => panic!("error!"),
        }
    }
}
impl FromValue for f64{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::F64(x) => x,
            _ => panic!("error! {:?}",ty),
        }
    }
}

impl FromValue for String{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::String(x) => x,
            _ => panic!("error! {:?}", ty),
        }
    }
}

impl FromValue for Uuid{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::Uuid(x) => x,
            _ => panic!("error!"),
        }
    }
}

impl FromValue for DateTime<UTC>{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::DateTime(x) => x,
            _ => panic!("error!"),
        }
    }
}

impl FromValue for NaiveTime{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::NaiveTime(x) => x,
            _ => panic!("error!"),
        }
    }
}

impl FromValue for NaiveDate{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::NaiveDate(x) => x,
            _ => panic!("error!"),
        }
    }
}

impl FromValue for NaiveDateTime{
    fn from_type(ty:Value)->Self{
        match ty{
            Value::NaiveDateTime(x) => x,
            _ => panic!("error!"),
        }
    }
}



#[test]
fn test_dao(){
    let s = "lee";
    let n = 20i8;
    let date = UTC::now();
    let mut d = Dao::new();
    d.set("name", &s);
    d.set("age", &n);
    d.set("created", &date);
    let name:String = d.get("name");
    let age:i8 = d.get("age");
    let created:DateTime<UTC> = d.get("created");
    let none:Option<u8> = d.get_opt("none");
    assert_eq!(name, s);
    assert_eq!(age, 20i8);
    assert_eq!(date, created);
    assert_eq!(none, None);
}

#[test]
fn test_json(){
    let s = "lee";
    let n = 20i8;
    let date = UTC::now();
    let mut dao = Dao::new();
    dao.set("name", &s);
    dao.set("age", &n);
    dao.set("created", &date);
    let name:String = dao.get("name");
    let age:i8 = dao.get("age");
    let created:DateTime<UTC> = dao.get("created");
    let none:Option<u8> = dao.get_opt("none");
    let expected = r#"{"age":20,"created":{"datetime":{"date":{"ymdf":16510090},"time":{"secs":28087,"frac":451865185}},"offset":{}},"name":"lee"}"#;
    let actual = json::encode(&dao).unwrap();
    println!("expected: {}", expected);
    println!("actual: {}",actual);
}