glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! What an Active Record-style record knows about itself.
//!
//! `#[glacier::model]` gives every model a hidden [`Record`]: whether it has
//! been saved, its values as loaded (so `save` writes only what changed),
//! the errors from its last save, and form input that couldn't be cast (so
//! the form shows it again).
//!
//! ```ignore
//! let mut post = Post::build(ctx.params());
//! if post.save().await? {
//!     redirect!(post, notice: "Post created.")
//! } else {
//!     render!(post; template = new, status = 422)   // post.errors_on("title")
//! }
//! ```

use crate::db::{Changeset, Save, Value};
use crate::error::Result;
use crate::model::Model;

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Record {
    persisted: bool,
    original: Vec<(&'static str, Value)>,
    errors: Vec<(&'static str, String)>,
    /// Input that didn't cast, kept to show again: (column, text).
    raw: Vec<(&'static str, String)>,
}

impl Record {
    /// Marks the record as matching the database with these values.
    #[doc(hidden)]
    pub fn mark_loaded(&mut self, values: Vec<(&'static str, Value)>) {
        self.persisted = true;
        self.original = values;
        self.errors.clear();
        self.raw.clear();
    }

    pub fn is_persisted(&self) -> bool {
        self.persisted
    }

    /// The column's value as loaded, before any change.
    pub fn original(&self, column: &str) -> Option<&Value> {
        self.original
            .iter()
            .find(|(c, _)| *c == column)
            .map(|(_, v)| v)
    }

    pub fn errors(&self) -> &[(&'static str, String)] {
        &self.errors
    }

    /// Input for `column` that couldn't be cast, if any.
    pub fn raw(&self, column: &str) -> Option<&str> {
        self.raw
            .iter()
            .find(|(c, _)| *c == column)
            .map(|(_, v)| v.as_str())
    }

    /// Adds an error, as a validation does: `add_error("answers", "note
    /// can't be blank")`.
    pub fn add_error(&mut self, column: &'static str, message: impl Into<String>) {
        self.errors.push((column, message.into()));
    }

    /// Records input that couldn't be cast into its field.
    #[doc(hidden)]
    pub fn cast_failed(&mut self, column: &'static str, raw: &str, message: String) {
        self.raw.retain(|(c, _)| *c != column);
        self.raw.push((column, raw.to_owned()));
        self.errors.retain(|(c, _)| *c != column);
        self.errors.push((column, message));
    }

    /// Forgets a cast failure once the field gets a valid value.
    #[doc(hidden)]
    pub fn cast_succeeded(&mut self, column: &'static str) {
        if self.raw.iter().any(|(c, _)| *c == column) {
            self.raw.retain(|(c, _)| *c != column);
            self.errors.retain(|(c, _)| *c != column);
        }
    }

    fn cast_errors(&self) -> Vec<(&'static str, String)> {
        self.errors
            .iter()
            .filter(|(c, _)| self.raw.iter().any(|(r, _)| r == c))
            .cloned()
            .collect()
    }
}

/// Converts a value written in `.glacier` into a field's type, so
/// `post.title = "Hi"` works for a `String` field and `body: "Hi"` for an
/// `Option<String>`. The `.glacier` dialect inserts it; Rust code can use
/// it too.
pub fn field<T, V: IntoField<T>>(value: V) -> T {
    value.into_field()
}

/// What [`field`] converts: a value into itself, into `Some(value)`, and
/// `&str` or `&String` into `String` / `Option<String>`.
pub trait IntoField<T> {
    fn into_field(self) -> T;
}

impl<T> IntoField<T> for T {
    fn into_field(self) -> T {
        self
    }
}

impl<T> IntoField<Option<T>> for T {
    fn into_field(self) -> Option<T> {
        Some(self)
    }
}

/// A time into a column without a zone, as Rails keeps them (in UTC).
impl IntoField<Option<crate::db::NaiveTimestamp>> for crate::db::Timestamp {
    fn into_field(self) -> Option<crate::db::NaiveTimestamp> {
        Some(self.naive_utc())
    }
}

impl IntoField<crate::db::NaiveTimestamp> for crate::db::Timestamp {
    fn into_field(self) -> crate::db::NaiveTimestamp {
        self.naive_utc()
    }
}

impl IntoField<String> for &str {
    fn into_field(self) -> String {
        self.to_owned()
    }
}

/// JSON text into a JSON field, as Active Record decodes strings for json
/// columns; text that isn't JSON becomes null.
impl IntoField<crate::db::JsonValue> for &str {
    fn into_field(self) -> crate::db::JsonValue {
        serde_json::from_str(self).unwrap_or(crate::db::JsonValue::Null)
    }
}

impl IntoField<Option<String>> for &str {
    fn into_field(self) -> Option<String> {
        Some(self.to_owned())
    }
}

/// A borrowed `String` as `&str` is: `find_by(email_address: &email)`.
impl IntoField<String> for &String {
    fn into_field(self) -> String {
        self.clone()
    }
}

impl IntoField<Option<String>> for &String {
    fn into_field(self) -> Option<String> {
        Some(self.clone())
    }
}

/// Errors as Rails renders them in JSON: each column with its messages.
pub(crate) fn errors_json(errors: &[(&'static str, String)]) -> serde_json::Value {
    let mut map = serde_json::Map::new();
    for (column, message) in errors {
        let messages = map
            .entry((*column).to_owned())
            .or_insert_with(|| serde_json::Value::Array(Vec::new()));
        if let serde_json::Value::Array(list) = messages {
            list.push(serde_json::Value::String(message.clone()));
        }
    }
    serde_json::Value::Object(map)
}

/// The columns `save` writes: every changed one for a saved record; for a
/// new one, all but the primary key, unset timestamps (`insert` fills those
/// in, keeping any set, as Rails does) and NULLs (so column defaults apply).
pub(crate) fn changes<M: Model>(record: &M) -> Vec<(&'static str, Value)> {
    let values = record.values();
    match record.record() {
        Some(state) if state.persisted => values
            .into_iter()
            .filter(|(column, value)| state.original(column) != Some(value))
            .collect(),
        _ if !record.is_new() => values,
        // Unset (NULL) columns are left out, so the database's defaults
        // apply, as Rails' new records start from the schema's defaults.
        _ => values
            .into_iter()
            .filter(|(column, value)| {
                let timestamp = Some(*column) == M::CREATED_AT || Some(*column) == M::UPDATED_AT;
                *column != M::PRIMARY_KEY
                    && !value.is_null()
                    && !(timestamp && is_unset_time(value))
            })
            .collect(),
    }
}

/// A timestamp nobody set: a new record's non-optional timestamp starts at
/// the Unix epoch (its `Default`).
fn is_unset_time(value: &Value) -> bool {
    matches!(value, Value::Timestamp(t) if t.timestamp() == 0 && t.timestamp_subsec_nanos() == 0)
}

/// A changeset of the record's pending changes, plus its cast failures.
fn pending<M: Model + Clone>(record: &M, new: bool) -> Changeset<M> {
    let mut changeset = if new {
        Changeset::new()
    } else {
        Changeset::for_record(record.clone())
    };
    for (column, value) in changes(record) {
        changeset = changeset.put(column, value);
    }
    if let Some(state) = record.record() {
        for (column, message) in state.cast_errors() {
            changeset = changeset.push_error(column, message);
        }
    }
    changeset
}

fn keep_errors<M: Model>(record: &mut M, changeset: &Changeset<M>) {
    if let Some(state) = record.record_mut() {
        state.errors = changeset.errors().to_vec();
    }
}

/// Validates and inserts or updates `record` in place, running its
/// callbacks in Rails' order; `false` (with errors on the record) when
/// it's invalid.
/// Errors from a model's own `validate`: `errors.add("password", "is too
/// short")`.
#[derive(Debug, Default)]
pub struct Errors(Vec<(&'static str, String)>);

impl Errors {
    pub fn add(&mut self, column: &'static str, message: impl Into<String>) {
        self.0.push((column, message.into()));
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// The record's pending write, with its fields' and its own validations
/// (and its uploads').
fn validated<M: Model + Clone>(
    record: &M,
    new: bool,
    files: &[crate::attachment::Pending],
) -> Changeset<M> {
    let mut changeset = M::validate(pending(record, new));
    let mut errors = Errors::default();
    for file in files {
        file.validate(&mut errors);
    }
    record.validate_record(&mut errors);
    for (column, message) in errors.0 {
        changeset = changeset.push_error(column, message);
    }
    changeset
}

pub(crate) async fn save<M: Model + Clone>(record: &mut M) -> Result<bool> {
    // Uploads for `has_attached`: their columns are set now, their files
    // stored once the record is, in the same transaction, so a file that
    // can't be stored leaves the row (and the record) as they were.
    // Boxed: nested records save through here, and the write's future is
    // large enough to overflow the stack when they nest.
    if !M::ATTACHMENTS {
        return Box::pin(write(record, Vec::new())).await;
    }
    let before = record.clone();
    let files = record.take_attachments();
    if files.is_empty() {
        return Box::pin(write(record, files)).await;
    }
    let saved = Box::pin(crate::db::savepoint_in(M::DATABASE, write(record, files))).await;
    if saved.is_err() {
        *record = before;
    }
    saved
}

async fn write<M: Model + Clone>(
    record: &mut M,
    files: Vec<crate::attachment::Pending>,
) -> Result<bool> {
    let new = record.is_new();
    record.before_validation().await?;
    let mut checked = validated(record, new, &files);
    if !checked.is_valid() {
        // As Rails, every error at once: "has already been taken" too.
        let conn = checked.connection()?;
        checked.check_unique(&conn).await?;
        keep_errors(record, &checked);
        return Ok(false);
    }
    record.before_save().await?;
    if new {
        record.before_create().await?;
    } else {
        record.before_update().await?;
    }
    // Callbacks may have changed fields (a slug from the title, say), so
    // the write is built again, but not validated again, as Rails: a
    // callback that clears a virtual field (a password, once hashed) mustn't
    // fail the save. Uniqueness is still checked as it's written.
    let changeset = M::validate(pending(record, new)).without_errors();
    let saved = if new {
        changeset.insert_valid().await?
    } else {
        changeset.update_valid().await?
    };
    match saved {
        Save::Saved(fresh) => {
            *record = fresh;
            if !files.is_empty() {
                let id = match record.id_value() {
                    crate::db::Value::Int(id) => id,
                    other => other
                        .to_text()
                        .parse()
                        .map_err(|_| crate::Error::internal("attachments need an integer id"))?,
                };
                for file in files {
                    file.store(id).await?;
                }
            }
            if new {
                record.after_create().await?;
            } else {
                record.after_update().await?;
            }
            record.after_save().await?;
            Ok(true)
        }
        // A unique constraint the database caught.
        Save::Invalid(changeset) => {
            keep_errors(record, &changeset);
            Ok(false)
        }
    }
}