Skip to main content

tablo_core/column/
relation.rs

1//! [`RelationColumn`] and [`CountColumn`]: columns over a relation field, and the
2//! [`RelationLens`] that names the field, built by [`relation!`](crate::relation!).
3
4use std::sync::Arc;
5
6use derive_where::derive_where;
7use toasty::{Deferred, Executor};
8use topcoat::{Result, context::Cx};
9
10use super::{Column, ColumnToggle, ColumnWidth, Includes, Related};
11use crate::{BoxFuture, DeclarationErrorKind, lens::Reads, schema::OptionSource};
12
13mod count;
14mod lens;
15mod restrict;
16
17pub use count::CountColumn;
18pub use lens::RelationLens;
19use restrict::{Restrict, restrict_many, restrict_one, shows};
20
21/// The text an unscoped relation column renders for a row whose relation was not loaded.
22const UNLOADED: &str = "(unloaded)";
23
24/// A label source's type name, and whether a context's panel can load from it.
25type LabelSource = (&'static str, fn(&Cx) -> bool);
26
27/// Whether a request may not view a field of the related records a column shows.
28type Masked = Arc<dyn Fn(&Cx) -> bool + Send + Sync>;
29
30/// The text a relation column shows for a row, which a source's label reads in the request's
31/// context, or `None` when the row's relation was not loaded.
32type LoadedText<M> = Arc<dyn Fn(&Cx, &M) -> Option<String> + Send + Sync>;
33
34/// A to-one relation field to `T` a [`RelationColumn`] reads: `Deferred<T>`, or
35/// `Deferred<Option<T>>` for a nullable relation.
36///
37/// `T` is inferred from the field: `Deferred<X>` matches the first impl with `T = X` alone,
38/// since an `Option` is not a model, and the two impls cannot overlap, which would need
39/// `T = Option<T>`.
40pub trait ToOneRelation<T>: sealed::Sealed<T> {
41    /// The related record, `Some(None)` for a nullable relation holding none, or `None` when the
42    /// relation was not loaded.
43    #[doc(hidden)]
44    fn loaded(&self) -> Option<Option<&T>>;
45}
46
47mod sealed {
48    pub trait Sealed<T> {}
49
50    impl<T: toasty::schema::Model> Sealed<T> for toasty::Deferred<T> {}
51    impl<T: toasty::schema::Model> Sealed<T> for toasty::Deferred<Option<T>> {}
52}
53
54impl<T: toasty::schema::Model> ToOneRelation<T> for Deferred<T> {
55    fn loaded(&self) -> Option<Option<&T>> {
56        (!self.is_unloaded()).then(|| Some(self.get()))
57    }
58}
59
60impl<T: toasty::schema::Model> ToOneRelation<T> for Deferred<Option<T>> {
61    fn loaded(&self) -> Option<Option<&T>> {
62        (!self.is_unloaded()).then(|| self.get().as_ref())
63    }
64}
65
66/// A column showing the record of a `Deferred` `belongs_to` or `has_one` field as text, or the
67/// records of a `has_many` one ([`list`](Self::list)), which declares the field's include so every
68/// page that renders it loads them.
69///
70/// ```rust
71/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
72/// # struct Author { #[key] #[auto] id: uuid::Uuid, name: String }
73/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
74/// # struct Post {
75/// #     #[key] #[auto] id: uuid::Uuid,
76/// #     author_id: uuid::Uuid,
77/// #     #[belongs_to(key = author_id, references = id)]
78/// #     author: toasty::Deferred<Author>,
79/// # }
80/// # struct AuthorResource;
81/// # impl tablo_core::extend::OptionSource for AuthorResource {
82/// #     type Model = Author;
83/// #     fn scoped_query(_cx: &topcoat::context::Cx)
84/// #         -> topcoat::Result<toasty::stmt::Query<toasty::stmt::List<Author>>>
85/// #     {
86/// #         Ok(toasty::stmt::Query::all())
87/// #     }
88/// #     fn label(_cx: &topcoat::context::Cx, author: &Author) -> String {
89/// #         author.name.clone()
90/// #     }
91/// # }
92/// use tablo_core::{RelationColumn, lens, relation};
93///
94/// RelationColumn::new::<AuthorResource>(
95///     relation!(Post.author),
96///     lens!(Author.name),
97///     |_, a: &Author| a.name.clone(),
98/// );
99/// ```
100///
101/// The header and the column's name are the field's name, capitalized, until
102/// [`label`](Self::label) replaces both. The column neither searches nor sorts.
103///
104/// A column over a source `S` shows only the related records `S` shows the user: the ones its
105/// [`scoped_query`](OptionSource::scoped_query) returns when it [`lists`](OptionSource::lists)
106/// for the user, as a relationship choice over `S` offers them. A resource's `View` policy plays
107/// no part: a related record to hide belongs out of the scoped query, in its
108/// [`query`](crate::ResourceDef::query). A related record it hides, soft-deleted or another
109/// tenant's, renders empty, and so does every record of a row loaded around the table's or the
110/// [`Detail`](crate::Detail)'s loader, which checks them. The row keeps what the include loaded,
111/// so a policy reading the relation sees it whole. [`unscoped`](Self::unscoped) shows whatever
112/// the include loads.
113///
114/// A field [`field_access`](crate::ResourceDef::field_access) restricts shows to a user only
115/// where the user may view it, on every resource the panel mounts over its model: a request that
116/// may not view a field [`new`](Self::new) reads finds no such column. A record's
117/// [`label`](OptionSource::label) is its title, which the mount keeps clear of every restricted
118/// field, or its key, which no field access may hide.
119#[derive_where(Clone, Debug)]
120pub struct RelationColumn<M> {
121    relation: Declared<M>,
122    #[derive_where(skip(Debug))]
123    project: LoadedText<M>,
124}
125
126impl<M> RelationColumn<M>
127where
128    M: toasty::schema::Model + Send + Sync + 'static,
129{
130    /// Declare a column rendering `project` of the record `relation` loads, when `S` shows it.
131    /// `reads` names the fields of the record `project` reads, a [`lens!`](crate::lens!) or a
132    /// [`Reads`]: a request `S` hides one of them from finds no such column.
133    pub fn new<S>(
134        relation: RelationLens<M, impl ToOneRelation<S::Model> + 'static>,
135        reads: impl Into<Reads<S::Model>>,
136        project: impl Fn(&Cx, &S::Model) -> String + Send + Sync + 'static,
137    ) -> Self
138    where
139        S: OptionSource,
140    {
141        let read = relation.read;
142        let reads = reads.into();
143        Self {
144            relation: Declared::of(&relation, ColumnWidth::Grow)
145                .scoped::<S>(restrict_one::<M, S, _>(relation.read))
146                .masked(Arc::new(move |cx| reads.reads_any(&S::hidden_fields(cx)))),
147            project: Arc::new(move |cx, row| {
148                read(row).loaded().map(|target| {
149                    target
150                        .filter(|target| shows::<S>(cx, target))
151                        .map(|target| project(cx, target))
152                        .unwrap_or_default()
153                })
154            }),
155        }
156    }
157
158    /// Declare a column showing the record `relation` loads by `S`'s
159    /// [`label`](OptionSource::label), when `S` shows it: for a resource, the
160    /// [`record_title`](crate::ResourceDef::record_title) its detail page is titled with.
161    ///
162    /// ```rust
163    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
164    /// # struct Author { #[key] #[auto] id: uuid::Uuid, name: String }
165    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
166    /// # struct Post {
167    /// #     #[key] #[auto] id: uuid::Uuid,
168    /// #     author_id: uuid::Uuid,
169    /// #     #[belongs_to(key = author_id, references = id)]
170    /// #     author: toasty::Deferred<Author>,
171    /// # }
172    /// # struct AuthorResource;
173    /// # impl tablo_core::extend::OptionSource for AuthorResource {
174    /// #     type Model = Author;
175    /// #     fn scoped_query(_cx: &topcoat::context::Cx)
176    /// #         -> topcoat::Result<toasty::stmt::Query<toasty::stmt::List<Author>>>
177    /// #     {
178    /// #         Ok(toasty::stmt::Query::all())
179    /// #     }
180    /// #     fn label(_cx: &topcoat::context::Cx, author: &Author) -> String {
181    /// #         author.name.clone()
182    /// #     }
183    /// # }
184    /// use tablo_core::{RelationColumn, relation};
185    ///
186    /// RelationColumn::of::<AuthorResource>(relation!(Post.author));
187    /// ```
188    pub fn of<S>(relation: RelationLens<M, impl ToOneRelation<S::Model> + 'static>) -> Self
189    where
190        S: OptionSource,
191    {
192        let read = relation.read;
193        Self {
194            relation: Declared::of(&relation, ColumnWidth::Grow)
195                .scoped::<S>(restrict_one::<M, S, _>(relation.read)),
196            project: Arc::new(move |cx, row| {
197                read(row).loaded().map(|target| {
198                    target
199                        .filter(|target| shows::<S>(cx, target))
200                        .map(|target| S::label(cx, target))
201                        .unwrap_or_default()
202                })
203            }),
204        }
205    }
206
207    /// Declare a column listing the records a `has_many` `relation` loads that `S` shows, a
208    /// many-to-many `#[has_many(via = ..)]` one included, each by `S`'s
209    /// [`label`](OptionSource::label), joined by commas.
210    ///
211    /// ```rust
212    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
213    /// # struct Post {
214    /// #     #[key] #[auto] id: uuid::Uuid,
215    /// #     #[has_many]
216    /// #     taggings: toasty::Deferred<Vec<Tagging>>,
217    /// #     #[has_many(via = taggings.tag)]
218    /// #     tags: toasty::Deferred<Vec<Tag>>,
219    /// # }
220    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
221    /// # struct Tag { #[key] #[auto] id: uuid::Uuid, name: String }
222    /// # #[derive(Debug, Clone, toasty::Model)]
223    /// # struct Tagging {
224    /// #     #[key] #[auto] id: uuid::Uuid,
225    /// #     #[index] post_id: uuid::Uuid,
226    /// #     #[belongs_to(key = post_id, references = id)]
227    /// #     post: toasty::Deferred<Post>,
228    /// #     #[index] tag_id: uuid::Uuid,
229    /// #     #[belongs_to(key = tag_id, references = id)]
230    /// #     tag: toasty::Deferred<Tag>,
231    /// # }
232    /// # struct TagResource;
233    /// # impl tablo_core::extend::OptionSource for TagResource {
234    /// #     type Model = Tag;
235    /// #     fn scoped_query(_cx: &topcoat::context::Cx)
236    /// #         -> topcoat::Result<toasty::stmt::Query<toasty::stmt::List<Tag>>>
237    /// #     {
238    /// #         Ok(toasty::stmt::Query::all())
239    /// #     }
240    /// #     fn label(_cx: &topcoat::context::Cx, tag: &Tag) -> String {
241    /// #         tag.name.clone()
242    /// #     }
243    /// #     fn lists(_cx: &topcoat::context::Cx) -> bool {
244    /// #         true
245    /// #     }
246    /// # }
247    /// use tablo_core::{RelationColumn, relation};
248    ///
249    /// RelationColumn::list::<TagResource>(relation!(Post.tags));
250    /// ```
251    pub fn list<S>(relation: RelationLens<M, Deferred<Vec<S::Model>>>) -> Self
252    where
253        S: OptionSource,
254    {
255        let read = relation.read;
256        Self {
257            relation: Declared::of(&relation, ColumnWidth::Grow)
258                .scoped::<S>(restrict_many::<M, S>(relation.read)),
259            project: Arc::new(move |cx, row| {
260                let records = read(row);
261                (!records.is_unloaded()).then(|| {
262                    records
263                        .get()
264                        .iter()
265                        .filter(|record| shows::<S>(cx, record))
266                        .map(|record| S::label(cx, record))
267                        .collect::<Vec<_>>()
268                        .join(", ")
269                })
270            }),
271        }
272    }
273
274    /// Declare a column rendering `project` of whatever record `relation` loads, under no
275    /// resource's query, policy or field access: for a related model no resource administers. A
276    /// panel mounting a resource that restricts a field of the related model refuses it. A row
277    /// loaded without the column's include renders `"(unloaded)"` and fails a debug assertion.
278    pub fn unscoped<T>(
279        relation: RelationLens<M, impl ToOneRelation<T> + 'static>,
280        project: impl Fn(&Cx, &T) -> String + Send + Sync + 'static,
281    ) -> Self {
282        let read = relation.read;
283        Self {
284            relation: Declared::of(&relation, ColumnWidth::Grow),
285            project: Arc::new(move |cx, row| {
286                read(row)
287                    .loaded()
288                    .map(|target| target.map(|target| project(cx, target)).unwrap_or_default())
289            }),
290        }
291    }
292}
293
294impl<M> RelationColumn<M> {
295    /// The row's text, or `None` when its relation was not loaded.
296    fn loaded_text(&self, cx: &Cx, row: &M) -> Option<String> {
297        (self.project)(cx, row)
298    }
299}
300
301/// What both relation-field columns declare: the name and label, the include and the width.
302#[derive_where(Clone, Debug)]
303struct Declared<M> {
304    name: String,
305    /// The declared label, over the field's.
306    label: Option<crate::Text>,
307    field_label: crate::Text,
308    misdeclared: Option<DeclarationErrorKind>,
309    includes: Includes<M>,
310    reads: crate::lens::Reads<M>,
311    width: ColumnWidth,
312    toggle: ColumnToggle,
313    /// The source that decides which related records show, and whether a context's panel can
314    /// load from it.
315    source: Option<LabelSource>,
316    /// Drops the related records the source does not show; `None` for an unscoped column.
317    #[derive_where(skip(Debug))]
318    restrict: Option<Restrict<M>>,
319    /// What the column shows of the related records, which a panel checks at mount.
320    related: Related,
321    /// Whether a request may not view a field the column shows; `None` for one showing only a
322    /// record's label or count.
323    #[derive_where(skip(Debug))]
324    masked: Option<Masked>,
325}
326
327impl<M> Declared<M> {
328    fn of<R>(relation: &RelationLens<M, R>, width: ColumnWidth) -> Self {
329        let (name, field_label, misdeclared) = match relation.field() {
330            Ok(name) => (name.to_string(), crate::Text::field(name), None),
331            Err(error) => (String::new(), crate::Text::from(""), Some(error)),
332        };
333        Self {
334            name,
335            label: None,
336            field_label,
337            misdeclared,
338            includes: relation.includes().clone(),
339            reads: relation.reads(),
340            width,
341            toggle: ColumnToggle::Fixed,
342            source: None,
343            restrict: None,
344            related: Related::Unmasked,
345            masked: None,
346        }
347    }
348
349    /// Show only the related records `S` shows, which `restrict` keeps, by their label or count
350    /// until [`masked`](Self::masked) says what else shows.
351    fn scoped<S: OptionSource>(self, restrict: Restrict<M>) -> Self {
352        Self {
353            source: Some((std::any::type_name::<S>(), S::available)),
354            related: Related::Source(std::any::TypeId::of::<S>()),
355            ..self.restricted(restrict)
356        }
357    }
358
359    /// Run `restrict` once a page's rows load, before any cell renders.
360    pub(super) fn restricted(self, restrict: Restrict<M>) -> Self {
361        Self {
362            restrict: Some(restrict),
363            ..self
364        }
365    }
366
367    /// Load nothing with the rows: the column queries what it shows itself.
368    pub(super) fn without_include(self) -> Self {
369        Self {
370            includes: Includes::new(),
371            ..self
372        }
373    }
374
375    /// Show the fields of the related records `masked` hides from a request it refuses.
376    fn masked(self, masked: Masked) -> Self {
377        Self {
378            masked: Some(masked),
379            ..self
380        }
381    }
382
383    /// Show no field of the related records.
384    fn fieldless(self) -> Self {
385        Self {
386            related: Related::None,
387            ..self
388        }
389    }
390
391    fn label(&self) -> crate::Text {
392        self.label
393            .clone()
394            .unwrap_or_else(|| self.field_label.clone())
395    }
396
397    fn relabel(&mut self, label: crate::Text) {
398        self.name = label.key();
399        self.label = Some(label);
400    }
401
402    /// The text of a row's loaded relation. A column that restricts renders empty when it has
403    /// nothing for its row, which is how a required related record the source hides reads, and a
404    /// count its loader did not run. An unscoped one renders the unloaded marker, since a loader
405    /// skipped the include it declares.
406    fn text(&self, loaded: Option<String>) -> String {
407        if self.restrict.is_some() {
408            return loaded.unwrap_or_default();
409        }
410        debug_assert!(
411            loaded.is_some(),
412            "the `{}` column declares its include, but its row was loaded without it",
413            self.name
414        );
415        loaded.unwrap_or_else(|| UNLOADED.to_string())
416    }
417}
418
419mod shared;
420
421#[cfg(test)]
422mod tests;