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
use crate::custom::{SqlValCustom, SqlValRefCustom};
use crate::{DataObject, Error::CannotConvertSqlVal, Result, SqlType};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::fmt;

#[cfg(feature = "pg")]
use crate::custom::SqlTypeCustom;

#[cfg(feature = "datetime")]
use chrono::naive::NaiveDateTime;

#[derive(Clone, Debug)]
pub enum SqlValRef<'a> {
    Null,
    Bool(bool),
    Int(i32),
    BigInt(i64),
    Real(f64),
    Text(&'a str),
    Blob(&'a [u8]),
    #[cfg(feature = "datetime")]
    Timestamp(NaiveDateTime), // NaiveDateTime is Copy
    Custom(SqlValRefCustom<'a>),
}
impl SqlValRef<'_> {
    // if this is Null
    pub fn sqltype(&self) -> Option<SqlType> {
        match self {
            SqlValRef::Null => None,
            SqlValRef::Bool(_) => Some(SqlType::Bool),
            SqlValRef::Int(_) => Some(SqlType::Int),
            SqlValRef::BigInt(_) => Some(SqlType::BigInt),
            SqlValRef::Real(_) => Some(SqlType::Real),
            SqlValRef::Text(_) => Some(SqlType::Text),
            #[cfg(feature = "datetime")]
            SqlValRef::Timestamp(_) => Some(SqlType::Timestamp),
            SqlValRef::Blob(_) => Some(SqlType::Blob),
            #[cfg(feature = "pg")]
            SqlValRef::Custom(c) => match c {
                SqlValRefCustom::PgToSql { ty, .. } => {
                    Some(SqlType::Custom(SqlTypeCustom::Pg(ty.clone())))
                }
                SqlValRefCustom::PgBytes { ty, .. } => {
                    Some(SqlType::Custom(SqlTypeCustom::Pg(ty.clone())))
                }
            },
            #[cfg(not(feature = "pg"))]
            SqlValRef::Custom(_) => None,
        }
    }
}

/// A database value.
///
/// For conversion between `SqlVal` and other types, see [`FromSql`] and [`ToSql`].
///
/// [`FromSql`]: crate::FromSql
/// [`ToSql`]: crate::ToSql
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SqlVal {
    Null,
    Bool(bool),
    Int(i32),
    BigInt(i64),
    Real(f64),
    Text(String),
    Blob(Vec<u8>),
    #[cfg(feature = "datetime")]
    Timestamp(NaiveDateTime),
    Custom(Box<SqlValCustom>),
}
impl SqlVal {
    pub fn as_ref(&self) -> SqlValRef<'_> {
        SqlValRef::from(self)
    }

    pub fn bool(&self) -> Result<bool> {
        match self {
            SqlVal::Bool(val) => Ok(*val),
            _ => Err(CannotConvertSqlVal(SqlType::Bool, self.clone())),
        }
    }
    pub fn integer(&self) -> Result<i32> {
        match self {
            SqlVal::Int(val) => Ok(*val),
            _ => Err(CannotConvertSqlVal(SqlType::Int, self.clone())),
        }
    }
    pub fn bigint(&self) -> Result<i64> {
        match self {
            SqlVal::Int(val) => Ok(*val as i64),
            SqlVal::BigInt(val) => Ok(*val),
            _ => Err(CannotConvertSqlVal(SqlType::BigInt, self.clone())),
        }
    }
    pub fn real(&self) -> Result<f64> {
        match self {
            SqlVal::Real(val) => Ok(*val),
            _ => Err(CannotConvertSqlVal(SqlType::Real, self.clone())),
        }
    }
    pub fn text(&self) -> Result<&str> {
        match self {
            SqlVal::Text(val) => Ok(val),
            _ => Err(CannotConvertSqlVal(SqlType::Text, self.clone())),
        }
    }
    pub fn owned_text(self) -> Result<String> {
        match self {
            SqlVal::Text(val) => Ok(val),
            _ => Err(CannotConvertSqlVal(SqlType::Text, self.clone())),
        }
    }
    pub fn blob(&self) -> Result<&[u8]> {
        match self {
            SqlVal::Blob(val) => Ok(val),
            _ => Err(CannotConvertSqlVal(SqlType::Blob, self.clone())),
        }
    }
    pub fn owned_blob(self) -> Result<Vec<u8>> {
        match self {
            SqlVal::Blob(val) => Ok(val),
            _ => Err(CannotConvertSqlVal(SqlType::Blob, self.clone())),
        }
    }

    /// Tests if this sqlval is compatible with the given
    /// `SqlType`. There are no implicit type conversions (i.e. if
    /// this is a `SqlVal::Bool`, it is only compatible with
    /// `SqlType::Bool`, not with `SqlType::Int`, even though an int
    /// contains enough information to encode a bool.
    #[allow(unreachable_patterns)]
    pub fn is_compatible(&self, t: &SqlType, null_allowed: bool) -> bool {
        match self.sqltype() {
            None => null_allowed,
            Some(self_ty) => *t == self_ty,
        }
    }

    // Returns the SqlType most appropriate to this value or None
    // if this is Null
    pub fn sqltype(&self) -> Option<SqlType> {
        match self {
            SqlVal::Null => None,
            SqlVal::Bool(_) => Some(SqlType::Bool),
            SqlVal::Int(_) => Some(SqlType::Int),
            SqlVal::BigInt(_) => Some(SqlType::BigInt),
            SqlVal::Real(_) => Some(SqlType::Real),
            SqlVal::Text(_) => Some(SqlType::Text),
            #[cfg(feature = "datetime")]
            SqlVal::Timestamp(_) => Some(SqlType::Timestamp),
            SqlVal::Blob(_) => Some(SqlType::Blob),
            #[cfg(feature = "pg")]
            SqlVal::Custom(c) => match c.as_ref() {
                SqlValCustom::Pg { ty, .. } => Some(SqlType::Custom(SqlTypeCustom::Pg(ty.clone()))),
            },
            #[cfg(not(feature = "pg"))]
            SqlVal::Custom(_) => None,
        }
    }
}
impl fmt::Display for SqlVal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use SqlVal::*;
        match &self {
            SqlVal::Null => f.write_str("NULL"),
            SqlVal::Bool(val) => val.fmt(f),
            Int(val) => val.fmt(f),
            BigInt(val) => val.fmt(f),
            Real(val) => val.fmt(f),
            Text(val) => val.fmt(f),
            Blob(val) => f.write_str(&hex::encode(val)),
            #[cfg(feature = "datetime")]
            Timestamp(val) => val.format("%+").fmt(f),
            Custom(val) => val.fmt(f),
        }
    }
}

/// Used to convert another type to a `SqlVal` or `SqlValRef`.
pub trait ToSql {
    fn to_sql(&self) -> SqlVal;
    fn to_sql_ref(&self) -> SqlValRef<'_>;
    /// The default implementation simply calls `to_sql`. Provide an
    /// alternative implementation if greater efficiency can be
    /// realized by consuming self.
    fn into_sql(self) -> SqlVal
    where
        Self: Sized,
    {
        self.to_sql()
    }
}

impl<T> From<T> for SqlVal
where
    T: ToSql,
{
    fn from(val: T) -> Self {
        val.into_sql()
    }
}

/// Used to convert a `SqlVal` or `SqlValRef` into another type.
///
/// The `SqlVal` is consumed.
pub trait FromSql {
    /// Used to convert a SqlValRef into another type.
    fn from_sql_ref(val: SqlValRef<'_>) -> Result<Self>
    where
        Self: Sized;

    /// Used to convert a SqlVal into another type. The default
    /// implementation calls `Self::from_sql_ref(val.as_ref())`, which
    /// may be inefficient. This method is chiefly used only for
    /// primary keys: a more efficient implementation is unlikely to
    /// provide benefits for types not used as primary keys.
    fn from_sql(val: SqlVal) -> Result<Self>
    where
        Self: Sized,
    {
        Self::from_sql_ref(val.as_ref())
    }
}

impl From<SqlValRef<'_>> for SqlVal {
    fn from(vref: SqlValRef) -> SqlVal {
        use SqlValRef::*;
        match vref {
            Null => SqlVal::Null,
            Bool(v) => SqlVal::Bool(v),
            Int(v) => SqlVal::Int(v),
            BigInt(v) => SqlVal::BigInt(v),
            Real(v) => SqlVal::Real(v),
            Text(v) => SqlVal::Text(v.to_string()),
            Blob(v) => SqlVal::Blob(v.into()),
            #[cfg(feature = "datetime")]
            Timestamp(v) => SqlVal::Timestamp(v),
            Custom(v) => SqlVal::Custom(Box::new(v.into())),
        }
    }
}

impl<'a> From<&'a SqlVal> for SqlValRef<'a> {
    fn from(val: &'a SqlVal) -> SqlValRef<'a> {
        use SqlVal::*;
        match val {
            Null => SqlValRef::Null,
            Bool(v) => SqlValRef::Bool(*v),
            Int(v) => SqlValRef::Int(*v),
            BigInt(v) => SqlValRef::BigInt(*v),
            Real(v) => SqlValRef::Real(*v),
            Text(v) => SqlValRef::Text(v.as_ref()),
            Blob(v) => SqlValRef::Blob(v.as_ref()),
            #[cfg(feature = "datetime")]
            Timestamp(v) => SqlValRef::Timestamp(*v),
            Custom(v) => SqlValRef::Custom(v.as_valref()),
        }
    }
}

/// Type suitable for being a database column.
pub trait FieldType: ToSql + FromSql {
    const SQLTYPE: SqlType;
    /// Reference type. Used for ergonomics with String (which has
    /// reference type str). For most, it is Self
    type RefType: ?Sized + ToSql;
}

/// Marker trait for a type suitable for being a primary key
pub trait PrimaryKeyType: FieldType + Clone + PartialEq {}

/// Trait for referencing the primary key for a given model. Used to
/// implement ForeignKey equality tests.
pub trait AsPrimaryKey<T: DataObject> {
    fn as_pk(&self) -> Cow<<T as DataObject>::PKType>;
}

impl<P, T> AsPrimaryKey<T> for P
where
    P: PrimaryKeyType,
    T: DataObject<PKType = P>,
{
    fn as_pk(&self) -> Cow<P> {
        Cow::Borrowed(self)
    }
}

macro_rules! sql_conv_err {
    ($val:ident, $sqltype:ident) => {
        Err(crate::Error::CannotConvertSqlVal(
            SqlType::$sqltype,
            $val.into(),
        ))
    };
}

macro_rules! impl_basic_from_sql {
    ($prim:ty, $variant:ident, $sqltype:ident) => {
        impl FromSql for $prim {
            fn from_sql_ref(valref: SqlValRef) -> Result<Self> {
                if let SqlValRef::$variant(val) = valref {
                    Ok(val as $prim)
                } else {
                    sql_conv_err!(valref, $sqltype)
                }
            }
            fn from_sql(val: SqlVal) -> Result<Self> {
                if let SqlVal::$variant(val) = val {
                    Ok(val as $prim)
                } else {
                    sql_conv_err!(val, $sqltype)
                }
            }
        }
    };
}

macro_rules! impl_prim_sql {
    ($prim:ty, $variant:ident, $sqltype:ident) => {
        impl_prim_sql! {$prim, $variant, $sqltype, $prim}
    };
    ($prim:ty, $variant:ident, $sqltype:ident, $reftype: ty) => {
        impl_basic_from_sql!($prim, $variant, $sqltype);
        impl ToSql for $prim {
            fn to_sql(&self) -> SqlVal {
                self.clone().into_sql()
            }
            fn to_sql_ref(&self) -> SqlValRef<'_> {
                SqlValRef::$variant(self.clone().into())
            }
            fn into_sql(self) -> SqlVal {
                SqlVal::$variant(self.into())
            }
        }
        impl FieldType for $prim {
            const SQLTYPE: SqlType = SqlType::$sqltype;
            type RefType = $reftype;
        }

        impl PrimaryKeyType for $prim {}
    };
}

impl_prim_sql!(bool, Bool, Bool);
impl_prim_sql!(i64, BigInt, BigInt);
impl_prim_sql!(i32, Int, Int);
impl_prim_sql!(u32, BigInt, BigInt);
// TODO need a small int type
impl_prim_sql!(u16, Int, Int);
impl_prim_sql!(i16, Int, Int);
impl_prim_sql!(u8, Int, Int);
impl_prim_sql!(i8, Int, Int);
impl_prim_sql!(f64, Real, Real);
impl_prim_sql!(f32, Real, Real);

impl FromSql for String {
    fn from_sql_ref(valref: SqlValRef) -> Result<Self> {
        if let SqlValRef::Text(val) = valref {
            Ok(val.to_string())
        } else {
            sql_conv_err!(valref, Text)
        }
    }
    fn from_sql(val: SqlVal) -> Result<Self> {
        if let SqlVal::Text(val) = val {
            Ok(val)
        } else {
            sql_conv_err!(val, Text)
        }
    }
}
impl ToSql for String {
    fn to_sql(&self) -> SqlVal {
        SqlVal::Text(self.clone())
    }
    fn to_sql_ref(&self) -> SqlValRef<'_> {
        SqlValRef::Text(self)
    }
    fn into_sql(self) -> SqlVal {
        SqlVal::Text(self)
    }
}
impl FieldType for String {
    const SQLTYPE: SqlType = SqlType::Text;
    type RefType = str;
}
impl PrimaryKeyType for String {}

impl FromSql for Vec<u8> {
    fn from_sql_ref(valref: SqlValRef) -> Result<Self> {
        if let SqlValRef::Blob(val) = valref {
            Ok(Vec::from(val))
        } else {
            sql_conv_err!(valref, Blob)
        }
    }
    fn from_sql(val: SqlVal) -> Result<Self> {
        if let SqlVal::Blob(val) = val {
            Ok(val)
        } else {
            sql_conv_err!(val, Blob)
        }
    }
}
impl ToSql for Vec<u8> {
    fn to_sql(&self) -> SqlVal {
        SqlVal::Blob(self.clone())
    }
    fn to_sql_ref(&self) -> SqlValRef<'_> {
        SqlValRef::Blob(self)
    }
    fn into_sql(self) -> SqlVal {
        SqlVal::Blob(self)
    }
}
impl FieldType for Vec<u8> {
    const SQLTYPE: SqlType = SqlType::Blob;
    type RefType = Self;
}
impl PrimaryKeyType for Vec<u8> {}

#[cfg(feature = "datetime")]
impl_basic_from_sql!(NaiveDateTime, Timestamp, Timestamp);
#[cfg(feature = "datetime")]
impl ToSql for NaiveDateTime {
    fn to_sql(&self) -> SqlVal {
        SqlVal::Timestamp(*self)
    }
    fn to_sql_ref(&self) -> SqlValRef<'_> {
        SqlValRef::Timestamp(*self)
    }
    fn into_sql(self) -> SqlVal {
        SqlVal::Timestamp(self)
    }
}
#[cfg(feature = "datetime")]
impl FieldType for NaiveDateTime {
    const SQLTYPE: SqlType = SqlType::Timestamp;
    type RefType = str;
}
#[cfg(feature = "datetime")]
impl PrimaryKeyType for NaiveDateTime {}

impl ToSql for &str {
    fn to_sql(&self) -> SqlVal {
        SqlVal::Text((*self).to_string())
    }
    fn to_sql_ref(&self) -> SqlValRef<'_> {
        SqlValRef::Text(self)
    }
}
impl ToSql for str {
    fn to_sql(&self) -> SqlVal {
        SqlVal::Text(self.to_string())
    }
    fn to_sql_ref(&self) -> SqlValRef<'_> {
        SqlValRef::Text(self)
    }
}

impl<T> ToSql for Option<T>
where
    T: ToSql,
{
    fn to_sql(&self) -> SqlVal {
        match self {
            None => SqlVal::Null,
            Some(v) => v.to_sql(),
        }
    }
    fn to_sql_ref(&self) -> SqlValRef<'_> {
        match self {
            None => SqlValRef::Null,
            Some(v) => v.to_sql_ref(),
        }
    }
    fn into_sql(self) -> SqlVal {
        match self {
            None => SqlVal::Null,
            Some(v) => v.into_sql(),
        }
    }
}
impl<T> FromSql for Option<T>
where
    T: FromSql,
{
    fn from_sql_ref(valref: SqlValRef) -> Result<Self> {
        Ok(match valref {
            SqlValRef::Null => None,
            _ => Some(T::from_sql_ref(valref)?),
        })
    }
}
impl<T> FieldType for Option<T>
where
    T: FieldType,
{
    const SQLTYPE: SqlType = T::SQLTYPE;
    type RefType = Self;
}