glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
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
//! 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
    }

    pub(crate) fn set_errors(&mut self, errors: Vec<(&'static str, String)>) {
        self.errors = 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_attributes(&mut errors);
    record.validate_record(&mut errors);
    for (column, message) in errors.0 {
        changeset = changeset.push_error(column, message);
    }
    changeset
}

/// A field's value through its `normalize:` closure.
#[doc(hidden)]
pub fn normalized<T>(value: &T, normalize: impl FnOnce(&T) -> T) -> T {
    normalize(value)
}

/// An optional field's value through its `normalize:` closure, when it
/// has one.
#[doc(hidden)]
pub fn normalized_option<T>(value: &Option<T>, normalize: impl FnOnce(&T) -> T) -> Option<T> {
    value.as_ref().map(normalize)
}

/// An `acceptance` field's value is accepted: not sent at all, or `true`,
/// `1`, `yes` or `on` (a checkbox).
#[doc(hidden)]
pub fn accepted(value: &Value) -> bool {
    match value {
        Value::Null => true,
        Value::Bool(b) => *b,
        Value::Int(n) => *n == 1,
        Value::Text(t) => matches!(
            t.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes" | "on"
        ),
        _ => false,
    }
}

/// `Model.create(params)` and `record.update_changeset(changes)`: the
/// changeset's own casts and validations, with the model's callbacks and
/// `validate do` around them in Rails' order (`before_validation`,
/// validations, `before_save`, `before_create`/`before_update`, the write,
/// `after_create`/`after_update`, `after_save`), on the record the changes
/// make. A callback's changes (a slug from the title) are written too.
pub(crate) async fn write_changeset<M: Model>(
    mut changeset: Changeset<M>,
    new: bool,
) -> Result<Save<M>> {
    let (record, was) = if new {
        (changeset.new_record(), Vec::new())
    } else {
        match changeset.take_record() {
            Some((record, was)) => (Some(record), was),
            None => (None, Vec::new()),
        }
    };
    // A model without `Default` has no record to call back: the write as
    // it was. (And `update` needs the record it changes.)
    let Some(mut record) = record else {
        return if new {
            changeset.insert().await
        } else {
            changeset.update().await
        };
    };
    let before = record.values();
    if new {
        record.belongs_to_defaults().await?;
    }
    record.normalize_fields();
    record.before_validation().await?;
    let mut errors = Errors::default();
    record.validate_attributes(&mut errors);
    record.validate_record(&mut errors);
    let mut changeset = changeset.changed_by(&record, &before);
    // Validations read an update's record: a field the params didn't send
    // is the record's.
    let mut kept = None;
    if new {
        kept = Some(record);
    } else {
        changeset = changeset.attach(record);
    }
    let mut changeset = M::validate(changeset);
    for (column, message) in errors.0 {
        changeset = changeset.push_error(column, message);
    }
    if !changeset.is_valid() {
        // The record as it was: the changeset holds the changes.
        if let Some(record) = changeset.data_mut() {
            for (column, value) in was {
                record.set_value(column, value);
            }
        }
        let conn = changeset.connection()?;
        changeset.check_unique(&conn).await?;
        return Ok(Save::Invalid(changeset));
    }
    let mut record = match kept {
        Some(record) => record,
        None => changeset
            .take_data()
            .expect("an update's record is attached"),
    };
    let before = record.values();
    record.before_save().await?;
    if new {
        record.before_create().await?;
    } else {
        record.before_update().await?;
    }
    let changeset = changeset.changed_by(&record, &before);
    let saved = if new {
        changeset.insert_valid().await?
    } else {
        changeset.attach(record).update_valid().await?
    };
    let Save::Saved(mut fresh) = saved else {
        return Ok(saved);
    };
    if new {
        fresh.after_create().await?;
    } else {
        fresh.after_update().await?;
    }
    fresh.after_save().await?;
    Ok(Save::Saved(fresh))
}

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();
    if new {
        record.belongs_to_defaults().await?;
    }
    record.normalize_fields();
    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)
        }
    }
}