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
// pub enum Value {
//     Float32(f32),
//     Float64(f64),
//     Text(String),
//     Int8(i8),
//     Int16(i16),
//     Int32(i32),
//     Int64(i64),
//     Int128(i128),
//     Isize(isize),
//     Usize(usize),
//     U32(u32),
//     U8(u8),
//     U16(u16),
//     U64(u64),
//     U128(u128),
//     Str(&'static str),
//     Nil,
// }

use std::fmt;
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use uuid::Uuid;

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Nil, // no value
    Bool(bool),

    Tinyint(i8),
    Smallint(i16),
    Int(i32),
    Bigint(i64),

    Float(f32),
    Double(f64),
    // BigDecimal(BigDecimal),

    Blob(Vec<u8>),
    Char(char),
    Text(String),
    Json(String),

    Uuid(Uuid),
    Date(NaiveDate),
    Time(NaiveTime),
    DateTime(NaiveDateTime),
    Timestamp(DateTime<Utc>),
    Interval(Interval),
    SerdeJson(mysql::serde_json::Value),

    // Point(Point<f64>),

    Array(Array),
}

#[derive(Debug, Clone, PartialEq)]
pub struct Interval {
    pub microseconds: i64,
    pub days: i32,
    pub months: i32,
}

impl Interval {
    pub fn new(microseconds: i64, days: i32, months: i32) -> Self {
        Interval {
            microseconds,
            days,
            months,
        }
    }
}

impl Value {
    pub fn is_nil(&self) -> bool {
        *self == Value::Nil
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::Nil => write!(f, ""),
            Value::Bool(v) => write!(f, "{}", v),
            Value::Tinyint(v) => write!(f, "{}", v),
            Value::Smallint(v) => write!(f, "{}", v),
            Value::Int(v) => write!(f, "{}", v),
            Value::Bigint(v) => write!(f, "{}", v),
            Value::Float(v) => write!(f, "{}", v),
            Value::Double(v) => write!(f, "{}", v),
            // Value::BigDecimal(v) => write!(f, "{}", v),
            Value::Char(v) => write!(f, "{}", v),
            Value::Text(v) => write!(f, "{}", v),
            Value::Json(v) => write!(f, "{}", v),
            Value::Uuid(v) => write!(f, "{}", v),
            Value::Date(v) => write!(f, "{}", v),
            Value::Time(v) => write!(f, "{}", v),
            Value::SerdeJson(v) => write!(f, "{}", mysql::serde_json::to_string(v).unwrap_or_default()),
            Value::DateTime(v) => write!(f, "{}", v.format("%Y-%m-%d %H:%M:%S").to_string()),
            Value::Timestamp(v) => write!(f, "{}", v.to_rfc3339()),
            Value::Array(array) => array.fmt(f),
            Value::Blob(v) => {
                let encoded = base64::encode_config(&v, base64::MIME);
                write!(f, "{}", encoded)
            }
            _ => panic!("not yet implemented: {:?}", self),
        }
    }
}


#[derive(Debug, Clone, PartialEq)]
pub enum Array {
    /*
    Bool(Vec<bool>),

    Tinyint(Vec<i8>),
    Smallint(Vec<i16>),
    */
    Int(Vec<i32>),
    Float(Vec<f32>),
    /*
    Bigint(Vec<i64>),

    Double(Vec<f64>),
    BigDecimal(Vec<BigDecimal>),
    */
    Text(Vec<String>),
    /*
    Char(Vec<char>),
    Uuid(Vec<Uuid>),
    Date(Vec<NaiveDate>),
    Timestamp(Vec<DateTime<Utc>>),
    */
}

impl fmt::Display for Array {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Array::Text(_texts) => {
                let json_arr = "";//serde_json::to_string(texts).expect("must serialize");
                write!(f, "{}", json_arr)
            }
            Array::Float(_floats) => {
                let json_arr = "";//serde_json::to_string(floats).expect("must serialize");
                write!(f, "{}", json_arr)
            }
            _ => panic!("not yet implemented: {:?}", self),
        }
    }
}

/// A trait to allow passing of parameters ergonomically
/// in em.execute_sql_with_return
pub trait ToValue {
    fn to_value(&self) -> Value;
}

macro_rules! impl_to_value {
    ($ty:ty, $variant:ident) => {
        impl ToValue for $ty {
            fn to_value(&self) -> Value {
                Value::$variant(self.to_owned())
            }
        }
    };
}

macro_rules! impl_usined_to_value {
    ($ty:ty, $variant:ident, $target_variant:ident) => {
        impl ToValue for $ty {
            fn to_value(&self) -> Value {
                Value::$variant(self.to_owned() as $target_variant)
            }
        }
    };
}

impl_usined_to_value!(u8, Tinyint, i8);
impl_usined_to_value!(u16, Smallint, i16);
impl_usined_to_value!(u32, Int, i32);
impl_usined_to_value!(u64, Bigint, i64);
impl_usined_to_value!(usize, Bigint, i64);


impl_to_value!(bool, Bool);
impl_to_value!(i8, Tinyint);
impl_to_value!(i16, Smallint);
impl_to_value!(i32, Int);

impl_to_value!(i64, Bigint);
impl_to_value!(f32, Float);
impl_to_value!(f64, Double);
impl_to_value!(Vec<u8>, Blob);
impl_to_value!(char, Char);
impl_to_value!(String, Text);
impl_to_value!(Uuid, Uuid);
impl_to_value!(NaiveDate, Date);
impl_to_value!(NaiveTime, Time);
impl_to_value!(DateTime<Utc>, Timestamp);
impl_to_value!(NaiveDateTime, DateTime);

impl ToValue for &str {
    fn to_value(&self) -> Value {
        Value::Text(self.to_string())
    }
}

impl ToValue for Vec<String> {
    fn to_value(&self) -> Value {
        Value::Array(Array::Text(self.to_owned()))
    }
}

impl<T> ToValue for Option<T>
where
    T: ToValue,
{
    fn to_value(&self) -> Value {
        
        match self {
            Some(v) => v.to_value(),
            None => Value::Nil,
        }
    }
}

impl<T> ToValue for &T
where
    T: ToValue,
{
    fn to_value(&self) -> Value {
        (*self).to_value()
    }
}

impl<T> From<T> for Value
where
    T: ToValue,
{
    fn from(v: T) -> Value {
        v.to_value()
    }
}

#[derive(Debug)]
pub enum ConvertError {
    NotSupported(String, String),
}

impl From<mysql::serde_json::Error> for ConvertError {
    fn from(err: mysql::serde_json::Error) -> Self {
        ConvertError::NotSupported(err.to_string(), "SerdeJson".to_string())
    }
}

pub trait FromValue: Sized {
    fn from_value(v: &Value) -> Result<Self, ConvertError>;
}

macro_rules! impl_from_value {
    ($ty: ty, $ty_name: tt, $($variant: ident),*) => {
        /// try from to owned
        impl FromValue for $ty {
            fn from_value(v: &Value) -> Result<Self, ConvertError> {
                match *v {
                    $(Value::$variant(ref v) => Ok(v.to_owned() as $ty),
                    )*
                    _ => Err(ConvertError::NotSupported(format!("{:?}",v), $ty_name.into())),
                }
            }
        }
    }
}

macro_rules! impl_from_value_numeric {
    ($ty: ty, $method:ident, $ty_name: tt, $($variant: ident),*) => {
        impl FromValue for $ty {
            fn from_value(v: &Value) -> Result<Self, ConvertError> {
                match *v {
                    $(Value::$variant(ref v) => Ok(v.to_owned() as $ty),
                    )*
                    // Value::BigDecimal(ref v) => Ok(v.$method().unwrap()),
                    _ => Err(ConvertError::NotSupported(format!("{:?}", v), $ty_name.into())),
                }
            }
        }
    }
}

impl_from_value!(Vec<u8>, "Vec<u8>", Blob);
impl_from_value!(char, "char", Char);
impl_from_value!(Uuid, "Uuid", Uuid);
impl_from_value!(NaiveDate, "NaiveDate", Date);
impl_from_value_numeric!(i8, to_i8, "i8", Tinyint);
impl_from_value_numeric!(u8, to_u8, "u8", Tinyint, Bigint, Int);
impl_from_value_numeric!(u16, to_u16, "u16", Tinyint, Bigint, Int);
impl_from_value_numeric!(u32, to_u32, "u32", Tinyint, Bigint, Int);
impl_from_value_numeric!(u64, to_u64, "u64", Tinyint, Bigint, Int);
impl_from_value_numeric!(usize, to_usize, "usize", Tinyint, Bigint, Int);
impl_from_value_numeric!(i16, to_i16, "i16", Tinyint, Smallint);
impl_from_value_numeric!(i32, to_i32, "i32", Tinyint, Smallint, Int, Bigint);
impl_from_value_numeric!(i64, to_i64, "i64", Tinyint, Smallint, Int, Bigint);
impl_from_value_numeric!(f32, to_f32, "f32", Float);
impl_from_value_numeric!(f64, to_f64, "f64", Float, Double);

/// Char can be casted into String
/// and they havea separate implementation for extracting data
impl FromValue for String {
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match *v {
            Value::Text(ref v) => Ok(v.to_owned()),
            Value::Char(ref v) => {
                let mut s = String::new();
                s.push(*v);
                Ok(s)
            }
            Value::Blob(ref v) => String::from_utf8(v.to_owned()).map_err(|e| {
                ConvertError::NotSupported(format!("{:?}", v), format!("String: {}", e))
            }),
            _ => Err(ConvertError::NotSupported(
                format!("{:?}", v),
                "String".to_string(),
            )),
        }
    }
}

impl FromValue for Vec<String> {
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match *v {
            Value::Array(Array::Text(ref t)) => Ok(t.to_owned()),
            _ => Err(ConvertError::NotSupported(
                format!("{:?}", v),
                "Vec<String>".to_string(),
            )),
        }
    }
}

impl FromValue for bool {
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match *v {
            Value::Bool(v) => Ok(v),
            Value::Tinyint(v) => Ok(v == 1),
            Value::Smallint(v) => Ok(v == 1),
            Value::Int(v) => Ok(v == 1),
            Value::Bigint(v) => Ok(v == 1),
            _ => Err(ConvertError::NotSupported(
                format!("{:?}", v),
                "bool".to_string(),
            )),
        }
    }
}

impl FromValue for mysql::serde_json::Value {
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match v.clone() {
            Value::Bool(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Tinyint(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Smallint(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Int(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Bigint(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Float(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Double(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Blob(v) => mysql::serde_json::to_value(String::from_utf8_lossy(&v)).map_err(ConvertError::from),
            Value::Char(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Text(v) => mysql::serde_json::from_str(&v).map_err(ConvertError::from),
            Value::Json(v) => mysql::serde_json::from_str(&v).map_err(ConvertError::from),
            Value::Uuid(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Date(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Time(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::DateTime(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::Timestamp(v) => mysql::serde_json::to_value(v).map_err(ConvertError::from),
            Value::SerdeJson(v) => Ok(v.clone()),
            // Value::Array(v) => mysql::serde_json::to_value(v).map_err(|err| ConvertError::from(err)),
            _ => Err(ConvertError::NotSupported(
                format!("{:?}", v),
                "SerdeJson".to_string(),
            )),
        }
    }
}

impl FromValue for DateTime<Utc> {
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match *v {
            Value::Text(ref v) => Ok(DateTime::<Utc>::from_utc(parse_naive_date_time(v), Utc)),
            Value::DateTime(v) => Ok(DateTime::<Utc>::from_utc(v, Utc)),
            Value::Timestamp(v) => Ok(v),
            _ => Err(ConvertError::NotSupported(
                format!("{:?}", v),
                "DateTime".to_string(),
            )),
        }
    }
}

impl FromValue for NaiveDateTime {
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match *v {
            Value::Text(ref v) => Ok(parse_naive_date_time(v)),
            Value::DateTime(v) => Ok(v),
            _ => Err(ConvertError::NotSupported(
                format!("{:?}", v),
                "NaiveDateTime".to_string(),
            )),
        }
    }
}

impl<T> FromValue for Option<T>
where
    T: FromValue,
{
    fn from_value(v: &Value) -> Result<Self, ConvertError> {
        match *v {
            Value::Nil => Ok(None),
            _ => FromValue::from_value(v).map(Some),
        }
    }
}

fn parse_naive_date_time(v: &str) -> NaiveDateTime {
    let ts = NaiveDateTime::parse_from_str(&v, "%Y-%m-%d %H:%M:%S");
    if let Ok(ts) = ts {
        ts
    } else {
        let ts = NaiveDateTime::parse_from_str(&v, "%Y-%m-%d %H:%M:%S%.3f");
        if let Ok(ts) = ts {
            ts
        } else {
            panic!("unable to parse timestamp: {}", v);
        }
    }
}

// impl Into<Value> for i16 {
//     fn into(self) -> Value {
//         Value::Int16(self)
//     }
// }

// impl Into<Value> for i32 {
//     fn into(self) -> Value {
//         Value::Int32(self)
//     }
// }

// impl Into<Value> for i64 {
//     fn into(self) -> Value {
//         Value::Int64(self)
//     }
// }

// impl Into<Value> for i128 {
//     fn into(self) -> Value {
//         Value::Int128(self)
//     }
// }

// impl Into<Value> for u128 {
//     fn into(self) -> Value {
//         Value::U128(self)
//     }
// }

// impl Into<Value> for u64 {
//     fn into(self) -> Value {
//         Value::U64(self)
//     }
// }


// impl Into<Value> for u32 {
//     fn into(self) -> Value {
//         Value::U32(self)
//     }
// }

// impl Into<Value> for u16 {
//     fn into(self) -> Value {
//         Value::U16(self)
//     }
// }


// impl Into<Value> for String {
//     fn into(self) -> Value {
//         Value::Text(self)
//     }
// }


// impl Into<Value> for usize {
//     fn into(self) -> Value {
//         Value::Usize(self)
//     }
// }

// impl Into<Value> for isize {
//     fn into(self) -> Value {
//         Value::Isize(self)
//     }
// }

// impl Into<Value> for f64 {
//     fn into(self) -> Value {
//         Value::Float64(self)
//     }
// }

// impl Into<Value> for f32 {
//     fn into(self) -> Value {
//         Value::Float32(self)
//     }
// }

// impl Into<Value> for &'static str {
//     fn into(self) -> Value {
//         Value::Str(self)
//     }
// }