glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Values bound into queries, and the types columns decode into.

use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};

/// A point in time, stored as `TIMESTAMPTZ` (Postgres) or ISO-8601 text
/// (SQLite).
pub type Timestamp = DateTime<Utc>;

/// A time without a zone, for `timestamp without time zone` columns such
/// as Rails' `created_at`. Taken to be UTC when written.
pub type NaiveTimestamp = NaiveDateTime;

/// A calendar day, for `date` columns: `field due_on: Date`.
pub type Date = NaiveDate;

/// A JSON document, for `json`/`jsonb` columns (JSON text on SQLite):
/// `field cache: JsonValue`.
pub type JsonValue = serde_json::Value;

/// A JSON column a model's `store` reads typed settings from.
#[doc(hidden)]
pub trait StoreSource {
    fn store_value(&self, key: &str) -> Option<&JsonValue>;
}

impl StoreSource for JsonValue {
    fn store_value(&self, key: &str) -> Option<&JsonValue> {
        self.get(key).filter(|v| !v.is_null())
    }
}

impl StoreSource for Option<JsonValue> {
    fn store_value(&self, key: &str) -> Option<&JsonValue> {
        self.as_ref()?.store_value(key)
    }
}

/// A JSON column a model's `store` writes settings into.
#[doc(hidden)]
pub trait StoreTarget {
    fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue>;
}

impl StoreTarget for JsonValue {
    fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue> {
        if !self.is_object() {
            *self = JsonValue::Object(serde_json::Map::new());
        }
        self.as_object_mut().expect("made an object above")
    }
}

impl StoreTarget for Option<JsonValue> {
    fn store_object(&mut self) -> &mut serde_json::Map<String, JsonValue> {
        self.get_or_insert_with(|| JsonValue::Object(serde_json::Map::new()))
            .store_object()
    }
}

/// Sets a setting in a JSON column, as Rails' `store_accessor` writes it.
#[doc(hidden)]
pub fn store_set(store: &mut impl StoreTarget, key: &str, value: impl serde::Serialize) {
    let value = serde_json::to_value(value).unwrap_or(JsonValue::Null);
    store.store_object().insert(key.to_owned(), value);
}

/// A setting from a JSON column, as Rails' `store_accessor` reads it:
/// `None` when it's missing, null, or not a `T`.
#[doc(hidden)]
pub fn store_get<T: serde::de::DeserializeOwned>(store: &impl StoreSource, key: &str) -> Option<T> {
    serde_json::from_value(store.store_value(key)?.clone()).ok()
}

/// A value sent to the database.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Text(String),
    Bytes(Vec<u8>),
    Timestamp(Timestamp),
    Date(Date),
    Json(JsonValue),
    Decimal(super::Decimal),
    Uuid(uuid::Uuid),
    /// Values bound as one Postgres array, for `column = ANY($1)`: made by
    /// `IN` lists, never by hand.
    #[doc(hidden)]
    List(Vec<Value>),
}

impl Value {
    pub fn is_null(&self) -> bool {
        matches!(self, Value::Null)
    }

    /// The value as text, e.g. to refill a form field. `Null` is empty.
    pub fn to_text(&self) -> String {
        match self {
            Value::Null => String::new(),
            Value::Bool(v) => v.to_string(),
            Value::Int(v) => v.to_string(),
            Value::Float(v) => v.to_string(),
            Value::Text(v) => v.clone(),
            Value::Bytes(v) => String::from_utf8_lossy(v).into_owned(),
            Value::Timestamp(v) => v.to_rfc3339(),
            Value::Date(v) => v.to_string(),
            Value::Json(v) => v.to_string(),
            Value::Decimal(v) => v.to_string(),
            Value::Uuid(v) => v.to_string(),
            Value::List(items) => items
                .iter()
                .map(Value::to_text)
                .collect::<Vec<_>>()
                .join(", "),
        }
    }
}

/// Rust values that can be bound into a query.
pub trait ToValue {
    fn to_value(&self) -> Value;
}

impl<T: ToValue + ?Sized> ToValue for &T {
    fn to_value(&self) -> Value {
        (**self).to_value()
    }
}

impl<T: ToValue> ToValue for Option<T> {
    fn to_value(&self) -> Value {
        self.as_ref().map_or(Value::Null, ToValue::to_value)
    }
}

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

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

to_value!(Int: i8, i16, i32, i64, u8, u16, u32);
to_value!(Float: f32, f64);
to_value!(Bool: bool);
to_value!(Timestamp: Timestamp);

impl ToValue for NaiveTimestamp {
    fn to_value(&self) -> Value {
        Value::Timestamp(self.and_utc())
    }
}

impl ToValue for Date {
    fn to_value(&self) -> Value {
        Value::Date(*self)
    }
}

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

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

impl ToValue for uuid::Uuid {
    fn to_value(&self) -> Value {
        Value::Uuid(*self)
    }
}

impl ToValue for super::Decimal {
    fn to_value(&self) -> Value {
        Value::Decimal(self.clone())
    }
}

impl ToValue for JsonValue {
    fn to_value(&self) -> Value {
        Value::Json(self.clone())
    }
}

impl ToValue for Vec<u8> {
    fn to_value(&self) -> Value {
        Value::Bytes(self.clone())
    }
}

#[cfg(feature = "postgres")]
mod pg {
    pub trait Decode:
        for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
    {
    }
    impl<T> Decode for T where T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> {}
}

#[cfg(not(feature = "postgres"))]
mod pg {
    pub trait Decode {}
    impl<T> Decode for T {}
}

#[cfg(feature = "sqlite")]
mod sqlite {
    pub trait Decode: for<'r> sqlx::Decode<'r, sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite> {}
    impl<T> Decode for T where T: for<'r> sqlx::Decode<'r, sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite> {}
}

#[cfg(not(feature = "sqlite"))]
mod sqlite {
    pub trait Decode {}
    impl<T> Decode for T {}
}

/// Types a column can be read into, on every enabled database. Covers
/// `i16`/`i32`/`i64`, `f32`/`f64`, `bool`, `String`, `Vec<u8>`,
/// [`Timestamp`], [`JsonValue`] and `Option` of those.
pub trait FromColumn: pg::Decode + sqlite::Decode + Send + 'static {}

impl<T> FromColumn for T where T: pg::Decode + sqlite::Decode + Send + 'static {}

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

    #[test]
    fn reads_store_settings() {
        let cache = serde_json::json!({"days": 3, "text": "Hi", "gone": null, "wrong": "x"});
        assert_eq!(store_get::<i64>(&cache, "days"), Some(3));
        assert_eq!(store_get::<String>(&cache, "text").as_deref(), Some("Hi"));
        assert_eq!(
            store_get::<String>(&cache, "gone"),
            None,
            "null reads as unset"
        );
        assert_eq!(store_get::<i64>(&cache, "missing"), None);
        assert_eq!(
            store_get::<i64>(&cache, "wrong"),
            None,
            "the wrong type reads as unset"
        );
        assert_eq!(store_get::<i64>(&None::<JsonValue>, "days"), None);

        let mut empty: Option<JsonValue> = None;
        store_set(&mut empty, "days", 4);
        assert_eq!(empty, Some(serde_json::json!({"days": 4})));
        let mut cache = cache;
        store_set(&mut cache, "text", "Bye");
        assert_eq!(cache["text"], "Bye");
        assert_eq!(cache["days"], 3, "other settings stay");
    }
}