Skip to main content

glacier/
model.rs

1//! Database models.
2//!
3//! `#[derive(Model)]` maps a struct to a table and gives it Rails-style
4//! class methods. They run on the ambient connection (see `glacier::db`):
5//!
6//! ```no_run
7//! use glacier::prelude::*;
8//!
9//! #[derive(Model)]
10//! struct Post {
11//!     id: i64,
12//!     title: String,
13//!     views: i64,
14//! }
15//!
16//! # async fn demo() -> glacier::Result<()> {
17//! let post = Post::find(1).await?;                        // 404 if missing
18//! let recent = Post::all().order(|p| p.id.desc()).limit(5).await?;
19//! let popular = Post::filter(|p| p.views.gt(100)).count().await?;
20//! # Ok(()) }
21//! ```
22//!
23//! The derive also generates a `PostColumns` struct with one typed column
24//! per field; queries receive it in their closures (`|p| p.views.gt(100)`).
25//!
26//! Field attributes: `#[glacier(skip)]` (not a column; filled with
27//! `Default::default()` when loading) and `#[glacier(primary_key)]` (when
28//! the key isn't `id`). Struct attribute: `#[glacier(table = "…")]`. A
29//! field named `inserted_at` or `updated_at` of type `Timestamp` is filled
30//! in automatically on insert and update.
31
32use std::future::Future;
33
34use crate::context::Params;
35use crate::db::{Changeset, Expr, Order, Preload, Query, Record, Row, Save, ToValue, Value};
36use crate::error::Result;
37
38/// Implemented via `#[derive(Model)]`.
39///
40/// ```
41/// use glacier::Model;
42///
43/// #[derive(Model)]
44/// struct BlogPost {
45///     id: i64,
46///     title: String,
47///     #[glacier(skip)]
48///     cached_html: Option<String>,
49/// }
50///
51/// assert_eq!(BlogPost::TABLE, "blog_posts");
52/// assert_eq!(BlogPost::COLUMNS, &["id", "title"]);
53/// ```
54/// Hooks around saving and destroying a record, run by
55/// [`Model::save`]/[`Model::update`] (in Rails' order: `before_validation`,
56/// validations, `before_save`, `before_create` or `before_update`, the
57/// write, `after_create` or `after_update`, `after_save`) and
58/// [`Model::destroy`]. Each does nothing unless implemented; an error stops
59/// the save and is returned.
60///
61/// ```ignore
62/// #[glacier::model(callbacks)]
63/// pub struct Post { title: String, slug: String }
64///
65/// impl Callbacks for Post {
66///     async fn before_save(&mut self) -> glacier::Result<()> {
67///         self.slug = slugify(&self.title);
68///         Ok(())
69///     }
70/// }
71/// ```
72///
73/// The changeset path (`Post::create`, `update_changeset`) has no
74/// callbacks, like Ecto.
75pub trait Callbacks: Send {
76    /// The model's own checks, beyond its fields' validations, as Rails'
77    /// `validate do … end`: add to `errors` and the save fails with them.
78    /// Runs on every record save, after `before_validation`.
79    fn validate_record(&self, errors: &mut crate::db::Errors) {
80        let _ = errors;
81    }
82
83    fn before_validation(&mut self) -> impl Future<Output = Result<()>> + Send {
84        async { Ok(()) }
85    }
86    fn before_save(&mut self) -> impl Future<Output = Result<()>> + Send {
87        async { Ok(()) }
88    }
89    fn before_create(&mut self) -> impl Future<Output = Result<()>> + Send {
90        async { Ok(()) }
91    }
92    fn before_update(&mut self) -> impl Future<Output = Result<()>> + Send {
93        async { Ok(()) }
94    }
95    fn after_create(&mut self) -> impl Future<Output = Result<()>> + Send {
96        async { Ok(()) }
97    }
98    fn after_update(&mut self) -> impl Future<Output = Result<()>> + Send {
99        async { Ok(()) }
100    }
101    fn after_save(&mut self) -> impl Future<Output = Result<()>> + Send {
102        async { Ok(()) }
103    }
104    fn before_destroy(&mut self) -> impl Future<Output = Result<()>> + Send {
105        async { Ok(()) }
106    }
107    fn after_destroy(&mut self) -> impl Future<Output = Result<()>> + Send {
108        async { Ok(()) }
109    }
110}
111
112pub trait Model: Callbacks + Sized + Send + Sync + 'static {
113    /// Defaults to the snake_case, pluralized struct name.
114    const TABLE: &'static str;
115    const COLUMNS: &'static [&'static str];
116    /// What a bare JSON body may set, which a controller's params wrap as
117    /// Rails' `wrap_parameters` does: the columns, and the derive adds
118    /// attributes that aren't stored and nested `<name>_attributes`.
119    const ATTRIBUTES: &'static [&'static str] = Self::COLUMNS;
120    /// The columns an [`Access`](crate::access::Access) owns rows by, each
121    /// with the access's key it holds: `("org_id", "org_id")` for `owned_by
122    /// :org` in `.glacier`, `("account_id", "org_id")` for `owned_by :org,
123    /// foreign_key: :account_id`. Empty for a model that isn't scoped.
124    const OWNER: &'static [(&'static str, &'static str)] = &[];
125    /// The model's `belongs_to` parents, so saving checks that an owned
126    /// parent is the same tenant's (a project of this note's org).
127    const PARENTS: &'static [Parent] = &[];
128    /// The columns stored encrypted (`field secret: String, encrypted`):
129    /// written through [`crate::encryption`] and read back as plain text.
130    const ENCRYPTED: &'static [&'static str] = &[];
131    /// Rows with no owner (`org_id` NULL) that every tenant reads, as
132    /// `owned_by :org, global: true` declares: shared templates, defaults.
133    /// They change only `unscoped`.
134    const GLOBAL_ROWS: bool = false;
135    /// `soft_deletes`: the column (`deleted_at`) a deleted record's time
136    /// goes in, rather than the row going. Queries leave such records out
137    /// unless `with_trashed()`; `restore()` brings one back and
138    /// `force_delete()` deletes it.
139    const SOFT_DELETE: Option<&'static str> = None;
140    /// The encrypted columns encrypted the same way every time
141    /// (`encrypted(deterministic)`), so queries can find their values.
142    const DETERMINISTIC: &'static [&'static str] = &[];
143    /// The columns never written to JSON (`serialize::attributes`, the
144    /// model's `Serialize` and its schema): `hidden` fields, `encrypted`
145    /// ones and `*_digest` columns such as `password_digest`.
146    const HIDDEN: &'static [&'static str] = &[];
147    const PRIMARY_KEY: &'static str = "id";
148    /// Whether the primary key is a number, so `find("12")` (a param, as
149    /// text) parses it, and text that isn't a number finds nothing.
150    const INTEGER_KEY: bool = true;
151    /// The named database the model lives in (`database = "analytics"`),
152    /// registered with `App::named_database`; `None` for the app's own.
153    const DATABASE: Option<&'static str> = None;
154    /// Whether the model has `has_attached` attachments. Generated by
155    /// `#[glacier::model(attachments)]`.
156    #[doc(hidden)]
157    const ATTACHMENTS: bool = false;
158    /// The column set when a record is inserted (`inserted_at`, or Rails'
159    /// `created_at`), if the model has one.
160    const CREATED_AT: Option<&'static str> = None;
161    /// The column set on every write, if the model has one.
162    const UPDATED_AT: Option<&'static str> = None;
163
164    /// The generated struct of typed columns (`PostColumns`).
165    type Columns;
166
167    fn columns() -> Self::Columns;
168    fn from_row(row: &Row) -> Result<Self>;
169    /// Every column with its current value.
170    fn values(&self) -> Vec<(&'static str, Value)>;
171    /// Sets a column or virtual field from a `Value`, the reverse of
172    /// [`values`](Self::values): `false` when there's no such field or the
173    /// value doesn't fit it. Generated by the derive; how a record is made
174    /// from a changeset, for its callbacks.
175    /// `normalize:` fields, set to their normal form before validation:
176    /// `field email: String, normalize: fn e -> e.trim().to_lowercase()
177    /// end`. Generated by the derive.
178    #[doc(hidden)]
179    fn normalize_fields(&mut self) {}
180    /// `belongs_to :account, default: …`: a new record's unset parent
181    /// keys, filled before `before_validation`. Generated.
182    #[doc(hidden)]
183    fn belongs_to_defaults(&mut self) -> impl Future<Output = Result<()>> + Send {
184        async { Ok(()) }
185    }
186    /// `confirmation` and `acceptance` checks, on the record itself (they
187    /// read virtual fields). Generated by the derive.
188    #[doc(hidden)]
189    fn validate_attributes(&self, errors: &mut crate::db::Errors) {
190        let _ = errors;
191    }
192    #[doc(hidden)]
193    fn set_value(&mut self, column: &str, value: Value) -> bool {
194        let _ = (column, value);
195        false
196    }
197    /// A new, empty record (`Default::default()`), or `None` for a model
198    /// without one. Generated by the derive.
199    #[doc(hidden)]
200    fn blank() -> Option<Self> {
201        None
202    }
203    /// The virtual fields (`#[glacier(attribute)]`) with their values.
204    fn attribute_values(&self) -> Vec<(&'static str, Value)> {
205        Vec::new()
206    }
207    fn id_value(&self) -> Value;
208
209    /// The model's own validations, run on every insert and update.
210    /// `#[validate(…)]` field attributes generate this.
211    fn validate(changeset: Changeset<Self>) -> Changeset<Self> {
212        changeset
213    }
214
215    /// A changeset casting the permitted fields from request params: every
216    /// column except the primary key, timestamps and fields marked
217    /// `#[glacier(protected)]`. Generated by the derive.
218    fn from_params(params: &Params) -> Changeset<Self> {
219        let _ = params;
220        Changeset::new()
221    }
222
223    /// The JSON Schema of the params `from_params` takes, for OpenAPI's
224    /// request bodies. Generated by the derive.
225    fn params_schema() -> serde_json::Value {
226        serde_json::json!({"type": "object"})
227    }
228
229    /// This record's URL: `/posts/7` by default (the table name and the
230    /// primary key). Override it when the routes differ.
231    fn path(&self) -> String {
232        let id = self.id_value().to_text();
233        // A nested resource's params from the record's own columns
234        // (`org_id`), else the request's.
235        let values = self.values();
236        let collection = crate::router::collection_path_of(Self::TABLE, |param| {
237            values
238                .iter()
239                .find(|(column, _)| *column == param)
240                .map(|(_, value)| value.to_text())
241        });
242        format!("{collection}/{}", crate::router::encode_segment(&id))
243    }
244
245    /// The URL of the collection, `/posts` by default.
246    fn collection_path() -> String {
247        crate::router::collection_path_of(Self::TABLE, |_| None)
248    }
249
250    /// All records, as a query to refine or `.await`.
251    fn all() -> Query<Self> {
252        Query::new()
253    }
254
255    /// Refines every query of the model, as Rails' `default_scope`:
256    /// `default_scope order(:position)` in a `.glacier` model.
257    fn default_scope(query: Query<Self>) -> Query<Self> {
258        query
259    }
260
261    /// The records `access` may see, `Post.for(access)` in `.glacier`:
262    /// those whose owner columns hold its values (the org's id). An
263    /// access that owns none of them sees nothing. Records built from the
264    /// query (`.build(params)`) get those values too.
265    fn r#for(access: &dyn crate::access::Access) -> Query<Self> {
266        Query::new().owned_by(access)
267    }
268
269    /// Sets an owner column (`org_id`) from its value as text. Generated
270    /// by the derive for `OWNER`'s columns, which params never set.
271    fn set_owner(&mut self, column: &str, value: &str) {
272        let _ = (column, value);
273    }
274
275    /// All records, without the default scope.
276    fn unscoped() -> Query<Self> {
277        Query::unscoped()
278    }
279
280    fn filter(condition: impl FnOnce(&Self::Columns) -> Expr) -> Query<Self> {
281        Query::new().filter(condition)
282    }
283
284    /// The records matching a condition in SQL, `?` for each of `values`,
285    /// as Rails' `where("…", …)`: see [`Query::where_sql`].
286    fn where_sql(sql: &str, values: impl IntoIterator<Item = crate::db::Value>) -> Query<Self> {
287        Self::all().where_sql(sql, values)
288    }
289
290    fn order(order: impl FnOnce(&Self::Columns) -> Order) -> Query<Self> {
291        Query::new().order(order)
292    }
293
294    /// All records with an association loaded: `Country::preload(|c|
295    /// c.installations)`, `Country.preload(:installations)` in `.glacier`.
296    fn preload<P: Into<Preload<Self>>>(
297        association: impl FnOnce(&Self::Columns) -> P,
298    ) -> Query<Self> {
299        Query::new().preload(association)
300    }
301
302    /// The record with this primary key, or `404 Not Found`.
303    /// The record with this primary key, or a `404 Not Found`. A key given
304    /// as text, such as `params[:id]`, is parsed for a numeric key, as
305    /// Rails' `find` is: text that isn't a number finds nothing.
306    fn find(id: impl ToValue) -> impl Future<Output = Result<Self>> + Send {
307        let id = match id.to_value() {
308            crate::db::Value::Text(text) if Self::INTEGER_KEY => {
309                text.trim().parse::<i64>().map(crate::db::Value::Int).ok()
310            }
311            value => Some(value),
312        };
313        let query = id.map(by_id::<Self>);
314        async move {
315            match query {
316                Some(query) => query.one().await,
317                None => Err(crate::Error::not_found()),
318            }
319        }
320    }
321
322    /// The first record matching `condition`, if any.
323    fn find_by(
324        condition: impl FnOnce(&Self::Columns) -> Expr,
325    ) -> impl Future<Output = Result<Option<Self>>> + Send {
326        let query = Self::filter(condition);
327        async move { query.first().await }
328    }
329
330    /// The first record matching `condition`, or a new unsaved one set up
331    /// by `init`, as Rails' `find_or_initialize_by`:
332    /// `Tag.find_or_initialize_by(name: "rust")` in `.glacier`.
333    fn find_or_initialize_by(
334        condition: impl FnOnce(&Self::Columns) -> Expr,
335        init: impl FnOnce(&mut Self) + Send,
336    ) -> impl Future<Output = Result<Self>> + Send
337    where
338        Self: Default,
339    {
340        let query = Self::filter(condition);
341        async move {
342            Ok(match query.first().await? {
343                Some(found) => found,
344                None => Self::default().tap(init),
345            })
346        }
347    }
348
349    /// The first record matching `condition`, or one set up by `init` and
350    /// saved, as Rails' `find_or_create_by`. A record that fails validation
351    /// comes back unsaved, with its errors.
352    fn find_or_create_by(
353        condition: impl FnOnce(&Self::Columns) -> Expr,
354        init: impl FnOnce(&mut Self) + Send,
355    ) -> impl Future<Output = Result<Self>> + Send
356    where
357        Self: Default + Clone,
358    {
359        let query = Self::filter(condition);
360        async move {
361            if let Some(found) = query.first().await? {
362                return Ok(found);
363            }
364            let mut record = Self::default().tap(init);
365            record.save().await?;
366            Ok(record)
367        }
368    }
369
370    /// The first record by primary key, if any.
371    fn first() -> impl Future<Output = Result<Option<Self>>> + Send {
372        Query::<Self>::new().first()
373    }
374
375    /// The last record by primary key, if any.
376    fn last() -> impl Future<Output = Result<Option<Self>>> + Send {
377        Query::<Self>::new().last()
378    }
379
380    /// The first `n` records by primary key.
381    fn take(n: u64) -> impl Future<Output = Result<Vec<Self>>> + Send {
382        Query::<Self>::new()
383            .order(|_| Order::by(Self::PRIMARY_KEY, false))
384            .take(n)
385    }
386
387    fn count() -> impl Future<Output = Result<i64>> + Send {
388        Query::<Self>::new().count()
389    }
390
391    /// Every record's primary key: `Book.ids()!`, as Rails' `Book.ids`.
392    fn ids() -> impl Future<Output = Result<Vec<i64>>> + Send {
393        Query::<Self>::new().ids()
394    }
395
396    /// Whether there are any records at all: `User.exists()!`, as
397    /// Rails' `User.exists?` (`User.exists(email: e)!` for some).
398    fn exists() -> impl Future<Output = Result<bool>> + Send {
399        Query::<Self>::new().exists()
400    }
401
402    /// Records with a related record meeting a condition:
403    /// `Post::join(|p| p.author, |a| a.name.eq("Ada"))`.
404    fn join<C: Model>(
405        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
406        condition: impl FnOnce(&C::Columns) -> Expr,
407    ) -> Query<Self> {
408        Query::new().join(association, condition)
409    }
410
411    /// Records with at least one related record: `Post::joins(|p| p.comments)`.
412    fn joins<C: Model>(
413        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
414    ) -> Query<Self> {
415        Query::new().joins(association)
416    }
417
418    /// Every record grouped by a column, to count or total each group:
419    /// `Post::group(|p| p.status).count()`, `Post.group(:status).count()`.
420    fn group<K: crate::db::FromColumn>(
421        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, K>,
422    ) -> crate::db::Grouped<Self, K> {
423        Query::new().group(column)
424    }
425
426    /// The sum of a numeric column over every record: `Post.sum(:views)`.
427    fn sum<T: crate::db::Summable>(
428        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
429    ) -> impl Future<Output = Result<T::Sum>> + Send {
430        Query::<Self>::new().sum(column)
431    }
432
433    /// The mean of a numeric column over every record.
434    fn average<T: crate::db::Summable>(
435        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
436    ) -> impl Future<Output = Result<Option<f64>>> + Send {
437        Query::<Self>::new().average(column)
438    }
439
440    /// The smallest value of a column.
441    fn minimum<T: crate::db::Aggregable>(
442        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
443    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
444        Query::<Self>::new().minimum(column)
445    }
446
447    /// The largest value of a column.
448    fn maximum<T: crate::db::Aggregable>(
449        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
450    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
451        Query::<Self>::new().maximum(column)
452    }
453
454    /// Inserts a record from params, a changeset, or anything convertible
455    /// into one:
456    ///
457    /// ```ignore
458    /// match Post::create(ctx.params()).await? {
459    ///     Saved(post) => redirect!(post, notice: "Post created."),
460    ///     Invalid(changeset) => render!(changeset; template = new, status = 422),
461    /// }
462    /// ```
463    ///
464    /// The model's callbacks run, as Rails' `create` runs them;
465    /// `changeset.insert()` is the write without them.
466    fn create(
467        changes: impl Into<Changeset<Self>>,
468    ) -> impl Future<Output = Result<Save<Self>>> + Send {
469        let changeset = changes.into();
470        async move { crate::db::record::write_changeset(changeset, true).await }
471    }
472
473    /// Inserts a new record its fields set by `change`, running the
474    /// callbacks and validations as [`save`](Self::save) does:
475    /// `.glacier`'s `Post.create(title: "Hi")!`. Returns `Saved(post)` or
476    /// `Invalid` with its errors.
477    fn create_with(
478        change: impl FnOnce(&mut Self),
479    ) -> impl Future<Output = Result<Save<Self>>> + Send
480    where
481        Self: Default + Clone,
482    {
483        let mut record = Self::build_with(change);
484        async move {
485            if record.save().await? {
486                return Ok(Save::Saved(record));
487            }
488            let mut changeset = Changeset::<Self>::new();
489            for (column, message) in record.errors() {
490                changeset = changeset.push_error(column, message.clone());
491            }
492            Ok(Save::Invalid(changeset))
493        }
494    }
495
496    /// A changeset for a new record: `Post::changeset().set(|p| p.title, t)`.
497    fn changeset() -> Changeset<Self> {
498        Changeset::new()
499    }
500
501    /// An empty changeset for this record, to build an update by hand.
502    fn change(self) -> Changeset<Self> {
503        Changeset::for_record(self)
504    }
505
506    /// Applies params, a changeset or anything convertible into one to this
507    /// record, Ecto-style, returning `Saved(record)` or `Invalid(changeset)`.
508    /// [`update`](Self::update) is the Active Record-style version.
509    ///
510    /// The model's callbacks run, as `update` runs them;
511    /// `changeset.update()` is the write without them.
512    fn update_changeset(
513        self,
514        changes: impl Into<Changeset<Self>>,
515    ) -> impl Future<Output = Result<Save<Self>>> + Send {
516        let changeset = changes.into().attach(self);
517        async move { crate::db::record::write_changeset(changeset, false).await }
518    }
519
520    /// Deletes the record, running `before_destroy`, then removing its
521    /// `dependent` children, then `after_destroy`.
522    fn destroy(mut self) -> impl Future<Output = Result<()>> + Send {
523        async move {
524            self.check_not_shared()?;
525            self.before_destroy().await?;
526            // A soft delete keeps its children, to come back with it.
527            if Self::SOFT_DELETE.is_none() {
528                self.destroy_dependents().await?;
529            }
530            by_id::<Self>(self.id_value())
531                .of_record()
532                .delete_all()
533                .await?;
534            for file in self.attached_files() {
535                file.remove().await?;
536            }
537            self.touch_parents().await?;
538            self.after_destroy().await
539        }
540    }
541
542    /// The uploads waiting to be kept by `has_attached`, taken from the
543    /// record (its columns set from them) as it saves. Generated by
544    /// `#[glacier::model(attachments)]`.
545    #[doc(hidden)]
546    fn take_attachments(&mut self) -> Vec<crate::attachment::Pending> {
547        Vec::new()
548    }
549
550    /// The files the record keeps through `has_attached`, removed with it.
551    #[doc(hidden)]
552    fn attached_files(&self) -> Vec<crate::attachment::Attached> {
553        Vec::new()
554    }
555
556    /// Sets `updated_at` on the parents of `belongs_to … touch`
557    /// associations, after a write. Generated by `#[glacier::model]`.
558    #[doc(hidden)]
559    fn touch_parents(&self) -> impl Future<Output = Result<()>> + Send {
560        async { Ok(()) }
561    }
562
563    /// Removes the children of `has_many … dependent` associations.
564    /// Generated by `#[glacier::model]`.
565    #[doc(hidden)]
566    fn destroy_dependents(&self) -> impl Future<Output = Result<()>> + Send {
567        async { Ok(()) }
568    }
569
570    /// Deletes the record without callbacks.
571    fn delete(self) -> impl Future<Output = Result<()>> + Send {
572        let query = by_id::<Self>(self.id_value()).of_record();
573        let shared = self.check_not_shared();
574        async move {
575            shared?;
576            query.delete_all().await?;
577            Ok(())
578        }
579    }
580
581    /// Whether it's been soft-deleted (`soft_deletes`): `deleted_at` set.
582    fn is_trashed(&self) -> bool {
583        Self::SOFT_DELETE.is_some_and(|column| {
584            self.values()
585                .into_iter()
586                .any(|(c, value)| c == column && !value.is_null())
587        })
588    }
589
590    /// Brings a soft-deleted record back: `deleted_at` cleared, in the
591    /// database and on the record.
592    fn restore(&mut self) -> impl Future<Output = Result<()>> + Send {
593        let column = Self::SOFT_DELETE;
594        let query = by_id::<Self>(self.id_value()).of_record().with_trashed();
595        if let Some(column) = column {
596            self.set_value(column, Value::Null);
597        }
598        async move {
599            let Some(column) = column else {
600                return Err(crate::Error::internal(
601                    "restore is for a model with `soft_deletes`",
602                ));
603            };
604            query
605                .update_all(|_| [crate::db::Assign::new(column, Value::Null)])
606                .await?;
607            Ok(())
608        }
609    }
610
611    /// Deletes the row for good, even with `soft_deletes`; no callbacks.
612    fn force_delete(self) -> impl Future<Output = Result<()>> + Send {
613        let query = by_id::<Self>(self.id_value()).of_record().with_trashed();
614        let shared = self.check_not_shared();
615        async move {
616            shared?;
617            query.force_delete_all().await?;
618            Ok(())
619        }
620    }
621
622    /// The records with an associated record matching `inner`:
623    /// `Author.where_has(:books, published: true)`.
624    fn where_has<C: Model>(
625        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
626        inner: impl FnOnce(Query<C>) -> Query<C>,
627    ) -> Query<Self> {
628        Query::new().where_has(association, inner)
629    }
630
631    /// The records with no associated record: `Author.without(:books)`.
632    fn without<C: Model>(
633        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
634    ) -> Query<Self> {
635        Query::new().without(association)
636    }
637
638    /// Every record, soft-deleted ones too.
639    fn with_trashed() -> Query<Self> {
640        Query::new().with_trashed()
641    }
642
643    /// Only the soft-deleted records.
644    fn only_trashed() -> Query<Self> {
645        Query::new().only_trashed()
646    }
647
648    /// `Err(403)` for a shared row (no owner, in a `global` model) changed
649    /// under a tenant's access: those change only `unscoped`.
650    #[doc(hidden)]
651    fn check_not_shared(&self) -> Result<()> {
652        if !Self::GLOBAL_ROWS || crate::access::may_change_shared() {
653            return Ok(());
654        }
655        let values = self.values();
656        let shared = Self::OWNER.iter().all(|(column, _)| {
657            values
658                .iter()
659                .find(|(c, _)| c == column)
660                .is_none_or(|(_, value)| value.is_null())
661        });
662        if shared {
663            Err(crate::Error::new(
664                http::StatusCode::FORBIDDEN,
665                "a shared row changes only `unscoped`",
666            ))
667        } else {
668            Ok(())
669        }
670    }
671
672    /// Sets the record's `updated_at` to now in the database, without
673    /// callbacks or validation, as Rails' `touch`. The record in hand keeps
674    /// its old `updated_at`. Nothing happens without that column.
675    fn touch(&self) -> impl Future<Output = Result<()>> + Send {
676        crate::db::assoc::touch_parent::<Self>(self.id_value())
677    }
678
679    // Active Record style: the record carries its state (see
680    // `glacier::db::Record`, which `#[glacier::model]` adds).
681
682    /// The record's state, when the model has one (`#[glacier::model]`).
683    fn record(&self) -> Option<&Record> {
684        None
685    }
686
687    fn record_mut(&mut self) -> Option<&mut Record> {
688        None
689    }
690
691    /// A new, unsaved record with default values: `Post::new()`.
692    fn new() -> Self
693    where
694        Self: Default,
695    {
696        Self::default()
697    }
698
699    /// Changes fields in a closure and returns the record:
700    /// `Post::new().tap(|p| p.title = "Hi".into())`.
701    fn tap(mut self, change: impl FnOnce(&mut Self)) -> Self {
702        change(&mut self);
703        self
704    }
705
706    /// A new record from form params: `Post::build(ctx.params())`.
707    fn build(params: impl Into<Params>) -> Self
708    where
709        Self: Default,
710    {
711        let mut record = Self::default();
712        record.assign(&params.into());
713        record
714    }
715
716    /// A new record, with `change` setting its fields: `Note.build(title:
717    /// "…")` in `.glacier`.
718    fn build_with(change: impl FnOnce(&mut Self)) -> Self
719    where
720        Self: Default,
721    {
722        let mut record = Self::default();
723        change(&mut record);
724        record
725    }
726
727    /// Loads an association of this record now, as `preload` does for a
728    /// query's: `post.load(:comments)!`, then `post.comments`.
729    fn load<P: Into<crate::db::Preload<Self>>>(
730        &mut self,
731        association: impl FnOnce(&Self::Columns) -> P,
732    ) -> impl Future<Output = Result<()>> + Send {
733        let preload = association(&Self::columns()).into();
734        async move {
735            let conn = crate::db::current_in(Self::DATABASE)?;
736            preload.run(std::slice::from_mut(self), conn).await
737        }
738    }
739
740    /// A new record of a `has_many` association, its foreign key this
741    /// record's, `change` setting its fields: `post.build(:comments, body:
742    /// "…")` in `.glacier`, as Rails' `post.comments.build`.
743    fn build_in<C: Model + Default>(
744        &self,
745        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
746        change: impl FnOnce(&mut C),
747    ) -> C {
748        let association = association(&Self::columns());
749        let (own, other) = association
750            .join
751            .expect("build_in is for a `has_many` (not `through` a join table)");
752        let key = self
753            .values()
754            .into_iter()
755            .find(|(column, _)| *column == own)
756            .map_or(Value::Null, |(_, value)| value);
757        let mut child = C::default();
758        change(&mut child);
759        child.set_value(other, key);
760        // A polymorphic child names this model too.
761        if let Some((column, name)) = association.kind {
762            child.set_value(column, Value::Text(name.to_owned()));
763        }
764        child
765    }
766
767    /// Links this record to more records of a `has_many … through:` (by
768    /// id), as Laravel's `attach`: `book.attach(:tags, [tag.id])!`.
769    /// Links that exist already are left alone.
770    fn attach<C: Model>(
771        &self,
772        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
773        ids: impl IntoIterator<Item = i64>,
774    ) -> impl Future<Output = Result<()>> + Send {
775        self.write_links(association, ids, crate::db::assoc::Links::Add)
776    }
777
778    /// Unlinks records of a `has_many … through:` (by id): `detach`.
779    fn detach<C: Model>(
780        &self,
781        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
782        ids: impl IntoIterator<Item = i64>,
783    ) -> impl Future<Output = Result<()>> + Send {
784        self.write_links(association, ids, crate::db::assoc::Links::Remove)
785    }
786
787    /// Links this record to exactly these records of a `has_many …
788    /// through:` (by id), as Laravel's `sync`.
789    fn sync<C: Model>(
790        &self,
791        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
792        ids: impl IntoIterator<Item = i64>,
793    ) -> impl Future<Output = Result<()>> + Send {
794        self.write_links(association, ids, crate::db::assoc::Links::Exactly)
795    }
796
797    #[doc(hidden)]
798    fn write_links<C: Model>(
799        &self,
800        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
801        ids: impl IntoIterator<Item = i64>,
802        links: crate::db::assoc::Links,
803    ) -> impl Future<Output = Result<()>> + Send {
804        let through = association(&Self::columns()).through;
805        let owner = self.id_value();
806        let ids: Vec<i64> = ids.into_iter().collect();
807        async move {
808            let (table, owner_key, target_key) = through.ok_or_else(|| {
809                crate::Error::internal("attach, detach and sync are for a `has_many … through:`")
810            })?;
811            crate::db::assoc::write_through_ids(owner, table, owner_key, target_key, ids, links)
812                .await
813        }
814    }
815
816    /// `build_in`, then saved: `post.create(:comments, body: "…")!`.
817    fn create_in<C: Model + Default + Clone>(
818        &self,
819        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
820        change: impl FnOnce(&mut C),
821    ) -> impl Future<Output = Result<crate::db::Save<C>>> + Send {
822        let mut child = self.build_in(association, change);
823        async move {
824            if child.save().await? {
825                return Ok(crate::db::Save::Saved(child));
826            }
827            let mut changeset = crate::db::Changeset::<C>::new();
828            for (column, message) in child.errors() {
829                changeset = changeset.push_error(column, message.clone());
830            }
831            Ok(crate::db::Save::Invalid(changeset))
832        }
833    }
834
835    /// Sets the permitted fields from params, keeping input that doesn't
836    /// cast (and why) for the form. Generated by the derive.
837    fn assign(&mut self, params: &Params) {
838        let _ = params;
839    }
840
841    /// Sets the protected fields too, which params never set: for trusted
842    /// code only, as a test's factory is. Generated by the derive.
843    #[doc(hidden)]
844    fn assign_protected(&mut self, params: &Params) {
845        let _ = params;
846    }
847
848    /// Whether the record hasn't been saved yet.
849    fn is_new(&self) -> bool {
850        match self.record() {
851            Some(state) => !state.is_persisted(),
852            None => matches!(self.id_value(), Value::Null | Value::Int(0)),
853        }
854    }
855
856    fn is_persisted(&self) -> bool {
857        !self.is_new()
858    }
859
860    /// The columns that differ from what was loaded (every column for a new
861    /// record), as `save` would write them.
862    fn changes(&self) -> Vec<(&'static str, Value)> {
863        crate::db::record::changes(self)
864    }
865
866    fn is_changed(&self) -> bool {
867        !self.changes().is_empty()
868    }
869
870    /// Whether `column` differs from what was loaded.
871    fn changed(&self, column: &str) -> bool {
872        self.changes().iter().any(|(c, _)| *c == column)
873    }
874
875    /// The column's value as loaded, before any change.
876    fn was(&self, column: &str) -> Option<Value> {
877        self.record()?.original(column).cloned()
878    }
879
880    /// Validates and saves the record (insert or update), in place: `true`
881    /// when saved; `false` with [`errors`](Self::errors) when invalid.
882    fn save(&mut self) -> impl Future<Output = Result<bool>> + Send
883    where
884        Self: Clone,
885    {
886        crate::db::record::save(self)
887    }
888
889    /// Sets fields from params and saves, in place: `true` when saved,
890    /// `false` with [`errors`](Self::errors) when invalid.
891    ///
892    /// ```ignore
893    /// if post.update(ctx.params()).await? { … } else { … }
894    /// ```
895    fn update(&mut self, params: impl Into<Params>) -> impl Future<Output = Result<bool>> + Send
896    where
897        Self: Clone,
898    {
899        let params = params.into();
900        self.assign(&params);
901        async move {
902            if !Self::HAS_NESTED {
903                return crate::db::record::save(self).await;
904            }
905            // With nested attributes, the record and its children are saved
906            // together or not at all.
907            let state = self.record().cloned();
908            let kept: Vec<(&'static str, Value)> = self
909                .values()
910                .into_iter()
911                .filter(|(column, _)| {
912                    *column == Self::PRIMARY_KEY
913                        || Some(*column) == Self::CREATED_AT
914                        || Some(*column) == Self::UPDATED_AT
915                })
916                .collect();
917            let saved = crate::db::savepoint_in(Self::DATABASE, async {
918                if !crate::db::record::save(&mut *self).await? || !self.save_nested(&params).await?
919                {
920                    return Err(crate::db::assoc::nested_invalid());
921                }
922                Ok(())
923            })
924            .await;
925            if saved.is_err() {
926                // Rolled back, so the record is as it was before the
927                // save, as Rails restores it: new if it was (its id gone),
928                // its changes still to write, the errors kept.
929                for (column, value) in kept {
930                    self.set_value(column, value);
931                }
932                if let (Some(state), Some(now)) = (state, self.record_mut()) {
933                    let errors = now.errors().to_vec();
934                    *now = state;
935                    now.set_errors(errors);
936                }
937            }
938            match saved {
939                Ok(()) => Ok(true),
940                Err(err) if crate::db::assoc::is_nested_invalid(&err) => Ok(false),
941                Err(err) => Err(err),
942            }
943        }
944    }
945
946    /// Whether the model takes nested attributes (`has_many … nested`).
947    #[doc(hidden)]
948    const HAS_NESTED: bool = false;
949
950    /// Applies `<association>_attributes` from `params` to the children,
951    /// adding their errors to this record's; `false` if any is invalid.
952    /// Generated by `#[glacier::model]`.
953    #[doc(hidden)]
954    fn save_nested<'a>(
955        &'a mut self,
956        params: &'a Params,
957    ) -> std::pin::Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
958        let _ = params;
959        Box::pin(async { Ok(true) })
960    }
961
962    /// Changes fields in a closure, then saves:
963    /// `post.update_with(|p| p.title = "New".into()).await?`.
964    fn update_with(
965        &mut self,
966        change: impl FnOnce(&mut Self),
967    ) -> impl Future<Output = Result<bool>> + Send
968    where
969        Self: Clone,
970    {
971        change(self);
972        crate::db::record::save(self)
973    }
974
975    /// Loads the record again from the database, dropping unsaved changes.
976    fn reload(&mut self) -> impl Future<Output = Result<()>> + Send {
977        let query = by_id::<Self>(self.id_value()).of_record();
978        async move {
979            *self = query.one().await?;
980            Ok(())
981        }
982    }
983
984    /// The errors from the last `save`: `(column, message)`.
985    fn errors(&self) -> &[(&'static str, String)] {
986        self.record().map_or(&[], Record::errors)
987    }
988
989    /// Error messages for one column, to show next to its form field.
990    fn errors_on(&self, column: &str) -> Vec<&str> {
991        self.errors()
992            .iter()
993            .filter(|(c, _)| *c == column)
994            .map(|(_, m)| m.as_str())
995            .collect()
996    }
997
998    /// The errors as Rails renders them in JSON: `{"title": ["can't be blank"]}`.
999    fn errors_json(&self) -> serde_json::Value {
1000        crate::db::record::errors_json(self.errors())
1001    }
1002
1003    /// Messages with their column, lower case: `["title can't be blank"]`,
1004    /// for matching in tests and building nested records' errors.
1005    fn messages(&self) -> Vec<String> {
1006        self.errors()
1007            .iter()
1008            .map(|(c, m)| format!("{} {m}", c.replace('_', " ")))
1009            .collect()
1010    }
1011
1012    /// Messages with their column, as Rails shows them:
1013    /// `["Title can't be blank"]`.
1014    fn full_messages(&self) -> Vec<String> {
1015        self.errors()
1016            .iter()
1017            .map(|(c, m)| format!("{} {m}", crate::db::humanize(c)))
1018            .collect()
1019    }
1020
1021    /// One field for a form, its value and errors, for the `<.input>`
1022    /// component: `<.input field={post.field("title")} />`.
1023    fn field(&self, column: &str) -> crate::view::Field {
1024        crate::view::Field::new(
1025            column,
1026            self.text(column),
1027            self.errors_on(column)
1028                .into_iter()
1029                .map(str::to_owned)
1030                .collect(),
1031        )
1032    }
1033
1034    /// The column's value as text for a form field, or the input that
1035    /// couldn't be cast: `value="{{ post.text("price") }}"`.
1036    fn text(&self, column: &str) -> String {
1037        if let Some(raw) = self.record().and_then(|r| r.raw(column)) {
1038            return raw.to_owned();
1039        }
1040        self.values()
1041            .into_iter()
1042            .chain(self.attribute_values())
1043            .find(|(c, _)| *c == column)
1044            .map(|(_, v)| v.to_text())
1045            .unwrap_or_default()
1046    }
1047}
1048
1049/// A `belongs_to` parent, as [`Model::PARENTS`] lists them.
1050#[derive(Debug, Clone, Copy)]
1051pub struct Parent {
1052    /// The key column on this model: `project_id`.
1053    pub column: &'static str,
1054    /// The parent's table and primary key.
1055    pub table: &'static str,
1056    pub key: &'static str,
1057    /// The parent's owner columns and the access keys they hold.
1058    pub owner: &'static [(&'static str, &'static str)],
1059}
1060
1061pub(crate) fn by_id<M: Model>(id: Value) -> Query<M> {
1062    Query::new().filter(|_| Expr::Compare {
1063        column: M::PRIMARY_KEY,
1064        op: "=",
1065        value: id,
1066    })
1067}