Skip to main content

glacier/db/
record.rs

1//! What an Active Record-style record knows about itself.
2//!
3//! `#[glacier::model]` gives every model a hidden [`Record`]: whether it has
4//! been saved, its values as loaded (so `save` writes only what changed),
5//! the errors from its last save, and form input that couldn't be cast (so
6//! the form shows it again).
7//!
8//! ```ignore
9//! let mut post = Post::build(ctx.params());
10//! if post.save().await? {
11//!     redirect!(post, notice: "Post created.")
12//! } else {
13//!     render!(post; template = new, status = 422)   // post.errors_on("title")
14//! }
15//! ```
16
17use crate::db::{Changeset, Save, Value};
18use crate::error::Result;
19use crate::model::Model;
20
21#[derive(Debug, Clone, Default, PartialEq)]
22pub struct Record {
23    persisted: bool,
24    original: Vec<(&'static str, Value)>,
25    errors: Vec<(&'static str, String)>,
26    /// Input that didn't cast, kept to show again: (column, text).
27    raw: Vec<(&'static str, String)>,
28}
29
30impl Record {
31    /// Marks the record as matching the database with these values.
32    #[doc(hidden)]
33    pub fn mark_loaded(&mut self, values: Vec<(&'static str, Value)>) {
34        self.persisted = true;
35        self.original = values;
36        self.errors.clear();
37        self.raw.clear();
38    }
39
40    pub fn is_persisted(&self) -> bool {
41        self.persisted
42    }
43
44    /// The column's value as loaded, before any change.
45    pub fn original(&self, column: &str) -> Option<&Value> {
46        self.original
47            .iter()
48            .find(|(c, _)| *c == column)
49            .map(|(_, v)| v)
50    }
51
52    pub fn errors(&self) -> &[(&'static str, String)] {
53        &self.errors
54    }
55
56    pub(crate) fn set_errors(&mut self, errors: Vec<(&'static str, String)>) {
57        self.errors = errors;
58    }
59
60    /// Input for `column` that couldn't be cast, if any.
61    pub fn raw(&self, column: &str) -> Option<&str> {
62        self.raw
63            .iter()
64            .find(|(c, _)| *c == column)
65            .map(|(_, v)| v.as_str())
66    }
67
68    /// Adds an error, as a validation does: `add_error("answers", "note
69    /// can't be blank")`.
70    pub fn add_error(&mut self, column: &'static str, message: impl Into<String>) {
71        self.errors.push((column, message.into()));
72    }
73
74    /// Records input that couldn't be cast into its field.
75    #[doc(hidden)]
76    pub fn cast_failed(&mut self, column: &'static str, raw: &str, message: String) {
77        self.raw.retain(|(c, _)| *c != column);
78        self.raw.push((column, raw.to_owned()));
79        self.errors.retain(|(c, _)| *c != column);
80        self.errors.push((column, message));
81    }
82
83    /// Forgets a cast failure once the field gets a valid value.
84    #[doc(hidden)]
85    pub fn cast_succeeded(&mut self, column: &'static str) {
86        if self.raw.iter().any(|(c, _)| *c == column) {
87            self.raw.retain(|(c, _)| *c != column);
88            self.errors.retain(|(c, _)| *c != column);
89        }
90    }
91
92    fn cast_errors(&self) -> Vec<(&'static str, String)> {
93        self.errors
94            .iter()
95            .filter(|(c, _)| self.raw.iter().any(|(r, _)| r == c))
96            .cloned()
97            .collect()
98    }
99}
100
101/// Converts a value written in `.glacier` into a field's type, so
102/// `post.title = "Hi"` works for a `String` field and `body: "Hi"` for an
103/// `Option<String>`. The `.glacier` dialect inserts it; Rust code can use
104/// it too.
105pub fn field<T, V: IntoField<T>>(value: V) -> T {
106    value.into_field()
107}
108
109/// What [`field`] converts: a value into itself, into `Some(value)`, and
110/// `&str` or `&String` into `String` / `Option<String>`.
111pub trait IntoField<T> {
112    fn into_field(self) -> T;
113}
114
115impl<T> IntoField<T> for T {
116    fn into_field(self) -> T {
117        self
118    }
119}
120
121impl<T> IntoField<Option<T>> for T {
122    fn into_field(self) -> Option<T> {
123        Some(self)
124    }
125}
126
127/// A time into a column without a zone, as Rails keeps them (in UTC).
128impl IntoField<Option<crate::db::NaiveTimestamp>> for crate::db::Timestamp {
129    fn into_field(self) -> Option<crate::db::NaiveTimestamp> {
130        Some(self.naive_utc())
131    }
132}
133
134impl IntoField<crate::db::NaiveTimestamp> for crate::db::Timestamp {
135    fn into_field(self) -> crate::db::NaiveTimestamp {
136        self.naive_utc()
137    }
138}
139
140impl IntoField<String> for &str {
141    fn into_field(self) -> String {
142        self.to_owned()
143    }
144}
145
146/// JSON text into a JSON field, as Active Record decodes strings for json
147/// columns; text that isn't JSON becomes null.
148impl IntoField<crate::db::JsonValue> for &str {
149    fn into_field(self) -> crate::db::JsonValue {
150        serde_json::from_str(self).unwrap_or(crate::db::JsonValue::Null)
151    }
152}
153
154impl IntoField<Option<String>> for &str {
155    fn into_field(self) -> Option<String> {
156        Some(self.to_owned())
157    }
158}
159
160/// A borrowed `String` as `&str` is: `find_by(email_address: &email)`.
161impl IntoField<String> for &String {
162    fn into_field(self) -> String {
163        self.clone()
164    }
165}
166
167impl IntoField<Option<String>> for &String {
168    fn into_field(self) -> Option<String> {
169        Some(self.clone())
170    }
171}
172
173/// Errors as Rails renders them in JSON: each column with its messages.
174pub(crate) fn errors_json(errors: &[(&'static str, String)]) -> serde_json::Value {
175    let mut map = serde_json::Map::new();
176    for (column, message) in errors {
177        let messages = map
178            .entry((*column).to_owned())
179            .or_insert_with(|| serde_json::Value::Array(Vec::new()));
180        if let serde_json::Value::Array(list) = messages {
181            list.push(serde_json::Value::String(message.clone()));
182        }
183    }
184    serde_json::Value::Object(map)
185}
186
187/// The columns `save` writes: every changed one for a saved record; for a
188/// new one, all but the primary key, unset timestamps (`insert` fills those
189/// in, keeping any set, as Rails does) and NULLs (so column defaults apply).
190pub(crate) fn changes<M: Model>(record: &M) -> Vec<(&'static str, Value)> {
191    let values = record.values();
192    match record.record() {
193        Some(state) if state.persisted => values
194            .into_iter()
195            .filter(|(column, value)| state.original(column) != Some(value))
196            .collect(),
197        _ if !record.is_new() => values,
198        // Unset (NULL) columns are left out, so the database's defaults
199        // apply, as Rails' new records start from the schema's defaults.
200        _ => values
201            .into_iter()
202            .filter(|(column, value)| {
203                let timestamp = Some(*column) == M::CREATED_AT || Some(*column) == M::UPDATED_AT;
204                *column != M::PRIMARY_KEY
205                    && !value.is_null()
206                    && !(timestamp && is_unset_time(value))
207            })
208            .collect(),
209    }
210}
211
212/// A timestamp nobody set: a new record's non-optional timestamp starts at
213/// the Unix epoch (its `Default`).
214fn is_unset_time(value: &Value) -> bool {
215    matches!(value, Value::Timestamp(t) if t.timestamp() == 0 && t.timestamp_subsec_nanos() == 0)
216}
217
218/// A changeset of the record's pending changes, plus its cast failures.
219fn pending<M: Model + Clone>(record: &M, new: bool) -> Changeset<M> {
220    let mut changeset = if new {
221        Changeset::new()
222    } else {
223        Changeset::for_record(record.clone())
224    };
225    for (column, value) in changes(record) {
226        changeset = changeset.put(column, value);
227    }
228    if let Some(state) = record.record() {
229        for (column, message) in state.cast_errors() {
230            changeset = changeset.push_error(column, message);
231        }
232    }
233    changeset
234}
235
236fn keep_errors<M: Model>(record: &mut M, changeset: &Changeset<M>) {
237    if let Some(state) = record.record_mut() {
238        state.errors = changeset.errors().to_vec();
239    }
240}
241
242/// Validates and inserts or updates `record` in place, running its
243/// callbacks in Rails' order; `false` (with errors on the record) when
244/// it's invalid.
245/// Errors from a model's own `validate`: `errors.add("password", "is too
246/// short")`.
247#[derive(Debug, Default)]
248pub struct Errors(Vec<(&'static str, String)>);
249
250impl Errors {
251    pub fn add(&mut self, column: &'static str, message: impl Into<String>) {
252        self.0.push((column, message.into()));
253    }
254
255    pub fn is_empty(&self) -> bool {
256        self.0.is_empty()
257    }
258}
259
260/// The record's pending write, with its fields' and its own validations
261/// (and its uploads').
262fn validated<M: Model + Clone>(
263    record: &M,
264    new: bool,
265    files: &[crate::attachment::Pending],
266) -> Changeset<M> {
267    let mut changeset = M::validate(pending(record, new));
268    let mut errors = Errors::default();
269    for file in files {
270        file.validate(&mut errors);
271    }
272    record.validate_attributes(&mut errors);
273    record.validate_record(&mut errors);
274    for (column, message) in errors.0 {
275        changeset = changeset.push_error(column, message);
276    }
277    changeset
278}
279
280/// A field's value through its `normalize:` closure.
281#[doc(hidden)]
282pub fn normalized<T>(value: &T, normalize: impl FnOnce(&T) -> T) -> T {
283    normalize(value)
284}
285
286/// An optional field's value through its `normalize:` closure, when it
287/// has one.
288#[doc(hidden)]
289pub fn normalized_option<T>(value: &Option<T>, normalize: impl FnOnce(&T) -> T) -> Option<T> {
290    value.as_ref().map(normalize)
291}
292
293/// An `acceptance` field's value is accepted: not sent at all, or `true`,
294/// `1`, `yes` or `on` (a checkbox).
295#[doc(hidden)]
296pub fn accepted(value: &Value) -> bool {
297    match value {
298        Value::Null => true,
299        Value::Bool(b) => *b,
300        Value::Int(n) => *n == 1,
301        Value::Text(t) => matches!(
302            t.trim().to_ascii_lowercase().as_str(),
303            "1" | "true" | "yes" | "on"
304        ),
305        _ => false,
306    }
307}
308
309/// `Model.create(params)` and `record.update_changeset(changes)`: the
310/// changeset's own casts and validations, with the model's callbacks and
311/// `validate do` around them in Rails' order (`before_validation`,
312/// validations, `before_save`, `before_create`/`before_update`, the write,
313/// `after_create`/`after_update`, `after_save`), on the record the changes
314/// make. A callback's changes (a slug from the title) are written too.
315pub(crate) async fn write_changeset<M: Model>(
316    mut changeset: Changeset<M>,
317    new: bool,
318) -> Result<Save<M>> {
319    let (record, was) = if new {
320        (changeset.new_record(), Vec::new())
321    } else {
322        match changeset.take_record() {
323            Some((record, was)) => (Some(record), was),
324            None => (None, Vec::new()),
325        }
326    };
327    // A model without `Default` has no record to call back: the write as
328    // it was. (And `update` needs the record it changes.)
329    let Some(mut record) = record else {
330        return if new {
331            changeset.insert().await
332        } else {
333            changeset.update().await
334        };
335    };
336    let before = record.values();
337    if new {
338        record.belongs_to_defaults().await?;
339    }
340    record.normalize_fields();
341    record.before_validation().await?;
342    let mut errors = Errors::default();
343    record.validate_attributes(&mut errors);
344    record.validate_record(&mut errors);
345    let mut changeset = changeset.changed_by(&record, &before);
346    // Validations read an update's record: a field the params didn't send
347    // is the record's.
348    let mut kept = None;
349    if new {
350        kept = Some(record);
351    } else {
352        changeset = changeset.attach(record);
353    }
354    let mut changeset = M::validate(changeset);
355    for (column, message) in errors.0 {
356        changeset = changeset.push_error(column, message);
357    }
358    if !changeset.is_valid() {
359        // The record as it was: the changeset holds the changes.
360        if let Some(record) = changeset.data_mut() {
361            for (column, value) in was {
362                record.set_value(column, value);
363            }
364        }
365        let conn = changeset.connection()?;
366        changeset.check_unique(&conn).await?;
367        return Ok(Save::Invalid(changeset));
368    }
369    let mut record = match kept {
370        Some(record) => record,
371        None => changeset
372            .take_data()
373            .expect("an update's record is attached"),
374    };
375    let before = record.values();
376    record.before_save().await?;
377    if new {
378        record.before_create().await?;
379    } else {
380        record.before_update().await?;
381    }
382    let changeset = changeset.changed_by(&record, &before);
383    let saved = if new {
384        changeset.insert_valid().await?
385    } else {
386        changeset.attach(record).update_valid().await?
387    };
388    let Save::Saved(mut fresh) = saved else {
389        return Ok(saved);
390    };
391    if new {
392        fresh.after_create().await?;
393    } else {
394        fresh.after_update().await?;
395    }
396    fresh.after_save().await?;
397    Ok(Save::Saved(fresh))
398}
399
400pub(crate) async fn save<M: Model + Clone>(record: &mut M) -> Result<bool> {
401    // Uploads for `has_attached`: their columns are set now, their files
402    // stored once the record is, in the same transaction, so a file that
403    // can't be stored leaves the row (and the record) as they were.
404    // Boxed: nested records save through here, and the write's future is
405    // large enough to overflow the stack when they nest.
406    if !M::ATTACHMENTS {
407        return Box::pin(write(record, Vec::new())).await;
408    }
409    let before = record.clone();
410    let files = record.take_attachments();
411    if files.is_empty() {
412        return Box::pin(write(record, files)).await;
413    }
414    let saved = Box::pin(crate::db::savepoint_in(M::DATABASE, write(record, files))).await;
415    if saved.is_err() {
416        *record = before;
417    }
418    saved
419}
420
421async fn write<M: Model + Clone>(
422    record: &mut M,
423    files: Vec<crate::attachment::Pending>,
424) -> Result<bool> {
425    let new = record.is_new();
426    if new {
427        record.belongs_to_defaults().await?;
428    }
429    record.normalize_fields();
430    record.before_validation().await?;
431    let mut checked = validated(record, new, &files);
432    if !checked.is_valid() {
433        // As Rails, every error at once: "has already been taken" too.
434        let conn = checked.connection()?;
435        checked.check_unique(&conn).await?;
436        keep_errors(record, &checked);
437        return Ok(false);
438    }
439    record.before_save().await?;
440    if new {
441        record.before_create().await?;
442    } else {
443        record.before_update().await?;
444    }
445    // Callbacks may have changed fields (a slug from the title, say), so
446    // the write is built again, but not validated again, as Rails: a
447    // callback that clears a virtual field (a password, once hashed) mustn't
448    // fail the save. Uniqueness is still checked as it's written.
449    let changeset = M::validate(pending(record, new)).without_errors();
450    let saved = if new {
451        changeset.insert_valid().await?
452    } else {
453        changeset.update_valid().await?
454    };
455    match saved {
456        Save::Saved(fresh) => {
457            *record = fresh;
458            if !files.is_empty() {
459                let id = match record.id_value() {
460                    crate::db::Value::Int(id) => id,
461                    other => other
462                        .to_text()
463                        .parse()
464                        .map_err(|_| crate::Error::internal("attachments need an integer id"))?,
465                };
466                for file in files {
467                    file.store(id).await?;
468                }
469            }
470            if new {
471                record.after_create().await?;
472            } else {
473                record.after_update().await?;
474            }
475            record.after_save().await?;
476            Ok(true)
477        }
478        // A unique constraint the database caught.
479        Save::Invalid(changeset) => {
480            keep_errors(record, &changeset);
481            Ok(false)
482        }
483    }
484}