tablo-core 0.8.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
//! Relation tables: a record page's related rows through the related resource's own list table.

use std::{any::TypeId, sync::Arc};

use toasty::stmt::{Expr, IntoExpr, List, Path};
use topcoat::{Result, context::Cx};

use super::{
    ErasedInput, InputResult, InputSpec, Resource, Trashed, can, scoped_query, scoped_query_in,
};
use crate::{
    BoxFuture,
    form::{FieldError, FormScalar, FormValues},
    policy::Ability,
    schema::{Field, Schema},
    toasty_compat::{
        join::{JoinTable, linked_to},
        model::{self, AppSchema, ModelPath},
        pk,
    },
};

/// One relation of a parent resource's records.
///
/// Declared by [`ResourceDef::relation`](super::ResourceDef::relation); the related resource
/// must be registered on the same panel, which keys the relation by its slug:
///
/// ```rust
/// # use tablo_core::{NoForm, Relation, Resource, ResourceDef};
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Post {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     #[has_many]
/// #     comments: toasty::Deferred<Vec<Comment>>,
/// # }
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Comment {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     #[index]
/// #     post_id: uuid::Uuid,
/// #     #[belongs_to(key = post_id, references = id)]
/// #     post: toasty::Deferred<Post>,
/// # }
/// # struct PostResource;
/// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
/// # struct CommentResource;
/// # impl Resource for CommentResource { type Model = Comment; type Form = NoForm<Comment>; }
/// let def: ResourceDef<PostResource> =
///     ResourceDef::new().relation(Relation::has_many::<CommentResource>(Comment::fields().post_id()));
/// ```
///
/// The table is the related resource's own list table, its columns, search, sort, filters and
/// pager, over its tenant-scoped query narrowed to the record, titled with its plural label or
/// [`label`](Self::label):
///
/// - its policy applies as on its own list: no section renders when it refuses `ViewAny`, or when
///   the resource is tenant-scoped and the request has no tenant, and each row keeps only the
///   actions its record allows;
/// - a [`has_many`](Self::has_many) table carries the related resource's View, Edit, Delete and
///   custom actions and its bulk bar, and a create button when the related resource has a form and
///   its policy allows `Create`. The button opens the create page with the owner preselected, as in
///   `/admin/comments/-/create?post_id=…`: a default for a relationship choice only, validated like
///   any other create;
/// - a [`belongs_to_many`](Self::belongs_to_many) table keeps View, Edit and Delete, and offers no
///   custom action and no create button, since a record created there would link nothing;
/// - writes started from the table carry `?return=` and land back on the page, which the panel
///   follows only to a path under its own prefix;
/// - its URL parameters take the related resource's slug as a prefix, as in `?comments.q=`, so
///   several tables share one page, and sorting, searching, filtering and paging update it in
///   place. On the edit page that keeps the fields the user edited, but loses repeater rows added
///   and options fetched since the page loaded. A refused save renders no related table.
///
/// Mounting refuses a relation to a resource the panel does not register, and two relations of
/// one resource to the same related resource.
pub struct Relation<P> {
    pub(crate) child: TypeId,
    pub(crate) child_name: &'static str,
    pub(crate) label: Option<crate::Text>,
    pub(crate) kind: RelationKind<P>,
    bind: BindFn<P>,
    /// Why the relation's field binds nothing, when it does not.
    pub(crate) misdeclared: Option<crate::DeclarationErrorKind>,
}

/// How a relation's child rows belong to the owner.
pub(crate) enum RelationKind<P> {
    /// Each child row holds the owner's key in this column, which a create from the table seeds.
    HasMany { foreign_key: String },
    /// The owner links child records through a join model, which the table attaches and detaches.
    ManyToMany(Links<P>),
}

/// An owner's rows filter on the child.
type BindFn<P> = Arc<dyn Fn(&P) -> (Expr<bool>, String) + Send + Sync>;

/// A many-to-many relation's writes: link the child record a key names to an owner, or unlink
/// the ones keys name.
pub(crate) struct Links<P> {
    /// The owner's `#[has_many(via = ..)]` field.
    pub(crate) field: String,
    /// The attach dialog's input: a choice of one child record.
    pub(crate) input: InputSpec,
    /// Links the record the key names, which the input's re-check proved a child record in
    /// scope that the user may view; linking a linked record changes nothing. Answers the key as
    /// the child's URLs spell it.
    pub(crate) attach: LinkFn<P, String>,
    /// Unlinks the records the keys name: 404 unless each is linked and in scope, 403 unless the
    /// user may view each. Answers the keys as the children's URLs spell them.
    pub(crate) detach: LinkFn<P, Vec<String>>,
}

/// A write of an owner's links, given what names the related records; answers those names as
/// the related resource's URLs spell them.
type LinkFn<P, K> = Arc<
    dyn for<'a> Fn(&'a Cx, &'a P, K, &'a mut dyn toasty::Executor) -> BoxFuture<'a, Result<K>>
        + Send
        + Sync,
>;

/// The input key the attach dialog's choice posts.
const ATTACH_KEY: &str = "record";

/// A foreign-key column type referencing a primary key of type `K`: `K` itself, or `Option<K>`
/// for an optional reference. Sealed: these are the only two.
pub trait ForeignKey<K>:
    sealed::Sealed<K> + IntoExpr<Self> + FormScalar + Send + Sync + 'static
{
}

impl<K> ForeignKey<K> for K where K: IntoExpr<K> + FormScalar + Send + Sync + 'static {}

impl<K> ForeignKey<K> for Option<K> where
    Option<K>: IntoExpr<Self> + FormScalar + Send + Sync + 'static
{
}

mod sealed {
    pub trait Sealed<K> {}

    impl<K> Sealed<K> for K {}

    impl<K> Sealed<K> for Option<K> {}
}

impl<P> Relation<P>
where
    P: toasty::schema::Model + IntoExpr<P> + 'static,
{
    /// Declare a `has_many` child resource whose `foreign_key` holds the owner's primary key, a
    /// single column.
    ///
    /// ```rust
    /// # use tablo_core::{NoForm, Relation, Resource, ResourceDef};
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct Post {
    /// #     #[key] #[auto] id: uuid::Uuid,
    /// #     #[has_many]
    /// #     comments: toasty::Deferred<Vec<Comment>>,
    /// # }
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct Comment {
    /// #     #[key] #[auto] id: uuid::Uuid,
    /// #     #[index]
    /// #     post_id: uuid::Uuid,
    /// #     #[belongs_to(key = post_id, references = id)]
    /// #     post: toasty::Deferred<Post>,
    /// # }
    /// # struct PostResource;
    /// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
    /// # struct CommentResource;
    /// # impl Resource for CommentResource { type Model = Comment; type Form = NoForm<Comment>; }
    /// let comments: Relation<Post> = Relation::has_many::<CommentResource>(Comment::fields().post_id());
    /// ```
    pub fn has_many<C>(foreign_key: Path<C::Model, impl ForeignKey<P::PrimaryKey>>) -> Self
    where
        C: Resource,
    {
        Self::bound_by::<C, _>(foreign_key)
    }

    fn bound_by<C, T>(foreign_key: Path<C::Model, T>) -> Self
    where
        C: Resource,
        T: ForeignKey<P::PrimaryKey>,
    {
        // A foreign key is one column of the child: it binds against the child's model alone.
        let (column, misdeclared) = match model::field::<C::Model>(&ModelPath::of(&foreign_key)) {
            Ok(field) => (field.name, None),
            Err(error) => (String::new(), Some(error)),
        };
        Self {
            child: TypeId::of::<C>(),
            child_name: std::any::type_name::<C>(),
            label: None,
            kind: RelationKind::HasMany {
                foreign_key: column,
            },
            misdeclared,
            bind: Arc::new(move |owner| {
                let scope = foreign_key.clone().eq(pk::pk_expr::<P, T>(owner));
                (scope, pk::pk_text(owner))
            }),
        }
    }

    /// Declare a many-to-many child resource whose records the owner links through `via`, its
    /// `#[has_many(via = joins.target)]` field: the owner's linked records, which the table
    /// attaches and detaches as join rows.
    ///
    /// ```rust
    /// # use tablo_core::{NoForm, Relation, Resource, ResourceDef};
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct Post {
    /// #     #[key] #[auto] id: uuid::Uuid,
    /// #     #[has_many]
    /// #     taggings: toasty::Deferred<Vec<Tagging>>,
    /// #     #[has_many(via = taggings.tag)]
    /// #     tags: toasty::Deferred<Vec<Tag>>,
    /// # }
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct Tag { #[key] #[auto] id: uuid::Uuid, name: String }
    /// # #[derive(Debug, Clone, toasty::Model)]
    /// # struct Tagging {
    /// #     #[key] #[auto] id: uuid::Uuid,
    /// #     #[index] post_id: uuid::Uuid,
    /// #     #[belongs_to(key = post_id, references = id)]
    /// #     post: toasty::Deferred<Post>,
    /// #     #[index] tag_id: uuid::Uuid,
    /// #     #[belongs_to(key = tag_id, references = id)]
    /// #     tag: toasty::Deferred<Tag>,
    /// # }
    /// # struct TagResource;
    /// # impl Resource for TagResource { type Model = Tag; type Form = NoForm<Tag>; }
    /// let tags: Relation<Post> = Relation::belongs_to_many::<TagResource>(Post::fields().tags());
    /// ```
    ///
    /// The section's header carries Attach, whose dialog asks for one record through a
    /// searchable choice offered as a relationship's options are; attaching a linked record
    /// changes nothing. Each row and the bulk bar carry Detach, which deletes the join rows and
    /// leaves the records. Both post under the owner's record:
    /// `{list}/{key}/-/relations/{slug}/-/actions/attach`, `…/-/actions/detach` with the
    /// selection's `ids`, and `…/{related}/-/actions/detach` for one row. The owner's hooks
    /// receive [`Change::Attach`](crate::Change::Attach) or
    /// [`Change::Detach`](crate::Change::Detach).
    ///
    /// Attaching and detaching ask the owner's policy for `Update`, as editing it does: no button
    /// renders without it, and the routes answer 403. A record the related resource's policy
    /// refuses `View` is neither offered nor detached. Mounting refuses a join model a link
    /// cannot write.
    pub fn belongs_to_many<C>(via: impl Into<Path<P, List<C::Model>>>) -> Self
    where
        C: Resource,
        P: Send + Sync,
    {
        let via: Path<P, List<C::Model>> = via.into();
        let (field, misdeclared) = match model::field::<P>(&ModelPath::of(&via)) {
            Ok(field) => (field.name, None),
            Err(error) => (String::new(), Some(error)),
        };
        let attach_via = via.clone();
        let attach_field = field.clone();
        let detach_via = via.clone();
        let detach_field = field.clone();
        Self {
            child: TypeId::of::<C>(),
            child_name: std::any::type_name::<C>(),
            label: None,
            kind: RelationKind::ManyToMany(Links {
                field,
                input: InputSpec {
                    schema: attach_schema::<C>,
                    takes_input: true,
                    parse: parse_attach,
                },
                attach: Arc::new(move |cx, owner, key, ex| {
                    let (via, field) = (attach_via.clone(), attach_field.clone());
                    Box::pin(async move { attach::<P, C>(cx, owner, via, &field, key, ex).await })
                }),
                detach: Arc::new(move |cx, owner, keys, ex| {
                    let (via, field) = (detach_via.clone(), detach_field.clone());
                    Box::pin(async move { detach::<P, C>(cx, owner, via, &field, keys, ex).await })
                }),
            }),
            misdeclared,
            bind: Arc::new(move |owner| (linked_to(owner, via.clone()), pk::pk_text(owner))),
        }
    }
}

/// The attach dialog's input: one searchable choice of `C`'s records.
fn attach_schema<C: Resource>() -> Schema {
    Schema::new(
        Field::choice_input(ATTACH_KEY)
            .label(crate::Text::model::<C::Model>())
            .relationship::<C>()
            .searchable(),
    )
}

/// The key the attach dialog's choice posts: the schema's check proved it one of the choice's
/// records.
fn parse_attach(_cx: &Cx, values: &FormValues) -> InputResult {
    match values.text(ATTACH_KEY).map(str::trim) {
        Some(key) if !key.is_empty() => Ok(Box::new(key.to_string()) as ErasedInput),
        _ => Err(vec![FieldError::required(ATTACH_KEY)]),
    }
}

/// The join model behind `owner`'s `field`.
fn join_table<P: toasty::schema::Model>(cx: &Cx, field: &str) -> Result<JoinTable> {
    let schema = AppSchema::of(cx).ok_or_else(|| {
        crate::error::declaration(crate::DeclarationErrorKind::MissingDb.to_string())
    })?;
    JoinTable::of::<P>(&schema, field).map_err(|fault| {
        crate::error::declaration(
            crate::DeclarationErrorKind::ManyToMany {
                field: field.to_string(),
                fault,
            }
            .to_string(),
        )
    })
}

/// Links `owner` to the record `key` names, unless they are linked already.
async fn attach<P, C>(
    cx: &Cx,
    owner: &P,
    via: Path<P, List<C::Model>>,
    field: &str,
    key: String,
    ex: &mut dyn toasty::Executor,
) -> Result<String>
where
    P: toasty::schema::Model + IntoExpr<P>,
    C: Resource,
{
    let join = join_table::<P>(cx, field)?;
    let (Some(key), Some(record)) = (
        pk::canonical_key::<C::Model>(&key),
        pk::pk_eq_expr::<C::Model>(&key),
    ) else {
        return Err(topcoat::router::error::not_found().into());
    };
    let linked = scoped_query::<C>(cx)?
        .filter(record)
        .filter(linked_to(owner, via))
        .first()
        .exec(&mut *ex)
        .await
        .map_err(crate::error::unavailable)?;
    if linked.is_none() {
        join.link(owner, std::slice::from_ref(&key), ex)
            .await
            .map_err(|error| -> topcoat::Error { error.into() })?;
    }
    Ok(key)
}

/// Unlinks `owner` from the records `keys` names.
async fn detach<P, C>(
    cx: &Cx,
    owner: &P,
    via: Path<P, List<C::Model>>,
    field: &str,
    keys: Vec<String>,
    ex: &mut dyn toasty::Executor,
) -> Result<Vec<String>>
where
    P: toasty::schema::Model + IntoExpr<P>,
    C: Resource,
{
    let join = join_table::<P>(cx, field)?;
    let ids: Vec<&str> = keys.iter().map(String::as_str).collect();
    let Some(records) = pk::pk_in_expr::<C::Model>(&ids) else {
        return Err(topcoat::router::error::not_found().into());
    };
    // A trashed record stays linked, and the relation table offers to unlink it.
    let linked = scoped_query_in::<C>(cx, Trashed::With)?
        .filter(records)
        .filter(linked_to(owner, via))
        .exec(&mut *ex)
        .await
        .map_err(crate::error::unavailable)?;
    if linked.len() != keys.len() {
        return Err(topcoat::router::error::not_found().into());
    }
    // A record the user cannot view cannot be unlinked by guessing its key.
    if linked
        .iter()
        .any(|record| !can::<C>(cx, Ability::View(record)))
    {
        return Err(topcoat::router::error::forbidden().into());
    }
    join.unlink(owner, &keys, ex)
        .await
        .map_err(|error| -> topcoat::Error { error.into() })?;
    Ok(linked.iter().map(pk::pk_text).collect())
}

impl<P> Relation<P> {
    /// Titles the section `label` instead of the related resource's plural label.
    #[must_use]
    pub fn label(mut self, label: impl Into<crate::Text>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// The child's rows that belong to `owner`, and the owner's primary key as text.
    pub(crate) fn bind(&self, owner: &P) -> (Expr<bool>, String) {
        (self.bind)(owner)
    }
}

impl<P> Relation<P> {
    /// The relation's join-row writes, when it is a many-to-many one.
    pub(crate) fn links(&self) -> Option<&Links<P>> {
        match &self.kind {
            RelationKind::ManyToMany(links) => Some(links),
            RelationKind::HasMany { .. } => None,
        }
    }
}

impl<P> std::fmt::Debug for Relation<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug = f.debug_struct("Relation");
        debug
            .field("child", &self.child_name)
            .field("label", &self.label);
        match &self.kind {
            RelationKind::HasMany { foreign_key } => debug.field("foreign_key", foreign_key),
            RelationKind::ManyToMany(links) => debug.field("via", &links.field),
        };
        debug.finish_non_exhaustive()
    }
}