tablo_core/resource/relation.rs
1//! Relation tables: a record page's related rows through the related resource's own list table.
2
3use std::{any::TypeId, sync::Arc};
4
5use toasty::stmt::{Expr, IntoExpr, List, Path};
6use topcoat::{Result, context::Cx};
7
8use super::{
9 ErasedInput, InputResult, InputSpec, Resource, Trashed, can, scoped_query, scoped_query_in,
10};
11use crate::{
12 BoxFuture,
13 toasty_compat::{
14 join::linked_to,
15 model::{self, ModelPath},
16 pk,
17 },
18};
19
20mod links;
21
22use links::{attach, attach_schema, detach, parse_attach};
23
24/// One relation of a parent resource's records.
25///
26/// Declared by [`ResourceDef::relation`](super::ResourceDef::relation); the related resource
27/// must be registered on the same panel, which keys the relation by its slug:
28///
29/// ```rust
30/// # use tablo_core::{NoForm, Relation, Resource, ResourceDef, lens};
31/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
32/// # struct Post {
33/// # #[key] #[auto] id: uuid::Uuid,
34/// # #[has_many]
35/// # comments: toasty::Deferred<Vec<Comment>>,
36/// # }
37/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
38/// # struct Comment {
39/// # #[key] #[auto] id: uuid::Uuid,
40/// # #[index]
41/// # post_id: uuid::Uuid,
42/// # #[belongs_to(key = post_id, references = id)]
43/// # post: toasty::Deferred<Post>,
44/// # }
45/// # struct PostResource;
46/// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
47/// # struct CommentResource;
48/// # impl Resource for CommentResource { type Model = Comment; type Form = NoForm<Comment>; }
49/// let def: ResourceDef<PostResource> =
50/// ResourceDef::new().relation(Relation::has_many::<CommentResource>(lens!(Comment.post_id)));
51/// ```
52///
53/// The table is the related resource's own list table, its columns, search, sort, filters and
54/// pager, over its tenant-scoped query narrowed to the record, titled with its plural label or
55/// [`label`](Self::label):
56///
57/// - its policy applies as on its own list: no section renders when it refuses `ViewAny`, or when
58/// the resource is tenant-scoped and the request has no tenant, and each row keeps only the
59/// actions its record allows;
60/// - a [`has_many`](Self::has_many) table carries the related resource's View, Edit, Delete and
61/// custom actions and its bulk bar, and a create button when the related resource has a form and
62/// its policy allows `Create`. The button opens the create page with the owner preselected, as in
63/// `/admin/comments/-/create?post_id=…`: a default for a relationship choice only, validated like
64/// any other create;
65/// - a [`belongs_to_many`](Self::belongs_to_many) table keeps View, Edit and Delete, and offers no
66/// custom action and no create button, since a record created there would link nothing;
67/// - a [`through`](Self::through) table carries the related resource's View, Edit, Delete and
68/// custom actions and its bulk bar, and no create button, since no column of a record created
69/// there would hold the owner;
70/// - writes started from the table carry `?return=` and land back on the page, which the panel
71/// follows only to a path under its own prefix;
72/// - its URL parameters take the related resource's slug as a prefix, as in `?comments.q=`, so
73/// several tables share one page, and sorting, searching, filtering and paging update it in
74/// place. On the edit page that keeps the fields the user edited, but loses repeater rows added
75/// and options fetched since the page loaded. A refused save renders no related table.
76///
77/// A [`has_one`](Self::has_one) relation renders no table: the related resource's form edits the
78/// record's one child inside the record's own form.
79///
80/// [`tab`](Self::tab) moves the table off the detail and edit pages onto a page of its own.
81///
82/// Mounting refuses a relation to a resource the panel does not register, and two relations of
83/// one resource to the same related resource.
84pub struct Relation<P> {
85 pub(crate) child: TypeId,
86 pub(crate) child_name: &'static str,
87 pub(crate) label: Option<crate::Text>,
88 /// Whether [`Self::tab`] serves the table on a page of its own.
89 pub(crate) tab: bool,
90 pub(crate) kind: RelationKind<P>,
91 bind: BindFn<P>,
92 /// Why the relation's field binds nothing, when it does not.
93 pub(crate) misdeclared: Option<crate::DeclarationErrorKind>,
94}
95
96/// How a relation's child rows belong to the owner.
97pub(crate) enum RelationKind<P> {
98 /// Each child row holds the owner's key in this column, which a create from the table seeds.
99 HasMany { foreign_key: String },
100 /// The owner's one child row holds its key in this column, which the related form fills.
101 HasOne { foreign_key: String },
102 /// The owner links child records through a join model, which the table attaches and detaches.
103 ManyToMany(Links<P>),
104 /// The owner reaches child records through other relations, which the table only reads; the
105 /// owner's field.
106 Through { field: String },
107}
108
109/// An owner's rows filter on the child.
110type BindFn<P> = Arc<dyn Fn(&P) -> (Expr<bool>, String) + Send + Sync>;
111
112/// A many-to-many relation's writes: link the child record a key names to an owner, or unlink
113/// the ones keys name.
114pub(crate) struct Links<P> {
115 /// The owner's `#[has_many(via = ..)]` field.
116 pub(crate) field: String,
117 /// The attach dialog's input: a choice of one child record.
118 pub(crate) input: InputSpec,
119 /// Links the record the key names, which the input's re-check proved a child record in
120 /// scope; linking a linked record changes nothing. Answers the key as
121 /// the child's URLs spell it.
122 pub(crate) attach: LinkFn<P, String>,
123 /// Unlinks the records the keys name: 404 unless each is linked and in scope, 403 unless the
124 /// user may view each. Answers the keys as the children's URLs spell them.
125 pub(crate) detach: LinkFn<P, Vec<String>>,
126}
127
128/// A write of an owner's links, given what names the related records; answers those names as
129/// the related resource's URLs spell them.
130type LinkFn<P, K> = Arc<
131 dyn for<'a> Fn(&'a Cx, &'a P, K, &'a mut dyn toasty::Executor) -> BoxFuture<'a, Result<K>>
132 + Send
133 + Sync,
134>;
135
136/// The input key the attach dialog's choice posts.
137const ATTACH_KEY: &str = "record";
138
139/// A field of the child model `M` holding the owner's primary key, of type `K`: a
140/// [`lens!`](crate::lens!) or a field path over a `K` column, or an `Option<K>` one for an
141/// optional reference. Sealed.
142pub trait ForeignKey<M, K>: sealed::Field<M, K> {}
143
144impl<M, K, F: sealed::Field<M, K>> ForeignKey<M, K> for F {}
145
146mod sealed {
147 use toasty::stmt::{IntoExpr, Path};
148
149 use crate::{Lens, form::FormScalar};
150
151 pub trait Field<M, K> {
152 type Column: Column<K>;
153
154 fn into_path(self) -> Path<M, Self::Column>;
155 }
156
157 impl<M, K, T: Column<K>> Field<M, K> for Path<M, T> {
158 type Column = T;
159
160 fn into_path(self) -> Path<M, T> {
161 self
162 }
163 }
164
165 impl<M, K, V, T: Column<K>> Field<M, K> for Lens<M, V, T> {
166 type Column = T;
167
168 fn into_path(self) -> Path<M, T> {
169 self.into()
170 }
171 }
172
173 /// A column type holding a key of type `K`: `K` itself, or `Option<K>`.
174 pub trait Column<K>: IntoExpr<Self> + FormScalar + Send + Sync + 'static {}
175
176 impl<K> Column<K> for K where K: IntoExpr<K> + FormScalar + Send + Sync + 'static {}
177
178 impl<K> Column<K> for Option<K> where Option<K>: IntoExpr<Self> + FormScalar + Send + Sync + 'static {}
179}
180
181impl<P> Relation<P>
182where
183 P: toasty::schema::Model + IntoExpr<P> + 'static,
184{
185 /// Declare a `has_many` child resource whose `foreign_key` holds the owner's primary key, a
186 /// single column.
187 ///
188 /// ```rust
189 /// # use tablo_core::{NoForm, Relation, Resource, ResourceDef, lens};
190 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
191 /// # struct Post {
192 /// # #[key] #[auto] id: uuid::Uuid,
193 /// # #[has_many]
194 /// # comments: toasty::Deferred<Vec<Comment>>,
195 /// # }
196 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
197 /// # struct Comment {
198 /// # #[key] #[auto] id: uuid::Uuid,
199 /// # #[index]
200 /// # post_id: uuid::Uuid,
201 /// # #[belongs_to(key = post_id, references = id)]
202 /// # post: toasty::Deferred<Post>,
203 /// # }
204 /// # struct PostResource;
205 /// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
206 /// # struct CommentResource;
207 /// # impl Resource for CommentResource { type Model = Comment; type Form = NoForm<Comment>; }
208 /// let comments: Relation<Post> = Relation::has_many::<CommentResource>(lens!(Comment.post_id));
209 /// ```
210 pub fn has_many<C>(foreign_key: impl ForeignKey<C::Model, P::PrimaryKey>) -> Self
211 where
212 C: Resource,
213 {
214 Self::bound_by::<C, _>(foreign_key)
215 }
216
217 /// Declare a `has_one` child resource whose `foreign_key` holds the owner's primary key, a
218 /// single column: the record's one child, edited by the child resource's own form inside the
219 /// owner's create and edit forms rather than by a table.
220 ///
221 /// ```rust
222 /// # use tablo_core::{Relation, Resource, ResourceDef, lens};
223 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel, tablo_core::ModelForm)]
224 /// # struct User {
225 /// # #[key] #[auto] id: uuid::Uuid,
226 /// # name: String,
227 /// # #[has_one]
228 /// # profile: toasty::Deferred<Option<Profile>>,
229 /// # }
230 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel, tablo_core::ModelForm)]
231 /// # struct Profile {
232 /// # #[key] #[auto] id: uuid::Uuid,
233 /// # #[unique]
234 /// # #[form(relationship = UserResource)]
235 /// # user_id: uuid::Uuid,
236 /// # #[belongs_to(key = user_id, references = id)]
237 /// # user: toasty::Deferred<User>,
238 /// # bio: String,
239 /// # }
240 /// # struct UserResource;
241 /// # impl Resource for UserResource { type Model = User; type Form = UserForm; }
242 /// # struct ProfileResource;
243 /// # impl Resource for ProfileResource { type Model = Profile; type Form = ProfileForm; }
244 /// let profile: Relation<User> = Relation::has_one::<ProfileResource>(lens!(Profile.user_id));
245 /// ```
246 ///
247 /// The related resource's form renders as a section of the owner's form, titled with its
248 /// label or [`label`](Self::label), each control posting under the child's slug, as in
249 /// `profiles.bio`; the foreign key renders no control, since the owner's key fills it. Saving
250 /// the owner writes the child in the same transaction, after the owner: a create creates it,
251 /// and an edit updates the record's child or creates one when it has none. Either way the
252 /// child goes through its own resource as on its own pages: its policy, tenancy, field access,
253 /// control rules, unique probe, `validate_record`, record fn and commit hooks. A refusal from
254 /// either form rolls both back and renders both with their errors. The owner's hooks receive
255 /// the owner's change, the child's its own.
256 ///
257 /// The section renders only while the request may write the child: `Create` on the related
258 /// resource, or `View` and `Update` on the record's child, with the foreign key neither hidden
259 /// nor locked by field access. A record with more than one child, or one the related
260 /// resource's query leaves out, renders none. A submission posting under the prefix with no
261 /// section is refused, and one posting nothing under it, such as an editable cell's or an
262 /// import row's, leaves the child alone. The relation renders no table.
263 ///
264 /// Mounting refuses a related resource with no form, one whose form binds no control for
265 /// the foreign key, a soft-deleting one, one whose form holds a control that needs its own
266 /// keys or routes (a file field, a repeater, an embedded value, a searchable or dependent
267 /// choice), an owner with no form, and an owner form key the prefix would shadow.
268 pub fn has_one<C>(foreign_key: impl ForeignKey<C::Model, P::PrimaryKey>) -> Self
269 where
270 C: Resource,
271 {
272 let mut relation = Self::bound_by::<C, _>(foreign_key);
273 if let RelationKind::HasMany { foreign_key } = relation.kind {
274 relation.kind = RelationKind::HasOne { foreign_key };
275 }
276 relation
277 }
278
279 fn bound_by<C, F>(foreign_key: F) -> Self
280 where
281 C: Resource,
282 F: ForeignKey<C::Model, P::PrimaryKey>,
283 {
284 let foreign_key = foreign_key.into_path();
285 // A foreign key is one column of the child: it binds against the child's model alone.
286 let (column, misdeclared) = match model::field::<C::Model>(&ModelPath::of(&foreign_key)) {
287 Ok(field) => (field.name, None),
288 Err(error) => (String::new(), Some(error)),
289 };
290 Self {
291 child: TypeId::of::<C>(),
292 child_name: std::any::type_name::<C>(),
293 label: None,
294 tab: false,
295 kind: RelationKind::HasMany {
296 foreign_key: column,
297 },
298 misdeclared,
299 bind: Arc::new(move |owner| {
300 let scope = foreign_key.clone().eq(pk::pk_expr::<P, F::Column>(owner));
301 (scope, pk::pk_text(owner))
302 }),
303 }
304 }
305
306 /// Declare a child resource whose records the owner reaches through `via`, its
307 /// `#[has_many(via = ..)]` field: the records at the end of a path of relations, such as a
308 /// customer's payments through its orders, which the table reads but never links.
309 ///
310 /// ```rust
311 /// # use tablo_core::{NoForm, Relation, Resource};
312 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
313 /// # struct Customer {
314 /// # #[key] #[auto] id: uuid::Uuid,
315 /// # #[has_many]
316 /// # orders: toasty::Deferred<Vec<Order>>,
317 /// # #[has_many(via = orders.payments)]
318 /// # payments: toasty::Deferred<Vec<Payment>>,
319 /// # }
320 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
321 /// # struct Order {
322 /// # #[key] #[auto] id: uuid::Uuid,
323 /// # #[index] customer_id: uuid::Uuid,
324 /// # #[belongs_to(key = customer_id, references = id)]
325 /// # customer: toasty::Deferred<Customer>,
326 /// # #[has_many]
327 /// # payments: toasty::Deferred<Vec<Payment>>,
328 /// # }
329 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
330 /// # struct Payment {
331 /// # #[key] #[auto] id: uuid::Uuid,
332 /// # #[index] order_id: uuid::Uuid,
333 /// # #[belongs_to(key = order_id, references = id)]
334 /// # order: toasty::Deferred<Order>,
335 /// # }
336 /// # struct PaymentResource;
337 /// # impl Resource for PaymentResource { type Model = Payment; type Form = NoForm<Payment>; }
338 /// let payments: Relation<Customer> =
339 /// Relation::through::<PaymentResource>(Customer::fields().payments());
340 /// ```
341 ///
342 /// The table lists each record the path reaches once, through the related resource's own
343 /// query and policy as any relation table does, so a record of another tenant, or one the
344 /// related resource leaves out, never shows, whatever the records along the path hold. The
345 /// records along the path go through no resource: a soft-deleted order still leads to its
346 /// payments. A direct `#[has_many]` field works too, as a `has_many` table with no create
347 /// button. The path needs a SQL driver, as Toasty's `via` does.
348 pub fn through<C>(via: impl Into<Path<P, List<C::Model>>>) -> Self
349 where
350 C: Resource,
351 P: Send + Sync,
352 {
353 let via: Path<P, List<C::Model>> = via.into();
354 let (field, misdeclared) = match model::field::<P>(&ModelPath::of(&via)) {
355 Ok(field) => (field.name, None),
356 Err(error) => (String::new(), Some(error)),
357 };
358 Self {
359 child: TypeId::of::<C>(),
360 child_name: std::any::type_name::<C>(),
361 label: None,
362 tab: false,
363 kind: RelationKind::Through { field },
364 misdeclared,
365 bind: Arc::new(move |owner| (linked_to(owner, via.clone()), pk::pk_text(owner))),
366 }
367 }
368
369 /// Declare a many-to-many child resource whose records the owner links through `via`, its
370 /// `#[has_many(via = joins.target)]` field: the owner's linked records, which the table
371 /// attaches and detaches as join rows.
372 ///
373 /// ```rust
374 /// # use tablo_core::{NoForm, Relation, Resource, ResourceDef};
375 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
376 /// # struct Post {
377 /// # #[key] #[auto] id: uuid::Uuid,
378 /// # #[has_many]
379 /// # taggings: toasty::Deferred<Vec<Tagging>>,
380 /// # #[has_many(via = taggings.tag)]
381 /// # tags: toasty::Deferred<Vec<Tag>>,
382 /// # }
383 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
384 /// # struct Tag { #[key] #[auto] id: uuid::Uuid, name: String }
385 /// # #[derive(Debug, Clone, toasty::Model)]
386 /// # struct Tagging {
387 /// # #[key] #[auto] id: uuid::Uuid,
388 /// # #[index] post_id: uuid::Uuid,
389 /// # #[belongs_to(key = post_id, references = id)]
390 /// # post: toasty::Deferred<Post>,
391 /// # #[index] tag_id: uuid::Uuid,
392 /// # #[belongs_to(key = tag_id, references = id)]
393 /// # tag: toasty::Deferred<Tag>,
394 /// # }
395 /// # struct TagResource;
396 /// # impl Resource for TagResource { type Model = Tag; type Form = NoForm<Tag>; }
397 /// let tags: Relation<Post> = Relation::belongs_to_many::<TagResource>(Post::fields().tags());
398 /// ```
399 ///
400 /// The section's header carries Attach, whose dialog asks for one record through a
401 /// searchable choice offered as a relationship's options are; attaching a linked record
402 /// changes nothing. Each row and the bulk bar carry Detach, which deletes the join rows and
403 /// leaves the records. Both post under the owner's record:
404 /// `{list}/{key}/-/relations/{slug}/-/actions/attach`, `…/-/actions/detach` with the
405 /// selection's `ids`, and `…/{related}/-/actions/detach` for one row. The owner's hooks
406 /// receive [`Change::Attach`](crate::Change::Attach) or
407 /// [`Change::Detach`](crate::Change::Detach).
408 ///
409 /// Attaching and detaching ask the owner's policy for `Update`, as editing it does: no button
410 /// renders without it, and the routes answer 403. The attach dialog offers the related
411 /// resource's rows as its relationship choices do; a record its policy refuses `View` shows
412 /// without a Detach action, as it shows without its other row actions, and is not detached.
413 /// Mounting refuses a join model a link cannot write.
414 pub fn belongs_to_many<C>(via: impl Into<Path<P, List<C::Model>>>) -> Self
415 where
416 C: Resource,
417 P: Send + Sync,
418 {
419 let via: Path<P, List<C::Model>> = via.into();
420 let (field, misdeclared) = match model::field::<P>(&ModelPath::of(&via)) {
421 Ok(field) => (field.name, None),
422 Err(error) => (String::new(), Some(error)),
423 };
424 let attach_via = via.clone();
425 let attach_field = field.clone();
426 let detach_via = via.clone();
427 let detach_field = field.clone();
428 Self {
429 child: TypeId::of::<C>(),
430 child_name: std::any::type_name::<C>(),
431 label: None,
432 tab: false,
433 kind: RelationKind::ManyToMany(Links {
434 field,
435 input: InputSpec {
436 schema: attach_schema::<C>,
437 takes_input: true,
438 parse: parse_attach,
439 submits: Vec::new,
440 },
441 attach: Arc::new(move |cx, owner, key, ex| {
442 let (via, field) = (attach_via.clone(), attach_field.clone());
443 Box::pin(async move { attach::<P, C>(cx, owner, via, &field, key, ex).await })
444 }),
445 detach: Arc::new(move |cx, owner, keys, ex| {
446 let (via, field) = (detach_via.clone(), detach_field.clone());
447 Box::pin(async move { detach::<P, C>(cx, owner, via, &field, keys, ex).await })
448 }),
449 }),
450 misdeclared,
451 bind: Arc::new(move |owner| (linked_to(owner, via.clone()), pk::pk_text(owner))),
452 }
453 }
454}
455
456impl<P> Relation<P> {
457 /// Titles the section `label` instead of the related resource's label: its plural one over a
458 /// table, its singular one over a `has_one` relation's form.
459 #[must_use]
460 pub fn label(mut self, label: impl Into<crate::Text>) -> Self {
461 self.label = Some(label.into());
462 self
463 }
464
465 /// Serves the table on a page of its own, `{list}/{key}/{related slug}`, instead of under the
466 /// record's detail and edit pages, linked from the record's navigation: the tab bar its detail
467 /// page, edit page, [record pages](crate::RecordPage) and relation tabs share.
468 ///
469 /// The page loads the record as its detail page does, through the resource's query and
470 /// [`Ability::View`](crate::Ability::View), and answers 403 when the related resource's policy
471 /// refuses `ViewAny`. Mounting refuses a `has_one` relation as a tab, since its form edits
472 /// inside the record's, and a tab whose related slug is `edit`, `delete`, `-` or a record
473 /// page's.
474 #[must_use]
475 pub fn tab(mut self) -> Self {
476 self.tab = true;
477 self
478 }
479
480 /// The child's rows that belong to `owner`, and the owner's primary key as text.
481 pub(crate) fn bind(&self, owner: &P) -> (Expr<bool>, String) {
482 (self.bind)(owner)
483 }
484}
485
486impl<P> Relation<P> {
487 /// The relation's join-row writes, when it is a many-to-many one.
488 pub(crate) fn links(&self) -> Option<&Links<P>> {
489 match &self.kind {
490 RelationKind::ManyToMany(links) => Some(links),
491 RelationKind::HasMany { .. }
492 | RelationKind::HasOne { .. }
493 | RelationKind::Through { .. } => None,
494 }
495 }
496
497 /// The child's column holding the owner's key, when the relation is a `has_one` one.
498 pub(crate) fn has_one_key(&self) -> Option<&str> {
499 match &self.kind {
500 RelationKind::HasOne { foreign_key } => Some(foreign_key),
501 RelationKind::HasMany { .. }
502 | RelationKind::ManyToMany(_)
503 | RelationKind::Through { .. } => None,
504 }
505 }
506}
507
508impl<P> std::fmt::Debug for Relation<P> {
509 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510 let mut debug = f.debug_struct("Relation");
511 debug
512 .field("child", &self.child_name)
513 .field("label", &self.label);
514 match &self.kind {
515 RelationKind::HasMany { foreign_key } | RelationKind::HasOne { foreign_key } => {
516 debug.field("foreign_key", foreign_key)
517 }
518 RelationKind::ManyToMany(links) => debug.field("via", &links.field),
519 RelationKind::Through { field } => debug.field("through", field),
520 };
521 debug.finish_non_exhaustive()
522 }
523}