fletch-orm 1.0.0

Lightweight database toolkit built on SQLx
Documentation
//! Dynamic value type for bind parameters.

/// A dynamically-typed database value used for bind parameters.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// A null value.
    Null,
    /// A boolean value.
    Bool(bool),
    /// A 32-bit integer.
    I32(i32),
    /// A 64-bit integer.
    I64(i64),
    /// A 32-bit float.
    F32(f32),
    /// A 64-bit float.
    F64(f64),
    /// A text string.
    Text(String),
    /// Raw bytes.
    Bytes(Vec<u8>),
    /// A UUID value.
    #[cfg(feature = "uuid")]
    Uuid(uuid::Uuid),
    /// A JSON value.
    #[cfg(feature = "json")]
    Json(serde_json::Value),
    /// A UTC timestamp.
    #[cfg(feature = "chrono")]
    Timestamp(chrono::DateTime<chrono::Utc>),
}

impl From<bool> for Value {
    fn from(v: bool) -> Self {
        Self::Bool(v)
    }
}

impl From<i32> for Value {
    fn from(v: i32) -> Self {
        Self::I32(v)
    }
}

impl From<i64> for Value {
    fn from(v: i64) -> Self {
        Self::I64(v)
    }
}

impl From<f32> for Value {
    fn from(v: f32) -> Self {
        Self::F32(v)
    }
}

impl From<f64> for Value {
    fn from(v: f64) -> Self {
        Self::F64(v)
    }
}

impl From<String> for Value {
    fn from(v: String) -> Self {
        Self::Text(v)
    }
}

impl From<&str> for Value {
    fn from(v: &str) -> Self {
        Self::Text(v.to_owned())
    }
}

impl From<Vec<u8>> for Value {
    fn from(v: Vec<u8>) -> Self {
        Self::Bytes(v)
    }
}

#[cfg(feature = "uuid")]
impl From<uuid::Uuid> for Value {
    fn from(v: uuid::Uuid) -> Self {
        Self::Uuid(v)
    }
}

#[cfg(feature = "json")]
impl From<serde_json::Value> for Value {
    fn from(v: serde_json::Value) -> Self {
        Self::Json(v)
    }
}

#[cfg(feature = "chrono")]
impl From<chrono::DateTime<chrono::Utc>> for Value {
    fn from(v: chrono::DateTime<chrono::Utc>) -> Self {
        Self::Timestamp(v)
    }
}

impl<T: Into<Self>> From<Option<T>> for Value {
    fn from(v: Option<T>) -> Self {
        match v {
            Some(v) => v.into(),
            None => Self::Null,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bool_from_impl() {
        assert_eq!(Value::from(true), Value::Bool(true));
    }

    #[cfg(feature = "uuid")]
    #[test]
    fn uuid_from_impl() {
        let id = uuid::Uuid::nil();
        assert_eq!(Value::from(id), Value::Uuid(id));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_from_impl() {
        let v = serde_json::json!({"key": "value"});
        assert_eq!(Value::from(v.clone()), Value::Json(v));
    }

    #[cfg(feature = "chrono")]
    #[test]
    fn timestamp_from_impl() {
        let ts = chrono::Utc::now();
        assert_eq!(Value::from(ts), Value::Timestamp(ts));
    }
}