tablo-core 0.10.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! 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, 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, lens};
/// # #[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>(lens!(Comment.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.
///
/// A [`has_one`](Self::has_one) relation renders no table: the related resource's form edits the
/// record's one child inside the record's own form.
///
/// [`tab`](Self::tab) moves the table off the detail and edit pages onto a page of its own.
///
/// 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>,
    /// Whether [`Self::tab`] serves the table on a page of its own.
    pub(crate) tab: bool,
    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's one child row holds its key in this column, which the related form fills.
    HasOne { 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; 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 field of the child model `M` holding the owner's primary key, of type `K`: a
/// [`lens!`](crate::lens!) or a field path over a `K` column, or an `Option<K>` one for an
/// optional reference. Sealed.
pub trait ForeignKey<M, K>: sealed::Field<M, K> {}

impl<M, K, F: sealed::Field<M, K>> ForeignKey<M, K> for F {}

mod sealed {
    use toasty::stmt::{IntoExpr, Path};

    use crate::{Lens, form::FormScalar};

    pub trait Field<M, K> {
        type Column: Column<K>;

        fn into_path(self) -> Path<M, Self::Column>;
    }

    impl<M, K, T: Column<K>> Field<M, K> for Path<M, T> {
        type Column = T;

        fn into_path(self) -> Path<M, T> {
            self
        }
    }

    impl<M, K, V, T: Column<K>> Field<M, K> for Lens<M, V, T> {
        type Column = T;

        fn into_path(self) -> Path<M, T> {
            self.into()
        }
    }

    /// A column type holding a key of type `K`: `K` itself, or `Option<K>`.
    pub trait Column<K>: IntoExpr<Self> + FormScalar + Send + Sync + 'static {}

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

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

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, lens};
    /// # #[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>(lens!(Comment.post_id));
    /// ```
    pub fn has_many<C>(foreign_key: impl ForeignKey<C::Model, P::PrimaryKey>) -> Self
    where
        C: Resource,
    {
        Self::bound_by::<C, _>(foreign_key)
    }

    /// Declare a `has_one` child resource whose `foreign_key` holds the owner's primary key, a
    /// single column: the record's one child, edited by the child resource's own form inside the
    /// owner's create and edit forms rather than by a table.
    ///
    /// ```rust
    /// # use tablo_core::{Relation, Resource, ResourceDef, lens};
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns, tablo_core::ModelForm)]
    /// # struct User {
    /// #     #[key] #[auto] id: uuid::Uuid,
    /// #     name: String,
    /// #     #[has_one]
    /// #     profile: toasty::Deferred<Option<Profile>>,
    /// # }
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns, tablo_core::ModelForm)]
    /// # struct Profile {
    /// #     #[key] #[auto] id: uuid::Uuid,
    /// #     #[unique]
    /// #     #[form(relationship = UserResource)]
    /// #     user_id: uuid::Uuid,
    /// #     #[belongs_to(key = user_id, references = id)]
    /// #     user: toasty::Deferred<User>,
    /// #     bio: String,
    /// # }
    /// # struct UserResource;
    /// # impl Resource for UserResource { type Model = User; type Form = UserForm; }
    /// # struct ProfileResource;
    /// # impl Resource for ProfileResource { type Model = Profile; type Form = ProfileForm; }
    /// let profile: Relation<User> = Relation::has_one::<ProfileResource>(lens!(Profile.user_id));
    /// ```
    ///
    /// The related resource's form renders as a section of the owner's form, titled with its
    /// label or [`label`](Self::label), each control posting under the child's slug, as in
    /// `profiles.bio`; the foreign key renders no control, since the owner's key fills it. Saving
    /// the owner writes the child in the same transaction, after the owner: a create creates it,
    /// and an edit updates the record's child or creates one when it has none. Either way the
    /// child goes through its own resource as on its own pages: its policy, tenancy, field access,
    /// control rules, unique probe, `validate_record`, record fn and commit hooks. A refusal from
    /// either form rolls both back and renders both with their errors. The owner's hooks receive
    /// the owner's change, the child's its own.
    ///
    /// The section renders only while the request may write the child: `Create` on the related
    /// resource, or `View` and `Update` on the record's child, with the foreign key neither hidden
    /// nor locked by field access. A record with more than one child, or one the related
    /// resource's query leaves out, renders none. A submission posting under the prefix with no
    /// section is refused, and one posting nothing under it, such as an editable cell's or an
    /// import row's, leaves the child alone. The relation renders no table.
    ///
    /// Mounting refuses a related resource with no form, one whose form binds no control for
    /// the foreign key, a soft-deleting one, one whose form holds a control that needs its own
    /// keys or routes (a file field, a repeater, an embedded value, a searchable or dependent
    /// choice), an owner with no form, and an owner form key the prefix would shadow.
    pub fn has_one<C>(foreign_key: impl ForeignKey<C::Model, P::PrimaryKey>) -> Self
    where
        C: Resource,
    {
        let mut relation = Self::bound_by::<C, _>(foreign_key);
        if let RelationKind::HasMany { foreign_key } = relation.kind {
            relation.kind = RelationKind::HasOne { foreign_key };
        }
        relation
    }

    fn bound_by<C, F>(foreign_key: F) -> Self
    where
        C: Resource,
        F: ForeignKey<C::Model, P::PrimaryKey>,
    {
        let foreign_key = foreign_key.into_path();
        // 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,
            tab: false,
            kind: RelationKind::HasMany {
                foreign_key: column,
            },
            misdeclared,
            bind: Arc::new(move |owner| {
                let scope = foreign_key.clone().eq(pk::pk_expr::<P, F::Column>(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. The attach dialog offers the related
    /// resource's rows as its relationship choices do; a record its policy refuses `View` shows
    /// without a Detach action, as it shows without its other row actions, and is not 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,
            tab: false,
            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 label: its plural one over a
    /// table, its singular one over a `has_one` relation's form.
    #[must_use]
    pub fn label(mut self, label: impl Into<crate::Text>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Serves the table on a page of its own, `{list}/{key}/{related slug}`, instead of under the
    /// record's detail and edit pages, linked from the record's navigation: the tab bar its detail
    /// page, edit page, [record pages](crate::RecordPage) and relation tabs share.
    ///
    /// The page loads the record as its detail page does, through the resource's query and
    /// [`Ability::View`](crate::Ability::View), and answers 403 when the related resource's policy
    /// refuses `ViewAny`. Mounting refuses a `has_one` relation as a tab, since its form edits
    /// inside the record's, and a tab whose related slug is `edit`, `delete`, `-` or a record
    /// page's.
    #[must_use]
    pub fn tab(mut self) -> Self {
        self.tab = true;
        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 { .. } | RelationKind::HasOne { .. } => None,
        }
    }

    /// The child's column holding the owner's key, when the relation is a `has_one` one.
    pub(crate) fn has_one_key(&self) -> Option<&str> {
        match &self.kind {
            RelationKind::HasOne { foreign_key } => Some(foreign_key),
            RelationKind::HasMany { .. } | RelationKind::ManyToMany(_) => 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 } | RelationKind::HasOne { foreign_key } => {
                debug.field("foreign_key", foreign_key)
            }
            RelationKind::ManyToMany(links) => debug.field("via", &links.field),
        };
        debug.finish_non_exhaustive()
    }
}