Skip to main content

day_persistence/
relations.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Relations (docs/persistence.md): `One<M>` foreign keys, `Many<M>` maintained inverses,
5//! delete rules, and the machinery that keeps them true.
6//!
7//! A to-one relation is stored in one place, the foreign-key column on the child, and the
8//! parent's `Many` side is a view over it, answered from the engine's foreign-key index and
9//! memoized per parent. Nothing is loaded at open: the first read of one parent's
10//! children is one indexed `SELECT`, remembered until a membership write invalidates it.
11//! Write `lodging.trip()` and the trip's `lodging()` read wakes; call
12//! `trip.lodging().add(id)` and it writes the lodging's foreign key through the front door,
13//! so the change announces, captures for undo, folds to one `UPDATE`, and marks any live
14//! query watching either table stale.
15//!
16//! Reads made mid-turn see the truth: the memo answers from the last flush, overlaid with
17//! this turn's unflushed dirty rows, so a child reparented a millisecond ago is under its new
18//! parent before any SQL runs.
19//!
20//! Delete rules run where the delete announces: a parent's removal cascades (recursively:
21//! the nested deletes take the same pipeline, so undoing the cascade is one unit that
22//! restores the whole subtree), nullifies (`Option<One<M>>` references clear), or denies
23//! (the checked door [`crate::ModelContainer::delete`] refuses while children remain). The
24//! generated DDL carries the matching `REFERENCES … ON DELETE …` clause,
25//! `DEFERRABLE INITIALLY DEFERRED` so within-transaction statement order never trips it. The
26//! clause also holds another process to the same rules, and is what deletes the non-resident
27//! rows a cascade reaches: the pipeline walks every child (so queries, memos and undo hear),
28//! and the engine's clause is the backstop that makes the file agree.
29
30use std::cell::{Cell, RefCell};
31use std::collections::HashMap;
32use std::marker::PhantomData;
33use std::rc::{Rc, Weak};
34
35use day_model::{ApplyField, Keyed, ModelId, Op, Store, announce, field_id};
36
37use crate::{
38    ColumnValue, ContainerInner, DbError, DbErrorKind, DirtyRow, Model, ModelContainer, Row,
39    SqlType, TableName, Value, ident, key_param, value_to_handle,
40};
41
42// ---------------------------------------------------------------------------
43// The reference types
44// ---------------------------------------------------------------------------
45
46/// A to-one reference: the foreign-key column on the child row. `One<M>` alone is a required
47/// reference (`NOT NULL`); wrap it `Option<One<M>>` for a nullable one. `Copy`, 16 bytes, and
48/// an ordinary [`ColumnValue`], so the derive treats the field as a plain column whose stored
49/// form is the target's key shape.
50pub struct One<M: ?Sized> {
51    id: Option<u64>,
52    _m: PhantomData<fn() -> M>,
53}
54
55impl<M: ?Sized> Clone for One<M> {
56    fn clone(&self) -> Self {
57        *self
58    }
59}
60impl<M: ?Sized> Copy for One<M> {}
61impl<M: ?Sized> Default for One<M> {
62    /// Unset. A required (`NOT NULL`) reference left at its default surfaces at flush time as
63    /// the constraint violation it is; set it before the turn ends.
64    fn default() -> Self {
65        One {
66            id: None,
67            _m: PhantomData,
68        }
69    }
70}
71impl<M: ?Sized> PartialEq for One<M> {
72    fn eq(&self, other: &Self) -> bool {
73        self.id == other.id
74    }
75}
76impl<M: ?Sized> Eq for One<M> {}
77impl<M: ?Sized> std::hash::Hash for One<M> {
78    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
79        self.id.hash(state);
80    }
81}
82impl<M: ?Sized> std::fmt::Debug for One<M> {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        match self.id {
85            Some(h) => write!(f, "One({:?})", ModelId::<M>::from_handle(h)),
86            None => f.write_str("One(unset)"),
87        }
88    }
89}
90
91impl<M: ?Sized> One<M> {
92    /// A reference to `id`.
93    pub fn to(id: impl Into<ModelId<M>>) -> Self {
94        One {
95            id: Some(id.into().handle()),
96            _m: PhantomData,
97        }
98    }
99    /// The unset reference (what [`Default`] gives).
100    pub const fn none() -> Self {
101        One {
102            id: None,
103            _m: PhantomData,
104        }
105    }
106    /// The referenced id, or `None` when unset.
107    pub fn id(self) -> Option<ModelId<M>> {
108        self.id.map(ModelId::from_handle)
109    }
110    pub(crate) fn from_handle(h: u64) -> Self {
111        One {
112            id: Some(h),
113            _m: PhantomData,
114        }
115    }
116    pub(crate) fn from_handle_opt(h: Option<u64>) -> Self {
117        One {
118            id: h,
119            _m: PhantomData,
120        }
121    }
122    pub(crate) fn handle_opt(self) -> Option<u64> {
123        self.id
124    }
125}
126
127impl<M: Model> ColumnValue for One<M> {
128    /// The target's key shape: `INTEGER`, a 16-byte `BLOB`, or `TEXT`.
129    const SQL_TYPE: SqlType = M::KEY_SQL;
130    fn to_sqlite_value(&self) -> Value {
131        match self.id {
132            Some(h) => key_param(h),
133            None => Value::Null,
134        }
135    }
136    fn from_sqlite_value(v: Value) -> Result<Self, DbError> {
137        match value_to_handle(&v) {
138            Some(h) => Ok(One::from_handle(h)),
139            None => Err(DbError::new(
140                DbErrorKind::Decode,
141                format!("a stored reference would not read as a key: {v:?}"),
142            )),
143        }
144    }
145}
146
147/// Predicates over a to-one reference column: the identity and presence tests, which need
148/// nothing but the foreign-key column already stored here.
149impl<M: Model> crate::Col<One<M>> {
150    /// The reference points at exactly this row.
151    pub fn is(self, id: impl Into<ModelId<M>>) -> crate::Pred {
152        self.eq(One::<M>::from_handle(id.into().handle()))
153    }
154
155    /// The reference points at one of these rows: the set form, and what a query feeding
156    /// another query compiles to. (Named apart from the generic [`crate::Col::is_in`], which
157    /// takes `One` values; this one takes ids, which is what a caller holds.)
158    pub fn is_one_of(self, ids: impl IntoIterator<Item = impl Into<ModelId<M>>>) -> crate::Pred {
159        self.is_in(
160            ids.into_iter()
161                .map(|i| One::<M>::from_handle(i.into().handle()))
162                .collect::<Vec<_>>(),
163        )
164    }
165
166    /// The reference was never set, or a nullify rule cleared it.
167    pub fn is_unset(self) -> crate::Pred {
168        self.is_null()
169    }
170
171    /// The reference points somewhere.
172    pub fn is_set(self) -> crate::Pred {
173        self.is_not_null()
174    }
175}
176
177/// Traversing a to-one reference in a predicate: "lodgings whose trip is done". A to-one is
178/// a to-many of at most one, so the quantifier vocabulary is the same one the `Many` side
179/// uses; `any` reads as "its target matches, and there is one".
180impl<M: Model> crate::Col<One<M>> {
181    pub fn any(self, inner: crate::Pred) -> crate::Pred {
182        self.quantified(crate::Quant::Any, inner)
183    }
184    pub fn none(self, inner: crate::Pred) -> crate::Pred {
185        self.quantified(crate::Quant::None, inner)
186    }
187
188    fn quantified(self, quant: crate::Quant, inner: crate::Pred) -> crate::Pred {
189        crate::Pred::Related {
190            owner: self.owner,
191            field: self.field,
192            target: <M as Model>::TABLE,
193            quant,
194            inner: Box::new(inner),
195        }
196    }
197}
198
199/// The same, over a nullable reference.
200impl<M: Model> crate::Col<Option<One<M>>> {
201    pub fn any(self, inner: crate::Pred) -> crate::Pred {
202        self.quantified(crate::Quant::Any, inner)
203    }
204    pub fn none(self, inner: crate::Pred) -> crate::Pred {
205        self.quantified(crate::Quant::None, inner)
206    }
207
208    fn quantified(self, quant: crate::Quant, inner: crate::Pred) -> crate::Pred {
209        crate::Pred::Related {
210            owner: self.owner,
211            field: self.field,
212            target: <M as Model>::TABLE,
213            quant,
214            inner: Box::new(inner),
215        }
216    }
217}
218
219/// The same tests over a nullable reference (`Option<One<M>>`), which is what a relation with
220/// a nullify delete rule requires the child to hold.
221impl<M: Model> crate::Col<Option<One<M>>> {
222    pub fn is(self, id: impl Into<ModelId<M>>) -> crate::Pred {
223        self.eq(Some(One::<M>::from_handle(id.into().handle())))
224    }
225
226    pub fn is_one_of(self, ids: impl IntoIterator<Item = impl Into<ModelId<M>>>) -> crate::Pred {
227        self.is_in(
228            ids.into_iter()
229                .map(|i| Some(One::<M>::from_handle(i.into().handle())))
230                .collect::<Vec<_>>(),
231        )
232    }
233
234    /// The reference was never set, or a nullify rule cleared it.
235    pub fn is_unset(self) -> crate::Pred {
236        self.is_null()
237    }
238
239    /// The reference points somewhere.
240    pub fn is_set(self) -> crate::Pred {
241        self.is_not_null()
242    }
243}
244
245/// The to-many side: a marker field. It stores nothing; membership lives in the children's
246/// foreign keys (or the join table), and the field exists so the relation has an observable
247/// path of its own and a declared home for `#[model(relation(…))]`. Reads go through the
248/// generated accessor's [`RelationRef`].
249pub struct Many<M: ?Sized> {
250    _m: PhantomData<fn() -> M>,
251}
252
253impl<M: ?Sized> Clone for Many<M> {
254    fn clone(&self) -> Self {
255        *self
256    }
257}
258impl<M: ?Sized> Copy for Many<M> {}
259impl<M: ?Sized> Default for Many<M> {
260    fn default() -> Self {
261        Many { _m: PhantomData }
262    }
263}
264impl<M: ?Sized> PartialEq for Many<M> {
265    fn eq(&self, _: &Self) -> bool {
266        true
267    }
268}
269impl<M: ?Sized> Eq for Many<M> {}
270impl<M: ?Sized> std::fmt::Debug for Many<M> {
271    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272        f.write_str("Many")
273    }
274}
275
276/// What deleting a referenced parent does. Declared per relation
277/// (`#[model(relation(delete = "…"))]`); the default is `Nullify` (also `SwiftData`'s default
278/// for `@Relationship`).
279#[derive(Clone, Copy, PartialEq, Eq, Debug)]
280pub enum DeleteRule {
281    /// Children survive; their references clear. Needs `Option<One<M>>` on the child: a
282    /// required reference cannot hold "nothing", and wiring refuses the combination.
283    Nullify,
284    /// Children delete with the parent, recursively, through the normal pipeline, undoable
285    /// as one unit and heard by live queries.
286    Cascade,
287    /// The delete is refused while children remain, through
288    /// [`crate::ModelContainer::delete`], the checked door; a raw `restructure` bypasses the
289    /// check and the deferred SQL `RESTRICT` refuses at flush instead.
290    Deny,
291}
292
293impl DeleteRule {
294    pub(crate) fn sql(self) -> &'static str {
295        match self {
296            DeleteRule::Nullify => "SET NULL",
297            DeleteRule::Cascade => "CASCADE",
298            DeleteRule::Deny => "RESTRICT",
299        }
300    }
301}
302
303/// One declared relation, as the derive records it on the parent (`Many`) side.
304#[derive(Clone, Copy, Debug)]
305pub struct RelationDef {
306    /// The `Many` field's name on the declaring model.
307    pub field: &'static str,
308    /// The target model's table.
309    pub target_table: &'static str,
310    /// To-one/to-many: the target's foreign-key field. Join relations leave it empty.
311    pub inverse: &'static str,
312    pub delete: DeleteRule,
313    /// The target's order field (`REAL`) for an ordered to-many.
314    pub ordered: Option<&'static str>,
315    /// A join table name: the many-to-many form.
316    pub join: Option<&'static str>,
317}
318
319// ---------------------------------------------------------------------------
320// Wiring
321// ---------------------------------------------------------------------------
322
323/// What `Model::wire` receives: the container mid-open. Wiring failures collect here and
324/// fail the open with the first one, named.
325pub struct Registrar<'c> {
326    pub(crate) container: &'c ModelContainer,
327    pub(crate) error: Option<DbError>,
328}
329
330impl Registrar<'_> {
331    fn fail(&mut self, message: String) {
332        if self.error.is_none() {
333            self.error = Some(DbError::new(DbErrorKind::Schema, message));
334        }
335    }
336}
337
338/// One wired to-one/to-many relation. The typed closures are monomorphized over both model
339/// types by [`wire_to_many`], so every write goes through the front door with full type
340/// knowledge; the SQL half (table and column names) is what lazy reads and the query
341/// compiler drive.
342pub(crate) struct ToOneRel {
343    pub(crate) container: Weak<ContainerInner>,
344    pub(crate) parent_store: u64,
345    pub(crate) parent_table: &'static str,
346    pub(crate) parent_field: &'static str,
347    pub(crate) parent_key_col: &'static str,
348    pub(crate) child_store: u64,
349    pub(crate) child_table: &'static str,
350    /// `child_table` as the lazy reads below name it.
351    pub(crate) child_sql: String,
352    pub(crate) child_key_col: &'static str,
353    /// The foreign key as the child's field (the change log's language) and column (SQL's).
354    pub(crate) fk_field: &'static str,
355    pub(crate) fk_col: &'static str,
356    pub(crate) delete: DeleteRule,
357    pub(crate) ordered: Option<&'static str>,
358    pub(crate) ord_col: Option<&'static str>,
359    read_fk: Box<dyn Fn(u64) -> Option<u64>>,
360    write_fk: Box<dyn Fn(u64, Option<u64>) -> bool>,
361    delete_child: Box<dyn Fn(u64)>,
362    /// Bring children into the cache (before their fields are written, or for undo capture).
363    materialize: Materialize,
364    read_ord_cached: Box<dyn Fn(u64) -> Option<f64>>,
365    pub(crate) write_ord: Box<dyn Fn(u64, f64) -> bool>,
366    /// parent → children (relation order), filled per parent on first read.
367    memo: RefCell<HashMap<u64, Vec<u64>>>,
368    /// child → memoized parent, maintained only for children of memoized parents: the O(1)
369    /// walk-back a foreign-key rewrite needs.
370    memo_parent: RefCell<HashMap<u64, u64>>,
371}
372
373impl ToOneRel {
374    fn with_container<R>(&self, f: impl FnOnce(&ModelContainer) -> R) -> Option<R> {
375        self.container.upgrade().map(|inner| {
376            let c = ModelContainer { inner };
377            f(&c)
378        })
379    }
380
381    /// The parent's children, in relation order: the memo, or one indexed `SELECT`, overlaid
382    /// with this turn's unflushed dirty rows so mid-turn reads see the truth.
383    pub(crate) fn children_of(&self, parent: u64) -> Vec<u64> {
384        // A parent deleted this turn has no children to show, whatever the file still holds
385        // until the flush takes them.
386        if self.with_container(|c| c.dirty_state_of(self.parent_store, parent))
387            == Some(Some(DirtyRow::Delete))
388        {
389            return Vec::new();
390        }
391        self.children_of_raw(parent)
392    }
393
394    /// `children_of` without the deleted-parent shortcut: what the cascade walk itself
395    /// needs, since it runs for a parent that is being deleted.
396    fn children_of_raw(&self, parent: u64) -> Vec<u64> {
397        if let Some(hit) = self.memo.borrow().get(&parent) {
398            return hit.clone();
399        }
400        let Some(mut ids) = self.with_container(|c| {
401            let order = ident(self.ord_col.unwrap_or(self.child_key_col));
402            c.select_id_column(
403                &format!(
404                    "SELECT {k} FROM {t} WHERE {fk} = ? ORDER BY {order}, {k}",
405                    k = ident(self.child_key_col),
406                    t = self.child_sql,
407                    fk = ident(self.fk_col),
408                ),
409                &[key_param(parent)],
410            )
411        }) else {
412            return Vec::new();
413        };
414        self.overlay_children(parent, &mut ids);
415        let mut memo = self.memo.borrow_mut();
416        let mut back = self.memo_parent.borrow_mut();
417        for id in &ids {
418            back.insert(*id, parent);
419        }
420        memo.insert(parent, ids.clone());
421        ids
422    }
423
424    /// Correct a freshly-selected child list against this turn's unflushed edits: dirty
425    /// resident children join or leave by their current foreign key, and dirty deletes leave.
426    fn overlay_children(&self, parent: u64, ids: &mut Vec<u64>) {
427        let Some(dirty) = self.with_container(|c| c.dirty_rows_of(self.child_store)) else {
428            return;
429        };
430        for (child, state) in dirty {
431            let is_mine = state != DirtyRow::Delete && (self.read_fk)(child) == Some(parent);
432            let at = ids.iter().position(|c| *c == child);
433            match (is_mine, at) {
434                (false, Some(i)) => {
435                    ids.remove(i);
436                }
437                (true, None) => {
438                    // Place by the relation's order (the child is resident: it is dirty).
439                    let ord = (self.read_ord_cached)(child).unwrap_or(f64::INFINITY);
440                    let at = if self.ordered.is_some() {
441                        ids.iter()
442                            .position(|c| (self.read_ord_cached)(*c).unwrap_or(0.0) > ord)
443                            .unwrap_or(ids.len())
444                    } else {
445                        ids.partition_point(|c| *c < child)
446                    };
447                    ids.insert(at, child);
448                }
449                _ => {}
450            }
451        }
452    }
453
454    /// The parent this child belongs to: the memo when it knows, the child's cached
455    /// foreign key, or one point `SELECT`.
456    /// Whether the container is re-reading rows an engine cascade touched.
457    fn reconciling(&self) -> bool {
458        self.with_container(|c| c.inner.reconciling.get())
459            .unwrap_or(false)
460    }
461
462    pub(crate) fn parent_of(&self, child: u64) -> Option<u64> {
463        if let Some(p) = self.memo_parent.borrow().get(&child) {
464            return Some(*p);
465        }
466        if let Some(p) = (self.read_fk)(child) {
467            return Some(p);
468        }
469        self.with_container(|c| {
470            c.select_id_column(
471                &format!(
472                    "SELECT {fk} FROM {t} WHERE {k} = ?",
473                    fk = ident(self.fk_col),
474                    t = self.child_sql,
475                    k = ident(self.child_key_col),
476                ),
477                &[key_param(child)],
478            )
479            .into_iter()
480            .next()
481        })
482        .flatten()
483    }
484
485    /// One child's order value: cache first (which covers every unflushed write), the file
486    /// otherwise.
487    pub(crate) fn read_order(&self, child: u64) -> f64 {
488        if let Some(v) = (self.read_ord_cached)(child) {
489            return v;
490        }
491        let Some(col) = self.ord_col else { return 0.0 };
492        self.with_container(|c| {
493            c.select_real(
494                &format!(
495                    "SELECT {} FROM {t} WHERE {k} = ?",
496                    ident(col),
497                    t = self.child_sql,
498                    k = ident(self.child_key_col),
499                ),
500                &[key_param(child)],
501            )
502        })
503        .flatten()
504        .unwrap_or(0.0)
505    }
506
507    pub(crate) fn set_fk(&self, child: u64, parent: Option<u64>) -> bool {
508        // Writes need the row resident; the announcement then routes back through
509        // `reparent`, which is where the memos and both parents' announcements happen:
510        // one path for every door.
511        (self.materialize)(&[child]);
512        (self.write_fk)(child, parent)
513    }
514
515    fn announce_parent(&self, parent: u64) {
516        announce(
517            &[self.parent_store, parent, field_id(self.parent_field)],
518            self.parent_field,
519        );
520    }
521
522    fn forget(&self, parent: u64) {
523        if let Some(children) = self.memo.borrow_mut().remove(&parent) {
524            let mut back = self.memo_parent.borrow_mut();
525            for c in children {
526                back.remove(&c);
527            }
528        }
529    }
530
531    pub(crate) fn invalidate_all(&self) {
532        self.memo.borrow_mut().clear();
533        self.memo_parent.borrow_mut().clear();
534    }
535
536    /// A child arrived (an insert, an undo re-insert, an external merge).
537    pub(crate) fn child_added(&self, child: u64) {
538        if let Some(p) = (self.read_fk)(child) {
539            self.forget(p);
540            self.announce_parent(p);
541        }
542    }
543
544    /// A child left. The memo knows its parent when the parent was ever read; otherwise the
545    /// file still holds the row until the flush, so one point `SELECT` answers.
546    pub(crate) fn child_removed(&self, child: u64) {
547        let memo = self.memo_parent.borrow().get(&child).copied();
548        // After an engine cascade the parent is gone too; the file has nothing to say.
549        let parent = if memo.is_none() && self.reconciling() {
550            None
551        } else {
552            memo.or_else(|| self.parent_of(child))
553        };
554        if let Some(p) = parent {
555            self.forget(p);
556            self.announce_parent(p);
557        }
558    }
559
560    /// The child's foreign key was rewritten: both parents' views move. The new parent is the
561    /// child's own field; the old one is the memo when a reader ever established it, the
562    /// file otherwise (the un-flushed value is exactly the pre-write one). A reader whose
563    /// memo was current re-establishes it on its own re-read, so repeated reparents in one
564    /// turn stay coherent for anything watching.
565    pub(crate) fn reparent(&self, child: u64) {
566        let new = (self.read_fk)(child);
567        let memo = self.memo_parent.borrow().get(&child).copied();
568        // An engine `SET NULL` re-pointed this child away from a parent that is gone.
569        let old = if memo.is_none() && self.reconciling() {
570            None
571        } else {
572            memo.or_else(|| self.former_parent_file(child))
573        };
574        if let Some(p) = old {
575            self.forget(p);
576        }
577        if let Some(p) = new
578            && Some(p) != old
579        {
580            self.forget(p);
581        }
582        self.announce_parent_set(old, new);
583    }
584
585    /// Announce each distinct parent in the pair.
586    fn announce_parent_set(&self, a: Option<u64>, b: Option<u64>) {
587        if let Some(p) = a {
588            self.announce_parent(p);
589        }
590        if let Some(p) = b
591            && Some(p) != a
592        {
593            self.announce_parent(p);
594        }
595    }
596
597    /// The parent the file records for this child: the pre-flush truth, bypassing both the
598    /// memo and the (already rewritten) cached row.
599    fn former_parent_file(&self, child: u64) -> Option<u64> {
600        self.with_container(|c| {
601            c.select_id_column(
602                &format!(
603                    "SELECT {fk} FROM {t} WHERE {k} = ?",
604                    fk = ident(self.fk_col),
605                    t = self.child_sql,
606                    k = ident(self.child_key_col),
607                ),
608                &[key_param(child)],
609            )
610            .into_iter()
611            .next()
612        })
613        .flatten()
614    }
615
616    /// The child's order field moved: its parent's view reorders.
617    pub(crate) fn order_changed(&self, child: u64) {
618        if let Some(p) = self.parent_of(child) {
619            self.forget(p);
620            self.announce_parent(p);
621        }
622    }
623
624    pub(crate) fn parent_deleted(&self, container: &ModelContainer, parent: u64) {
625        // With no undo stack to serve, the engine's own `ON DELETE CASCADE` / `SET NULL`
626        // does the work in the flush, in one statement per table; the resident children
627        // are re-read afterwards (`reconcile_engine_cascades`). Walking them here would read
628        // every child row and then issue deletes the engine has already performed.
629        if container.engine_cascade_allowed()
630            && matches!(self.delete, DeleteRule::Cascade | DeleteRule::Nullify)
631        {
632            self.forget(parent);
633            container.note_engine_cascade(self.child_table);
634            // A child inserted this same turn is not in the file, so the engine never sees
635            // the pair: the flush would write it against a parent its own DELETE removes.
636            // Those few take the in-process path (a delete absorbs the pending insert).
637            let pending: Vec<u64> = container
638                .dirty_rows_of(self.child_store)
639                .into_iter()
640                .filter(|(c, state)| {
641                    *state == DirtyRow::Insert && (self.read_fk)(*c) == Some(parent)
642                })
643                .map(|(c, _)| c)
644                .collect();
645            for child in pending {
646                match self.delete {
647                    DeleteRule::Cascade => (self.delete_child)(child),
648                    _ => {
649                        (self.write_fk)(child, None);
650                    }
651                }
652            }
653            return;
654        }
655        let children = self.children_of_raw(parent);
656        self.forget(parent);
657        if children.is_empty() {
658            return;
659        }
660        match self.delete {
661            DeleteRule::Cascade => {
662                // Each nested delete takes the whole pipeline (announce, undo capture,
663                // dirty, query staleness) and, for a self-referential tree, recurses
664                // through this same method one level down. When an undo stack stands by,
665                // the rows materialize first so their deletes carry what inversion needs;
666                // without one the deletes are value-free and the fold batches them.
667                if day_model::record_capture_active() {
668                    (self.materialize)(&children);
669                }
670                for child in children {
671                    (self.delete_child)(child);
672                }
673            }
674            DeleteRule::Nullify => {
675                (self.materialize)(&children);
676                for child in children {
677                    (self.write_fk)(child, None);
678                }
679            }
680            DeleteRule::Deny => {
681                // Too late to refuse: the row is gone from the store. The checked door
682                // (`ModelContainer::delete`) refuses before; a bypass surfaces here and at
683                // the deferred SQL RESTRICT.
684                container.inner.error.set(Some(format!(
685                    "deny: `{}` was deleted while `{}` rows still reference it — use \
686                     ModelContainer::delete for deny relations",
687                    self.parent_field, self.fk_field
688                )));
689            }
690        }
691    }
692}
693
694/// Read a child's foreign key, whichever nullability the field declared.
695fn fk_of<P: Model, C: Model>(c: &C, inverse: &str) -> Option<u64> {
696    let any = ApplyField::read_field(c, inverse)?;
697    if let Some(one) = any.downcast_ref::<One<P>>() {
698        return one.handle_opt();
699    }
700    if let Some(opt) = any.downcast_ref::<Option<One<P>>>() {
701        return opt.and_then(One::handle_opt);
702    }
703    None
704}
705
706/// Wire one `Many` declaration; called from the derive-generated `Model::wire`.
707pub fn wire_to_many<P: Model, C: Model>(
708    reg: &mut Registrar<'_>,
709    field: &'static str,
710    inverse: &'static str,
711    delete: DeleteRule,
712    ordered: Option<&'static str>,
713) {
714    let container = reg.container.clone();
715    let Some(parent_store) = container.try_cache::<P>() else {
716        reg.fail(format!(
717            "relation `{}.{field}` wired before `{}` attached",
718            P::TABLE,
719            P::TABLE
720        ));
721        return;
722    };
723    let Some(child_store) = container.try_cache::<C>() else {
724        reg.fail(format!(
725            "relation `{}.{field}` targets `{}`, which is not in this container's schema!",
726            P::TABLE,
727            C::TABLE
728        ));
729        return;
730    };
731    let Some(col) = C::COLUMNS.iter().find(|c| c.field == inverse) else {
732        reg.fail(format!(
733            "relation `{}.{field}` names inverse `{inverse}`, which is not a persisted \
734             field of `{}`",
735            P::TABLE,
736            C::TABLE
737        ));
738        return;
739    };
740    if delete == DeleteRule::Nullify && col.not_null {
741        reg.fail(format!(
742            "relation `{}.{field}` is delete = \"nullify\", but `{}.{inverse}` is a required \
743             `One<…>` — make it `Option<One<…>>`, or use cascade/deny",
744            P::TABLE,
745            C::TABLE
746        ));
747        return;
748    }
749    let mut ord_col = None;
750    if let Some(ord) = ordered {
751        if let Some(c) = C::COLUMNS
752            .iter()
753            .find(|c| c.field == ord && c.sql == SqlType::Real)
754        {
755            ord_col = Some(c.name);
756        } else {
757            reg.fail(format!(
758                "relation `{}.{field}` is ordered by `{ord}`, which is not a REAL (`f64`) \
759                 field of `{}` — the order column is a real, visible field of the child",
760                P::TABLE,
761                C::TABLE
762            ));
763            return;
764        }
765    }
766
767    let read_fk = Box::new(move |h: u64| {
768        child_store.with_untracked(|k| k.get(h).and_then(|c| fk_of::<P, C>(c, inverse)))
769    });
770    let write_fk = Box::new(move |h: u64, parent: Option<u64>| {
771        if child_store.write_field(h, inverse, One::<P>::from_handle_opt(parent)) {
772            return true;
773        }
774        let opt: Option<One<P>> = parent.map(One::<P>::from_handle);
775        child_store.write_field(h, inverse, opt)
776    });
777    let delete_child = Box::new(move |h: u64| {
778        child_store.restructure("cascade", Op::Delete, h, |k| {
779            k.remove(h);
780        });
781    });
782    let mat_container = container.clone();
783    let materialize = Box::new(move |keys: &[u64]| {
784        let _ = mat_container.ensure_resident::<C>(keys);
785    });
786    let read_ord_cached: Box<dyn Fn(u64) -> Option<f64>> = match ordered {
787        Some(ord) => Box::new(move |h| {
788            child_store.with_untracked(|k| {
789                k.get(h)
790                    .and_then(|c| ApplyField::read_field(c, ord))
791                    .and_then(|v| v.downcast_ref::<f64>().copied())
792            })
793        }),
794        None => Box::new(|_| None),
795    };
796    let write_ord: Box<dyn Fn(u64, f64) -> bool> = match ordered {
797        Some(ord) => Box::new(move |h, v| child_store.write_field(h, ord, v)),
798        None => Box::new(|_, _| false),
799    };
800
801    let rel = Rc::new(ToOneRel {
802        container: Rc::downgrade(&container.inner),
803        parent_store: parent_store.store_id(),
804        parent_table: P::TABLE,
805        parent_field: field,
806        parent_key_col: P::KEY,
807        child_store: child_store.store_id(),
808        child_table: C::TABLE,
809        child_sql: TableName::of::<C>().sql(),
810        child_key_col: C::KEY,
811        fk_field: inverse,
812        fk_col: col.name,
813        delete,
814        ordered,
815        ord_col,
816        read_fk,
817        write_fk,
818        delete_child,
819        materialize,
820        read_ord_cached,
821        write_ord,
822        memo: RefCell::new(HashMap::new()),
823        memo_parent: RefCell::new(HashMap::new()),
824    });
825
826    container.inner.relations.borrow_mut().push(rel);
827}
828
829// ---------------------------------------------------------------------------
830// Many-to-many: the join table
831// ---------------------------------------------------------------------------
832
833/// One membership row of a generated join table. Its key is the pair, which is what makes a
834/// membership addressable, undoable and mergeable by the same machinery every other row uses,
835/// with no second vocabulary. The store over these rows is a cache like every other: only
836/// memberships this process touched are resident.
837#[derive(Clone, Default, PartialEq, Debug)]
838pub(crate) struct JoinRow {
839    pub(crate) parent: u64,
840    pub(crate) child: u64,
841    /// The ordered form's position; 0.0 when the relation is unordered.
842    pub(crate) position: f64,
843}
844
845impl day_model::Identified for JoinRow {
846    fn key(&self) -> day_model::Key {
847        day_model::Key::Pair(self.parent, self.child)
848    }
849}
850
851impl ApplyField for JoinRow {
852    fn apply_field(&mut self, label: &str, value: &dyn std::any::Any) -> bool {
853        match (label, value.downcast_ref::<f64>()) {
854            ("position", Some(v)) => {
855                self.position = *v;
856                true
857            }
858            _ => false,
859        }
860    }
861    fn read_field(&self, label: &str) -> Option<Rc<dyn std::any::Any>> {
862        match label {
863            "position" => Some(Rc::new(self.position)),
864            _ => None,
865        }
866    }
867}
868
869/// A wired many-to-many: one per join table, whichever side (or both) declared it.
870///
871/// Membership lives in the join table; both directions answer from its indexes, memoized per
872/// row. When both models declare the relation over the same `join = "…"` table, the second
873/// declaration attaches as this relation's B side rather than opening a second store; two
874/// stores over one table would double every write and disagree about column order.
875pub(crate) struct JoinRel {
876    pub(crate) container: Weak<ContainerInner>,
877    pub(crate) join_table: &'static str,
878    /// `join_table` as the lazy reads below name it.
879    pub(crate) join_sql: String,
880    pub(crate) parent_col: &'static str,
881    pub(crate) child_col: &'static str,
882    /// The side that wired first: its rows are the join row's `parent`.
883    pub(crate) a_store: u64,
884    pub(crate) a_table: &'static str,
885    pub(crate) a_field: &'static str,
886    pub(crate) a_key_col: &'static str,
887    pub(crate) a_delete: DeleteRule,
888    /// The other side. `b_field` is set only if that model declared the relation too, and
889    /// is held in a `Cell` because the second declaration fills it in during wiring while
890    /// the first declaration's `Rc` is already held.
891    pub(crate) b_store: u64,
892    pub(crate) b_table: &'static str,
893    pub(crate) b_key_col: &'static str,
894    pub(crate) b_field: Cell<Option<&'static str>>,
895    pub(crate) b_delete: Cell<DeleteRule>,
896    pub(crate) join_store: u64,
897    /// Order is the A side's: a membership's position places a B row within one A row.
898    pub(crate) ordered: bool,
899    store: Store<Keyed<JoinRow>>,
900    delete_a: Box<dyn Fn(u64)>,
901    delete_b: Box<dyn Fn(u64)>,
902    /// A-side row → its members, and B-side row → its holders, filled on first read.
903    memo_fwd: RefCell<HashMap<u64, Vec<u64>>>,
904    memo_rev: RefCell<HashMap<u64, Vec<u64>>>,
905}
906
907impl JoinRel {
908    fn with_container<R>(&self, f: impl FnOnce(&ModelContainer) -> R) -> Option<R> {
909        self.container.upgrade().map(|inner| {
910            let c = ModelContainer { inner };
911            f(&c)
912        })
913    }
914
915    /// The members `key` holds, read from whichever side `forward` names: A→B forward, B→A
916    /// reverse. One indexed `SELECT` on first read, memoized, overlaid with this turn's
917    /// unflushed links and unlinks.
918    pub(crate) fn members_of(&self, key: u64, forward: bool) -> Vec<u64> {
919        {
920            let memo = if forward {
921                &self.memo_fwd
922            } else {
923                &self.memo_rev
924            };
925            if let Some(hit) = memo.borrow().get(&key) {
926                return hit.clone();
927            }
928        }
929        // A row deleted this turn holds no memberships, whatever the file says until the flush.
930        let own_store = if forward { self.a_store } else { self.b_store };
931        if self.with_container(|c| c.dirty_state_of(own_store, key)) == Some(Some(DirtyRow::Delete))
932        {
933            return Vec::new();
934        }
935        self.members_of_raw(key, forward)
936    }
937
938    /// `members_of` without the deleted-row shortcut: what a deletion's own upkeep reads.
939    fn members_of_raw(&self, key: u64, forward: bool) -> Vec<u64> {
940        let (own_col, other_col) = if forward {
941            (self.parent_col, self.child_col)
942        } else {
943            (self.child_col, self.parent_col)
944        };
945        let (other_col, own_col) = (ident(other_col), ident(own_col));
946        let order = if self.ordered && forward {
947            format!("position, {other_col}")
948        } else {
949            other_col.clone()
950        };
951        let Some(mut ids) = self.with_container(|c| {
952            c.select_id_column(
953                &format!(
954                    "SELECT {other_col} FROM {t} WHERE {own_col} = ? ORDER BY {order}",
955                    t = self.join_sql,
956                ),
957                &[key_param(key)],
958            )
959        }) else {
960            return Vec::new();
961        };
962        self.overlay_members(key, forward, &mut ids);
963        let memo = if forward {
964            &self.memo_fwd
965        } else {
966            &self.memo_rev
967        };
968        memo.borrow_mut().insert(key, ids.clone());
969        ids
970    }
971
972    /// Correct a freshly-selected member list against this turn's unflushed link/unlink rows.
973    fn overlay_members(&self, key: u64, forward: bool, ids: &mut Vec<u64>) {
974        // Members whose own row is leaving this turn leave the list now; the engine takes
975        // their membership rows in the flush.
976        let other_store = if forward { self.b_store } else { self.a_store };
977        ids.retain(|id| {
978            self.with_container(|c| c.dirty_state_of(other_store, *id))
979                != Some(Some(DirtyRow::Delete))
980        });
981        let Some(dirty) = self.with_container(|c| c.dirty_rows_of(self.join_store)) else {
982            return;
983        };
984        for (handle, state) in dirty {
985            let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) else {
986                continue;
987            };
988            let (own, other) = if forward { (p, c) } else { (c, p) };
989            if own != key {
990                continue;
991            }
992            let at = ids.iter().position(|m| *m == other);
993            let other_deleted = self.with_container(|c| c.dirty_state_of(other_store, other))
994                == Some(Some(DirtyRow::Delete));
995            match (state != DirtyRow::Delete && !other_deleted, at) {
996                (false, Some(i)) => {
997                    ids.remove(i);
998                }
999                (true, None) => {
1000                    if self.ordered && forward {
1001                        let pos = self.position_of(p, c);
1002                        let at = ids
1003                            .iter()
1004                            .position(|m| self.position_of(key, *m) > pos)
1005                            .unwrap_or(ids.len());
1006                        ids.insert(at, other);
1007                    } else {
1008                        let at = ids.partition_point(|m| *m < other);
1009                        ids.insert(at, other);
1010                    }
1011                }
1012                _ => {}
1013            }
1014        }
1015    }
1016
1017    /// The rows on the other side that hold `key`: the join's back-resolution.
1018    pub(crate) fn holders_of(&self, key: u64, forward: bool) -> Vec<u64> {
1019        // Looking back from a B row means asking the reverse direction, and vice versa.
1020        self.members_of(key, !forward)
1021    }
1022
1023    pub(crate) fn position_of(&self, parent: u64, child: u64) -> f64 {
1024        let cached = self.store.with_untracked(|k| {
1025            k.get(day_model::Key::Pair(parent, child).handle())
1026                .map(|r| r.position)
1027        });
1028        if let Some(p) = cached {
1029            return p;
1030        }
1031        if !self.ordered {
1032            return 0.0;
1033        }
1034        self.with_container(|c| {
1035            c.select_real(
1036                &format!(
1037                    "SELECT position FROM {t} WHERE {pc} = ? AND {cc} = ?",
1038                    t = self.join_sql,
1039                    pc = ident(self.parent_col),
1040                    cc = ident(self.child_col),
1041                ),
1042                &[key_param(parent), key_param(child)],
1043            )
1044        })
1045        .flatten()
1046        .unwrap_or(0.0)
1047    }
1048
1049    /// Whether the pair is currently a membership: the cache, the dirty set, or the file.
1050    fn is_member(&self, parent: u64, child: u64) -> bool {
1051        let handle = day_model::Key::Pair(parent, child).handle();
1052        if let Some(state) = self.with_container(|c| c.dirty_state_of(self.join_store, handle))
1053            && let Some(state) = state
1054        {
1055            return state != DirtyRow::Delete;
1056        }
1057        if self.store.with_untracked(|k| k.get(handle).is_some()) {
1058            return true;
1059        }
1060        // A row inserted this turn has no memberships in the file yet, so the dirty and
1061        // resident checks above were the whole answer: no probe for a brand-new parent or
1062        // child, which is what a seed or a "create with tags" does.
1063        let fresh = self.with_container(|c| {
1064            c.dirty_state_of(self.a_store, parent) == Some(DirtyRow::Insert)
1065                || c.dirty_state_of(self.b_store, child) == Some(DirtyRow::Insert)
1066        });
1067        if fresh == Some(true) {
1068            return false;
1069        }
1070        self.with_container(|c| {
1071            !c.select_id_column(
1072                &format!(
1073                    "SELECT 1 FROM {t} WHERE {pc} = ? AND {cc} = ?",
1074                    t = self.join_sql,
1075                    pc = ident(self.parent_col),
1076                    cc = ident(self.child_col),
1077                ),
1078                &[key_param(parent), key_param(child)],
1079            )
1080            .is_empty()
1081        })
1082        .unwrap_or(false)
1083    }
1084
1085    /// Wake both sides' readers: a membership change moves `a.field()` and `b.field()` alike.
1086    fn announce_pair(&self, parent: u64, child: u64) {
1087        announce(
1088            &[self.a_store, parent, field_id(self.a_field)],
1089            self.a_field,
1090        );
1091        if let Some(bf) = self.b_field.get() {
1092            announce(&[self.b_store, child, field_id(bf)], bf);
1093        }
1094    }
1095
1096    fn forget_pair(&self, parent: u64, child: u64) {
1097        self.memo_fwd.borrow_mut().remove(&parent);
1098        self.memo_rev.borrow_mut().remove(&child);
1099    }
1100
1101    pub(crate) fn invalidate_all(&self) {
1102        self.memo_fwd.borrow_mut().clear();
1103        self.memo_rev.borrow_mut().clear();
1104    }
1105
1106    /// A join row arrived (an `add`, an undo's re-insert, an external merge).
1107    pub(crate) fn row_added(&self, handle: u64) {
1108        if let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) {
1109            self.forget_pair(p, c);
1110            self.announce_pair(p, c);
1111        }
1112    }
1113
1114    pub(crate) fn row_removed(&self, handle: u64) {
1115        if let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) {
1116            self.forget_pair(p, c);
1117            self.announce_pair(p, c);
1118        }
1119    }
1120
1121    /// A membership's position moved: reposition and wake both sides.
1122    pub(crate) fn row_moved(&self, handle: u64) {
1123        if let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) {
1124            self.forget_pair(p, c);
1125            self.announce_pair(p, c);
1126        }
1127    }
1128
1129    /// Either side's row was deleted: its memberships go with it, and under that side's own
1130    /// cascade rule so do the rows across the join that nobody else still holds.
1131    /// Drop the memos a deleted row appears in: its own list, and the counterparts' lists
1132    /// that name it.
1133    fn forget_side(&self, is_a: bool, key: u64) {
1134        let (own, others) = if is_a {
1135            (&self.memo_fwd, &self.memo_rev)
1136        } else {
1137            (&self.memo_rev, &self.memo_fwd)
1138        };
1139        own.borrow_mut().remove(&key);
1140        others
1141            .borrow_mut()
1142            .retain(|_, members| !members.contains(&key));
1143    }
1144
1145    pub(crate) fn side_deleted(&self, is_a: bool, key: u64) {
1146        let engine = self
1147            .with_container(super::ModelContainer::engine_cascade_allowed)
1148            .unwrap_or(false);
1149        let rule = if is_a {
1150            self.a_delete
1151        } else {
1152            self.b_delete.get()
1153        };
1154        if engine {
1155            // The join table's foreign keys cascade in the engine: the memberships leave
1156            // with the row, in the flush, and the join rows resident here are re-read after
1157            // it. Only the cascade rule's counterpart deletes still need the member list.
1158            self.forget_side(is_a, key);
1159            self.with_container(|c| c.note_engine_cascade(self.join_table));
1160            if rule != DeleteRule::Cascade {
1161                return;
1162            }
1163        }
1164        let others = self.members_of_raw(key, is_a);
1165        if others.is_empty() {
1166            return;
1167        }
1168        // In process (an undo stack or a transaction participant is watching): each
1169        // membership leaves through the pipeline, so both see it go.
1170        let capture = day_model::record_capture_active();
1171        for other in others.iter().filter(|_| !engine) {
1172            let (p, c) = if is_a { (key, *other) } else { (*other, key) };
1173            let handle = day_model::Key::Pair(p, c).handle();
1174            if capture && self.store.with_untracked(|k| k.get(handle).is_none()) {
1175                // Materialize the membership so its delete carries what undo inversion
1176                // needs: the pair is known; only an ordered position needs the file.
1177                let position = self.position_of(p, c);
1178                self.store.populate(vec![JoinRow {
1179                    parent: p,
1180                    child: c,
1181                    position,
1182                }]);
1183            }
1184            self.store.restructure("unlink", Op::Delete, handle, |k| {
1185                k.remove(handle);
1186            });
1187        }
1188        if rule == DeleteRule::Cascade {
1189            // Cascade across a join takes the rows this one held, but only those no other
1190            // row still holds, or deleting one album would take a shared photo with it.
1191            // (`forward` here is the deleted side's perspective: the counterpart's holders
1192            // are read from the opposite index.)
1193            for other in others {
1194                let holders = self.holders_of(other, is_a);
1195                let still_held = holders.iter().any(|h| *h != key);
1196                if !still_held {
1197                    if is_a {
1198                        (self.delete_b)(other);
1199                    } else {
1200                        (self.delete_a)(other);
1201                    }
1202                }
1203            }
1204        }
1205    }
1206
1207    fn link(&self, parent: u64, child: u64, position: f64) -> bool {
1208        if self.is_member(parent, child) {
1209            return false; // already a member; membership is a set
1210        }
1211        let handle = day_model::Key::Pair(parent, child).handle();
1212        self.store.restructure("link", Op::Insert, handle, |k| {
1213            k.push(JoinRow {
1214                parent,
1215                child,
1216                position,
1217            });
1218        });
1219        true
1220    }
1221
1222    fn unlink(&self, parent: u64, child: u64) -> bool {
1223        if !self.is_member(parent, child) {
1224            return false;
1225        }
1226        let handle = day_model::Key::Pair(parent, child).handle();
1227        if day_model::record_capture_active()
1228            && self.store.with_untracked(|k| k.get(handle).is_none())
1229        {
1230            let position = self.position_of(parent, child);
1231            self.store.populate(vec![JoinRow {
1232                parent,
1233                child,
1234                position,
1235            }]);
1236        }
1237        self.store.restructure("unlink", Op::Delete, handle, |k| {
1238            k.remove(handle);
1239        });
1240        true
1241    }
1242}
1243
1244/// Wire one many-to-many; called from the derive-generated `Model::wire`.
1245pub fn wire_join<P: Model, C: Model>(
1246    reg: &mut Registrar<'_>,
1247    field: &'static str,
1248    join_table: &'static str,
1249    ordered: Option<&'static str>,
1250    delete: DeleteRule,
1251) {
1252    let container = reg.container.clone();
1253    let (Some(parent_store), Some(child_store)) =
1254        (container.try_cache::<P>(), container.try_cache::<C>())
1255    else {
1256        reg.fail(format!(
1257            "relation `{}.{field}` targets `{}`, which is not in this container's schema!",
1258            P::TABLE,
1259            C::TABLE
1260        ));
1261        return;
1262    };
1263
1264    // The other side already wired this table: attach as its B side (one relation, one
1265    // store, both directions) rather than opening a second store over the same rows.
1266    {
1267        let joins = container.inner.joins.borrow();
1268        if let Some(existing) = joins.iter().find(|j| j.join_table == join_table) {
1269            let ok = existing.a_store == child_store.store_id()
1270                && existing.b_store == parent_store.store_id();
1271            if !ok {
1272                let msg = format!(
1273                    "join table `{join_table}` is declared by `{}.{field}` and by another \
1274                     relation over different models — a join table belongs to exactly one pair",
1275                    P::TABLE
1276                );
1277                drop(joins);
1278                reg.fail(msg);
1279                return;
1280            }
1281            if existing.b_field.get().is_some() {
1282                let msg = format!(
1283                    "join table `{join_table}` is declared twice on `{}` — one field per side",
1284                    P::TABLE
1285                );
1286                drop(joins);
1287                reg.fail(msg);
1288                return;
1289            }
1290            if ordered.is_some() && !existing.ordered {
1291                let msg = format!(
1292                    "relation `{}.{field}` asks for order, but `{join_table}`'s other side \
1293                     declared it unordered — a membership has ONE position, so order is \
1294                     declared on one side only",
1295                    P::TABLE
1296                );
1297                drop(joins);
1298                reg.fail(msg);
1299                return;
1300            }
1301            existing.b_field.set(Some(field));
1302            existing.b_delete.set(delete);
1303            return;
1304        }
1305    }
1306
1307    if ordered.is_some_and(|o| o != "position") {
1308        reg.fail(format!(
1309            "relation `{}.{field}` is a join relation: its order lives on the join row, so \
1310             `ordered` takes no field name (a child can sit at different positions under \
1311             different parents)",
1312            P::TABLE
1313        ));
1314        return;
1315    }
1316    let ordered = ordered.is_some();
1317
1318    // Column names are derived and documented: the singular of each table, `_id`-suffixed.
1319    let parent_col: &'static str = Box::leak(format!("{}_id", singular(P::TABLE)).into_boxed_str());
1320    let child_col: &'static str = Box::leak(format!("{}_id", singular(C::TABLE)).into_boxed_str());
1321    if parent_col == child_col {
1322        reg.fail(format!(
1323            "relation `{}.{field}`: a self-join needs distinct column names, which the \
1324             derived `{parent_col}` pair cannot give",
1325            P::TABLE
1326        ));
1327        return;
1328    }
1329
1330    if let Err(e) =
1331        container.ensure_join_table::<P, C>(join_table, parent_col, child_col, ordered, delete)
1332    {
1333        reg.error.get_or_insert(e);
1334        return;
1335    }
1336
1337    // The membership cache starts empty; memberships fault through the memos on read and
1338    // enter through link/unlink on write; the file is never read whole.
1339    let store = Store::new(Keyed::new(Vec::new()));
1340    let delete_a = Box::new(move |h: u64| {
1341        parent_store.restructure("cascade", Op::Delete, h, |k| {
1342            k.remove(h);
1343        });
1344    });
1345    let delete_b = Box::new(move |h: u64| {
1346        child_store.restructure("cascade", Op::Delete, h, |k| {
1347            k.remove(h);
1348        });
1349    });
1350    let rel = Rc::new(JoinRel {
1351        container: Rc::downgrade(&container.inner),
1352        join_table,
1353        join_sql: ident(join_table),
1354        parent_col,
1355        child_col,
1356        a_store: parent_store.store_id(),
1357        a_table: P::TABLE,
1358        a_field: field,
1359        a_key_col: P::KEY,
1360        a_delete: delete,
1361        b_store: child_store.store_id(),
1362        b_table: C::TABLE,
1363        b_key_col: C::KEY,
1364        b_field: Cell::new(None),
1365        b_delete: Cell::new(DeleteRule::Nullify),
1366        join_store: store.store_id(),
1367        ordered,
1368        store,
1369        delete_a,
1370        delete_b,
1371        memo_fwd: RefCell::new(HashMap::new()),
1372        memo_rev: RefCell::new(HashMap::new()),
1373    });
1374
1375    container.register_join_hooks(join_table, parent_col, child_col, ordered, store);
1376    container.inner.joins.borrow_mut().push(rel);
1377}
1378
1379/// `trips` → `trip`, `boxes` → `box`, `categories` → `category`: the join column's stem.
1380fn singular(table: &str) -> String {
1381    if let Some(stem) = table.strip_suffix("ies") {
1382        return format!("{stem}y");
1383    }
1384    for suffix in ["ses", "xes", "zes", "ches", "shes"] {
1385        if let Some(stem) = table.strip_suffix(suffix) {
1386            return format!("{stem}{}", &suffix[..suffix.len() - 2]);
1387        }
1388    }
1389    table.strip_suffix('s').unwrap_or(table).to_string()
1390}
1391
1392// ---------------------------------------------------------------------------
1393// The accessor surface
1394// ---------------------------------------------------------------------------
1395
1396day_reactive::tls_group! {
1397    /// Every open container, so a `RelationRef` (which holds only a Field) can find the
1398    /// relation its parent store belongs to. Weak: dropping the container is the removal.
1399    static CONTAINERS: RefCell<Vec<Weak<ContainerInner>>> = const { RefCell::new(Vec::new()) };
1400
1401}
1402
1403/// The open container whose tables include `store`, for an accessor that holds only a
1404/// field (a [`crate::Blob`]'s reads).
1405pub(crate) fn container_for_store(store: u64) -> Option<ModelContainer> {
1406    CONTAINERS.with(|c| {
1407        c.borrow()
1408            .iter()
1409            .filter_map(Weak::upgrade)
1410            .find(|inner| inner.tables.borrow().contains_key(&store))
1411            .map(|inner| ModelContainer { inner })
1412    })
1413}
1414
1415pub(crate) fn register_container(inner: &Rc<ContainerInner>) {
1416    CONTAINERS.with(|c| {
1417        let mut v = c.borrow_mut();
1418        v.retain(|w| w.strong_count() > 0);
1419        v.push(Rc::downgrade(inner));
1420    });
1421}
1422
1423/// A resolved relation, either shape, and for a join, which end asked (`forward` is the A
1424/// side, the one whose declaration created the table).
1425enum Wired {
1426    ToOne(Rc<ToOneRel>),
1427    Join(Rc<JoinRel>, bool),
1428}
1429
1430fn find_relation(parent_store: u64, field: &str) -> Option<Wired> {
1431    CONTAINERS.with(|c| {
1432        c.borrow()
1433            .iter()
1434            .filter_map(Weak::upgrade)
1435            .find_map(|inner| {
1436                if let Some(r) = inner
1437                    .relations
1438                    .borrow()
1439                    .iter()
1440                    .find(|r| r.parent_store == parent_store && r.parent_field == field)
1441                {
1442                    return Some(Wired::ToOne(r.clone()));
1443                }
1444                inner.joins.borrow().iter().find_map(|r| {
1445                    if r.a_store == parent_store && r.a_field == field {
1446                        Some(Wired::Join(r.clone(), true))
1447                    } else if r.b_store == parent_store && r.b_field.get() == Some(field) {
1448                        Some(Wired::Join(r.clone(), false))
1449                    } else {
1450                        None
1451                    }
1452                })
1453            })
1454    })
1455}
1456
1457/// Bring a set of rows into the cache: what a relation write does before it writes.
1458type Materialize = Box<dyn Fn(&[u64])>;
1459
1460/// Read one row's order value by handle; write it back. The pair is what an ordered relation
1461/// needs, whichever shape holds the order (a child's field, or a membership's position).
1462type ReadOrder = Box<dyn Fn(u64) -> f64>;
1463type WriteOrder = Box<dyn Fn(u64, f64) -> bool>;
1464
1465/// What placing one row inside an ordered relation needs, resolved from whichever shape holds
1466/// the order.
1467struct Placement {
1468    ordered: bool,
1469    read_ord: ReadOrder,
1470    write_ord: WriteOrder,
1471    is_member: bool,
1472}
1473
1474/// What the generated accessor for a `Many` field returns: the relation, addressed from one
1475/// parent. Reads are tracked through the parent's field path (membership changes wake
1476/// exactly the readers of this parent's relation), and writes go through the children's
1477/// foreign keys, where membership is stored.
1478pub struct RelationRef<S: Copy + 'static, P: 'static, T: 'static> {
1479    field: day_model::Field<S, P, Many<T>>,
1480}
1481
1482impl<S: Copy + 'static, P: 'static, T: 'static> Clone for RelationRef<S, P, T> {
1483    fn clone(&self) -> Self {
1484        *self
1485    }
1486}
1487impl<S: Copy + 'static, P: 'static, T: 'static> Copy for RelationRef<S, P, T> {}
1488
1489impl<S: day_model::Source<P>, P: 'static, T: 'static> RelationRef<S, P, T> {
1490    pub fn new(field: day_model::Field<S, P, Many<T>>) -> Self {
1491        RelationRef { field }
1492    }
1493
1494    fn resolve(&self) -> Option<(Wired, u64)> {
1495        let mut parts = Vec::new();
1496        day_model::Source::components(self.field, &mut parts);
1497        if parts.len() < 2 {
1498            return None;
1499        }
1500        find_relation(parts[0], self.field.label()).map(|r| (r, parts[1]))
1501    }
1502
1503    /// The children this parent holds, in relation order.
1504    fn members(&self) -> Vec<u64> {
1505        match self.resolve() {
1506            Some((Wired::ToOne(r), p)) => r.children_of(p),
1507            Some((Wired::Join(r, forward), p)) => r.members_of(p, forward),
1508            None => Vec::new(),
1509        }
1510    }
1511
1512    /// The children's ids, in relation order, tracked: the caller re-runs when membership
1513    /// (or order) changes, and not when a child's other fields do.
1514    pub fn ids(&self) -> Vec<ModelId<T>> {
1515        self.field.with(|_| ());
1516        self.members()
1517            .into_iter()
1518            .map(ModelId::from_handle)
1519            .collect()
1520    }
1521
1522    /// The count, tracked like [`RelationRef::ids`].
1523    pub fn count(&self) -> usize {
1524        self.field.with(|_| ());
1525        self.members().len()
1526    }
1527
1528    pub fn is_empty(&self) -> bool {
1529        self.count() == 0
1530    }
1531
1532    /// Tracked membership test.
1533    pub fn contains(&self, id: impl Into<ModelId<T>>) -> bool {
1534        let h = id.into().handle();
1535        self.field.with(|_| ());
1536        self.members().contains(&h)
1537    }
1538
1539    /// Take `child` into this relation by writing its foreign key (reparenting it away from
1540    /// any previous parent, whose readers wake too). On an ordered relation the child lands
1541    /// last, its order field written past the current end. Returns false when the relation
1542    /// is unwired or the child is gone.
1543    pub fn add(&self, child: impl Into<ModelId<T>>) -> bool {
1544        let h = child.into().handle();
1545        match self.resolve() {
1546            Some((Wired::ToOne(r), parent)) => {
1547                if !r.set_fk(h, Some(parent)) {
1548                    return false;
1549                }
1550                if r.ordered.is_some() {
1551                    let last = r
1552                        .children_of(parent)
1553                        .iter()
1554                        .filter(|c| **c != h)
1555                        .map(|c| r.read_order(*c))
1556                        .fold(f64::NEG_INFINITY, f64::max);
1557                    let next = if last.is_finite() { last + 1.0 } else { 1.0 };
1558                    (r.write_ord)(h, next);
1559                }
1560                true
1561            }
1562            Some((Wired::Join(r, forward), key)) => {
1563                // Whichever end asked, the stored pair is always (A, B).
1564                let (a, b) = if forward { (key, h) } else { (h, key) };
1565                let next = if r.ordered {
1566                    let last = r
1567                        .members_of(a, true)
1568                        .iter()
1569                        .map(|c| r.position_of(a, *c))
1570                        .fold(f64::NEG_INFINITY, f64::max);
1571                    if last.is_finite() { last + 1.0 } else { 1.0 }
1572                } else {
1573                    0.0
1574                };
1575                r.link(a, b, next)
1576            }
1577            None => false,
1578        }
1579    }
1580
1581    /// Ordered relations: place `child` at `index` among the current children, normally one
1582    /// write of the child's order field (fractional keying), plus the adopt when it was not
1583    /// yet this parent's. When the gap between neighbors has bisected away, the siblings
1584    /// rebalance to whole numbers first (O(n), rare, and every write still takes the front
1585    /// door). Returns false on an unordered or unwired relation.
1586    pub fn insert_at(&self, child: impl Into<ModelId<T>>, index: usize) -> bool {
1587        let h = child.into().handle();
1588        let Some((wired, parent)) = self.resolve() else {
1589            return false;
1590        };
1591        // Read the neighbors' order values, place between them, and write one row, whichever
1592        // shape holds the order (the child's field, or the membership's position).
1593        let Placement {
1594            ordered,
1595            read_ord,
1596            write_ord,
1597            is_member,
1598        } = match &wired {
1599            Wired::ToOne(r) => {
1600                let (r1, r2) = (r.clone(), r.clone());
1601                Placement {
1602                    ordered: r.ordered.is_some(),
1603                    read_ord: Box::new(move |c| r1.read_order(c)),
1604                    write_ord: Box::new(move |c, v| {
1605                        (r2.materialize)(&[c]);
1606                        (r2.write_ord)(c, v)
1607                    }),
1608                    is_member: r.parent_of(h) == Some(parent) && {
1609                        // `parent_of` answers from the file too; membership here means the
1610                        // Current truth, which children_of's overlay establishes.
1611                        r.children_of(parent).contains(&h)
1612                    },
1613                }
1614            }
1615            Wired::Join(r, forward) => {
1616                let (r1, r2) = (r.clone(), r.clone());
1617                Placement {
1618                    // Order belongs to the A side: a membership's position places a B row
1619                    // within one A row, so the reverse view has no order to write.
1620                    ordered: r.ordered && *forward,
1621                    read_ord: Box::new(move |c| r1.position_of(parent, c)),
1622                    write_ord: Box::new(move |c, v| {
1623                        let handle = day_model::Key::Pair(parent, c).handle();
1624                        if r2.store.with_untracked(|k| k.get(handle).is_none()) {
1625                            let position = r2.position_of(parent, c);
1626                            r2.store.populate(vec![JoinRow {
1627                                parent,
1628                                child: c,
1629                                position,
1630                            }]);
1631                        }
1632                        r2.store.write_field(handle, "position", v)
1633                    }),
1634                    is_member: r.members_of(parent, *forward).contains(&h),
1635                }
1636            }
1637        };
1638        if !ordered {
1639            return false;
1640        }
1641        if !is_member && !self.add(ModelId::<T>::from_handle(h)) {
1642            return false;
1643        }
1644        let siblings: Vec<u64> = match &wired {
1645            Wired::ToOne(r) => r.children_of(parent),
1646            Wired::Join(r, forward) => r.members_of(parent, *forward),
1647        }
1648        .into_iter()
1649        .filter(|c| *c != h)
1650        .collect();
1651        let index = index.min(siblings.len());
1652        let prev = index.checked_sub(1).and_then(|i| siblings.get(i).copied());
1653        let next = siblings.get(index).copied();
1654        let ord = match (prev.map(&read_ord), next.map(&read_ord)) {
1655            (None, None) => 1.0,
1656            (Some(a), None) => a + 1.0,
1657            (None, Some(b)) => b - 1.0,
1658            (Some(a), Some(b)) => {
1659                let mid = a + (b - a) / 2.0;
1660                if mid > a && mid < b {
1661                    mid
1662                } else {
1663                    // The gap is spent: rebalance the siblings to whole numbers, then the
1664                    // target slot's midpoint is roomy again.
1665                    for (i, c) in siblings.iter().enumerate() {
1666                        write_ord(*c, (i + 1) as f64);
1667                    }
1668                    index as f64 + 0.5
1669                }
1670            }
1671        };
1672        write_ord(h, ord)
1673    }
1674
1675    /// Move an existing child to `index`: [`RelationRef::insert_at`], reading as intent.
1676    pub fn move_to(&self, child: impl Into<ModelId<T>>, index: usize) -> bool {
1677        self.insert_at(child, index)
1678    }
1679
1680    /// Clear `child`'s reference; it leaves this relation and belongs to no parent. On a
1681    /// required (`One<…>`, non-`Option`) inverse the cleared reference is a constraint
1682    /// violation at flush: reparent or delete the child instead.
1683    pub fn remove(&self, child: impl Into<ModelId<T>>) -> bool {
1684        let h = child.into().handle();
1685        match self.resolve() {
1686            Some((Wired::ToOne(r), p)) => {
1687                if !r.children_of(p).contains(&h) {
1688                    return false; // not this parent's child
1689                }
1690                r.set_fk(h, None)
1691            }
1692            Some((Wired::Join(r, forward), key)) => {
1693                let (a, b) = if forward { (key, h) } else { (h, key) };
1694                r.unlink(a, b)
1695            }
1696            None => false,
1697        }
1698    }
1699
1700    /// [`RelationRef::remove`] for every current child.
1701    pub fn clear(&self) {
1702        match self.resolve() {
1703            Some((Wired::ToOne(r), p)) => {
1704                let children = r.children_of(p);
1705                (r.materialize)(&children);
1706                for child in children {
1707                    (r.write_fk)(child, None);
1708                }
1709            }
1710            Some((Wired::Join(r, forward), key)) => {
1711                for other in r.members_of(key, forward) {
1712                    let (a, b) = if forward { (key, other) } else { (other, key) };
1713                    r.unlink(a, b);
1714                }
1715            }
1716            None => {}
1717        }
1718    }
1719}
1720
1721// ---------------------------------------------------------------------------
1722// Container-side dispatch
1723// ---------------------------------------------------------------------------
1724
1725impl ModelContainer {
1726    /// Route one announced change into relation maintenance. Called from the change sink,
1727    /// After dirty-marking and query staleness; the writes it makes (cascades, nullifies)
1728    /// nest through the same pipeline.
1729    pub(crate) fn relations_on_change(&self, change: &day_model::Change) {
1730        let Some(&store) = change.components.first() else {
1731            return;
1732        };
1733        if self.inner.relations.borrow().is_empty() && self.inner.joins.borrow().is_empty() {
1734            return;
1735        }
1736        let rels: Vec<Rc<ToOneRel>> = self.inner.relations.borrow().iter().cloned().collect();
1737        for rel in rels {
1738            if rel.child_store == store {
1739                match (change.components.get(1).copied(), change.op) {
1740                    (Some(k), _) if k == day_model::STRUCTURE => {}
1741                    (Some(child), Op::Set) if change.components.len() >= 3 => {
1742                        if change.label == rel.fk_field {
1743                            rel.reparent(child);
1744                        } else if Some(change.label) == rel.ordered {
1745                            rel.order_changed(child);
1746                        }
1747                    }
1748                    (Some(child), Op::Insert) if change.components.len() == 2 => {
1749                        rel.child_added(child);
1750                    }
1751                    (Some(child), Op::Delete) if change.components.len() == 2 => {
1752                        rel.child_removed(child);
1753                    }
1754                    _ => {}
1755                }
1756            }
1757            if rel.parent_store == store
1758                && change.components.len() == 2
1759                && change.op == Op::Delete
1760                && change.components[1] != day_model::STRUCTURE
1761            {
1762                rel.parent_deleted(self, change.components[1]);
1763            }
1764        }
1765
1766        let joins: Vec<Rc<JoinRel>> = self.inner.joins.borrow().iter().cloned().collect();
1767        for rel in joins {
1768            let Some(&key) = change.components.get(1) else {
1769                continue;
1770            };
1771            if key == day_model::STRUCTURE {
1772                continue;
1773            }
1774            if rel.join_store == store {
1775                match change.op {
1776                    Op::Insert if change.components.len() == 2 => rel.row_added(key),
1777                    Op::Delete if change.components.len() == 2 => rel.row_removed(key),
1778                    Op::Set if change.components.len() >= 3 && change.label == "position" => {
1779                        rel.row_moved(key);
1780                    }
1781                    _ => {}
1782                }
1783            }
1784            // Either side's deletion drops its memberships (and, under cascade from the
1785            // parent side, the children no other parent still holds).
1786            if change.op == Op::Delete && change.components.len() == 2 {
1787                if rel.a_store == store {
1788                    rel.side_deleted(true, key);
1789                } else if rel.b_store == store {
1790                    rel.side_deleted(false, key);
1791                }
1792            }
1793        }
1794    }
1795
1796    /// Drop every relation memo: the external-change and rescan reset.
1797    pub(crate) fn invalidate_relation_memos(&self) {
1798        for r in self.inner.relations.borrow().iter() {
1799            r.invalidate_all();
1800        }
1801        for j in self.inner.joins.borrow().iter() {
1802            j.invalidate_all();
1803        }
1804    }
1805
1806    /// Drop the memos of every relation with an end (or, for a many-to-many, its join
1807    /// table) in `tables`: what a table-scoped refresh invalidates.
1808    pub(crate) fn invalidate_relation_memos_of(&self, tables: &[&'static str]) {
1809        for r in self.inner.relations.borrow().iter() {
1810            if tables.contains(&r.parent_table) || tables.contains(&r.child_table) {
1811                r.invalidate_all();
1812            }
1813        }
1814        for j in self.inner.joins.borrow().iter() {
1815            if tables.contains(&j.join_table)
1816                || tables.contains(&j.a_table)
1817                || tables.contains(&j.b_table)
1818            {
1819                j.invalidate_all();
1820            }
1821        }
1822    }
1823
1824    /// The cache for `M` when it is in this container's schema: the non-panicking
1825    /// [`ModelContainer::cache`].
1826    pub fn try_cache<M: Model>(&self) -> Option<Store<Keyed<M>>> {
1827        self.inner
1828            .stores
1829            .borrow()
1830            .get(&std::any::TypeId::of::<M>())
1831            .and_then(|a| a.downcast_ref::<Store<Keyed<M>>>())
1832            .copied()
1833    }
1834
1835    /// Delete one row, honoring deny rules: a parent still referenced through a
1836    /// `DeleteRule::Deny` relation is refused with the relation named. Cascade and nullify
1837    /// need no checked door (a plain `restructure` delete triggers them), but deny cannot
1838    /// refuse after the row is gone, so this is deny's contract.
1839    ///
1840    /// # Errors
1841    /// Returns a `Deny` error naming the relation when a deny rule still references the row, or the
1842    /// storage error when the check cannot read the file.
1843    pub fn delete<M: Model>(&self, id: impl Into<ModelId<M>>) -> Result<(), DbError> {
1844        let h = id.into().handle();
1845        let store = self.cache::<M>();
1846        let rels: Vec<Rc<ToOneRel>> = self.inner.relations.borrow().iter().cloned().collect();
1847        for r in rels
1848            .iter()
1849            .filter(|r| r.parent_store == store.store_id() && r.delete == DeleteRule::Deny)
1850        {
1851            let n = r.children_of(h).len();
1852            if n > 0 {
1853                return Err(DbError::new(
1854                    DbErrorKind::Deny,
1855                    format!(
1856                        "`{}` row still referenced by {n} `{}` row(s) through `{}` — \
1857                         delete or reparent them first",
1858                        M::TABLE,
1859                        r.fk_field,
1860                        r.parent_field
1861                    ),
1862                ));
1863            }
1864        }
1865        let joins: Vec<Rc<JoinRel>> = self.inner.joins.borrow().iter().cloned().collect();
1866        for r in joins.iter().filter(|r| {
1867            (r.a_store == store.store_id() && r.a_delete == DeleteRule::Deny)
1868                || (r.b_store == store.store_id() && r.b_delete.get() == DeleteRule::Deny)
1869        }) {
1870            let forward = r.a_store == store.store_id();
1871            let n = r.members_of(h, forward).len();
1872            if n > 0 {
1873                return Err(DbError::new(
1874                    DbErrorKind::Deny,
1875                    format!(
1876                        "`{}` row still holds {n} membership(s) through `{}` — unlink them \
1877                         first",
1878                        M::TABLE,
1879                        if forward {
1880                            r.a_field
1881                        } else {
1882                            r.b_field.get().unwrap_or(r.a_field)
1883                        }
1884                    ),
1885                ));
1886            }
1887        }
1888        // The delete works resident or not (a value-free Delete folds to one statement),
1889        // but an installed undo stack needs the row to invert it.
1890        if day_model::record_capture_active() {
1891            let _ = self.ensure_resident::<M>(&[h]);
1892        }
1893        store.restructure("delete", Op::Delete, h, |k| {
1894            k.remove(h);
1895        });
1896        Ok(())
1897    }
1898
1899    /// Create (once) a generated join table: the pair as the primary key, a foreign key per
1900    /// side with its own delete rule, and an index on the reverse side so the child→parents
1901    /// direction is as cheap as the forward one.
1902    pub(crate) fn ensure_join_table<P: Model, C: Model>(
1903        &self,
1904        table: &str,
1905        parent_col: &str,
1906        child_col: &str,
1907        ordered: bool,
1908        delete: DeleteRule,
1909    ) -> Result<(), DbError> {
1910        // The engine's own rule for the parent side matches the declaration; the child side
1911        // always clears its memberships, because a membership row without its child is
1912        // garbage in any reading of the relation.
1913        let position = if ordered {
1914            ", position REAL NOT NULL"
1915        } else {
1916            ""
1917        };
1918        let index = ident(&format!("day_idx_{table}_{child_col}"));
1919        let (table, parent_col, child_col) = (ident(table), ident(parent_col), ident(child_col));
1920        let body = format!(
1921            "CREATE TABLE IF NOT EXISTS {table} (\
1922             {parent_col} {} NOT NULL REFERENCES {}({}) ON DELETE {} DEFERRABLE INITIALLY DEFERRED, \
1923             {child_col} {} NOT NULL REFERENCES {}({}) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED\
1924             {position}, PRIMARY KEY ({parent_col}, {child_col}))",
1925            P::KEY_SQL.ddl(),
1926            TableName::of::<P>().sql(),
1927            ident(P::KEY),
1928            if delete == DeleteRule::Deny {
1929                "RESTRICT"
1930            } else {
1931                "CASCADE"
1932            },
1933            C::KEY_SQL.ddl(),
1934            TableName::of::<C>().sql(),
1935            ident(C::KEY),
1936        );
1937        if self.conn().execute(&format!("{body} STRICT"), &[]).is_err() {
1938            self.conn().execute(&body, &[])?;
1939        }
1940        self.conn().execute(
1941            &format!("CREATE INDEX IF NOT EXISTS {index} ON {table}({child_col})"),
1942            &[],
1943        )?;
1944        Ok(())
1945    }
1946
1947    /// Give a join store the same table hooks every model store has, so one fold, one
1948    /// external merge and one undo history cover memberships too.
1949    #[expect(
1950        clippy::float_cmp,
1951        reason = "an unchanged check: the old and the new position are compared exactly, as stored"
1952    )]
1953    pub(crate) fn register_join_hooks(
1954        &self,
1955        table: &'static str,
1956        parent_col: &'static str,
1957        child_col: &'static str,
1958        ordered: bool,
1959        store: Store<Keyed<JoinRow>>,
1960    ) {
1961        let mut columns = vec![parent_col.to_string(), child_col.to_string()];
1962        let mut column_names = vec![parent_col, child_col];
1963        let mut fields = vec![parent_col.to_string(), child_col.to_string()];
1964        if ordered {
1965            columns.push("position".into());
1966            column_names.push("position");
1967            fields.push("position".into());
1968        }
1969        let to_row = move |r: &JoinRow| {
1970            let mut v = vec![key_param(r.parent), key_param(r.child)];
1971            if ordered {
1972                v.push(Value::Real(r.position));
1973            }
1974            v
1975        };
1976        let decode = move |r: &Vec<Value>| -> Result<JoinRow, DbError> {
1977            match (
1978                value_to_handle(&Row::get(r, 0)),
1979                value_to_handle(&Row::get(r, 1)),
1980            ) {
1981                (Some(p), Some(c)) => Ok(JoinRow {
1982                    parent: p,
1983                    child: c,
1984                    position: if ordered {
1985                        Row::get(r, 2).as_real().unwrap_or(0.0)
1986                    } else {
1987                        0.0
1988                    },
1989                }),
1990                _ => Err(DbError::new(
1991                    DbErrorKind::Decode,
1992                    format!("`{table}` holds a membership whose ids will not read as keys"),
1993                )),
1994            }
1995        };
1996        let (pc, cc) = (ident(parent_col), ident(child_col));
1997        let hooks = crate::TableHooks {
1998            table,
1999            name: TableName::plain(table),
2000            key_cols: vec![parent_col.to_string(), child_col.to_string()],
2001            key_where: Rc::new(move |h| match day_model::Key::of_handle(h) {
2002                Some(day_model::Key::Pair(p, c)) => (
2003                    format!("{pc} = ? AND {cc} = ?"),
2004                    vec![key_param(p), key_param(c)],
2005                ),
2006                _ => (format!("{pc} IS NULL"), Vec::new()),
2007            }),
2008            columns,
2009            column_names,
2010            fields,
2011            lazy: vec![false; if ordered { 3 } else { 2 }],
2012            settle: Rc::new(|_| Vec::new()),
2013            fts: None,
2014            fts_key: "rowid",
2015            spatial: None,
2016            row_for: Rc::new(move |h| store.with_untracked(|k| k.get(h).map(to_row))),
2017            all_rows: Rc::new(move || {
2018                store.with_untracked(|k| {
2019                    k.items()
2020                        .iter()
2021                        .map(|r| (day_model::Identified::handle(r), to_row(r)))
2022                        .collect()
2023                })
2024            }),
2025            resident_keys: Rc::new(move || store.with_untracked(day_model::Keyed::keys)),
2026            resident_len: Rc::new(move || store.with_untracked(day_model::Keyed::len)),
2027            is_resident: Rc::new(move |h| store.with_untracked(|k| k.get(h).is_some())),
2028            absorb: Rc::new(move |raw| {
2029                let mut rows = Vec::with_capacity(raw.len());
2030                for r in &raw {
2031                    rows.push(decode(r)?);
2032                }
2033                let keys = rows
2034                    .iter()
2035                    .map(day_model::Identified::handle)
2036                    .collect::<Vec<_>>();
2037                store.populate(rows);
2038                Ok(keys)
2039            }),
2040            refresh: Rc::new(move |raw| {
2041                // Memberships are a set: the diff against the resident rows is which pairs
2042                // arrived, moved, or left.
2043                let mut fresh: Vec<JoinRow> = Vec::with_capacity(raw.len());
2044                for r in &raw {
2045                    fresh.push(decode(r)?);
2046                }
2047                let existing: Vec<u64> = store.with_untracked(day_model::Keyed::keys);
2048                let arriving: std::collections::HashSet<u64> =
2049                    fresh.iter().map(day_model::Identified::handle).collect();
2050                let mut changed = false;
2051                day_model::with_author(ModelContainer::EXTERNAL_AUTHOR, || {
2052                    for row in fresh {
2053                        let h = day_model::Identified::handle(&row);
2054                        match store.with_untracked(|k| k.get(h).cloned()) {
2055                            None => {
2056                                changed = true;
2057                                store.restructure("external", Op::Insert, h, |k| k.push(row));
2058                            }
2059                            Some(old) if ordered && old.position != row.position => {
2060                                changed = true;
2061                                store.write_field(h, "position", row.position);
2062                            }
2063                            Some(_) => {}
2064                        }
2065                    }
2066                    for gone in existing.into_iter().filter(|h| !arriving.contains(h)) {
2067                        changed = true;
2068                        store.restructure("external", Op::Delete, gone, |k| {
2069                            k.remove(gone);
2070                        });
2071                    }
2072                });
2073                Ok(changed)
2074            }),
2075            #[cfg(not(target_arch = "wasm32"))]
2076            dispose_cache: Rc::new(move || store.dispose_contents()),
2077            evict: Rc::new(move |candidates, want| {
2078                let doomed: Vec<u64> = candidates
2079                    .iter()
2080                    .copied()
2081                    .filter(|h| !store.is_observed(*h))
2082                    .take(want)
2083                    .collect();
2084                store.depopulate_many(&doomed)
2085            }),
2086            watch_undo: Rc::new(move |stack: &day_model::UndoStack| stack.watch(store)),
2087        };
2088        self.inner
2089            .tables
2090            .borrow_mut()
2091            .insert(store.store_id(), hooks);
2092    }
2093}