1use 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
42pub 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 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 pub fn to(id: impl Into<ModelId<M>>) -> Self {
94 One {
95 id: Some(id.into().handle()),
96 _m: PhantomData,
97 }
98 }
99 pub const fn none() -> Self {
101 One {
102 id: None,
103 _m: PhantomData,
104 }
105 }
106 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 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
147impl<M: Model> crate::Col<One<M>> {
150 pub fn is(self, id: impl Into<ModelId<M>>) -> crate::Pred {
152 self.eq(One::<M>::from_handle(id.into().handle()))
153 }
154
155 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 pub fn is_unset(self) -> crate::Pred {
168 self.is_null()
169 }
170
171 pub fn is_set(self) -> crate::Pred {
173 self.is_not_null()
174 }
175}
176
177impl<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
199impl<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
219impl<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 pub fn is_unset(self) -> crate::Pred {
236 self.is_null()
237 }
238
239 pub fn is_set(self) -> crate::Pred {
241 self.is_not_null()
242 }
243}
244
245pub 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
280pub enum DeleteRule {
281 Nullify,
284 Cascade,
287 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#[derive(Clone, Copy, Debug)]
305pub struct RelationDef {
306 pub field: &'static str,
308 pub target_table: &'static str,
310 pub inverse: &'static str,
312 pub delete: DeleteRule,
313 pub ordered: Option<&'static str>,
315 pub join: Option<&'static str>,
317}
318
319pub 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
338pub(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 pub(crate) child_sql: String,
352 pub(crate) child_key_col: &'static str,
353 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 materialize: Materialize,
364 read_ord_cached: Box<dyn Fn(u64) -> Option<f64>>,
365 pub(crate) write_ord: Box<dyn Fn(u64, f64) -> bool>,
366 memo: RefCell<HashMap<u64, Vec<u64>>>,
368 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 pub(crate) fn children_of(&self, parent: u64) -> Vec<u64> {
384 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 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 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 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 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 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 (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 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 pub(crate) fn child_removed(&self, child: u64) {
547 let memo = self.memo_parent.borrow().get(&child).copied();
548 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 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 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 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 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 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 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 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 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 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
694fn 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
706pub 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#[derive(Clone, Default, PartialEq, Debug)]
838pub(crate) struct JoinRow {
839 pub(crate) parent: u64,
840 pub(crate) child: u64,
841 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
869pub(crate) struct JoinRel {
876 pub(crate) container: Weak<ContainerInner>,
877 pub(crate) join_table: &'static str,
878 pub(crate) join_sql: String,
880 pub(crate) parent_col: &'static str,
881 pub(crate) child_col: &'static str,
882 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 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 pub(crate) ordered: bool,
899 store: Store<Keyed<JoinRow>>,
900 delete_a: Box<dyn Fn(u64)>,
901 delete_b: Box<dyn Fn(u64)>,
902 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 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 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 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 fn overlay_members(&self, key: u64, forward: bool, ids: &mut Vec<u64>) {
974 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 pub(crate) fn holders_of(&self, key: u64, forward: bool) -> Vec<u64> {
1019 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 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 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 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 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 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 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 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 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 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 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; }
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
1244pub 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 {
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 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 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
1379fn 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
1392day_reactive::tls_group! {
1397 static CONTAINERS: RefCell<Vec<Weak<ContainerInner>>> = const { RefCell::new(Vec::new()) };
1400
1401}
1402
1403pub(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
1423enum 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
1457type Materialize = Box<dyn Fn(&[u64])>;
1459
1460type ReadOrder = Box<dyn Fn(u64) -> f64>;
1463type WriteOrder = Box<dyn Fn(u64, f64) -> bool>;
1464
1465struct Placement {
1468 ordered: bool,
1469 read_ord: ReadOrder,
1470 write_ord: WriteOrder,
1471 is_member: bool,
1472}
1473
1474pub 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 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 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 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 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 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 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 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 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 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 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 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 pub fn move_to(&self, child: impl Into<ModelId<T>>, index: usize) -> bool {
1677 self.insert_at(child, index)
1678 }
1679
1680 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; }
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 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
1721impl ModelContainer {
1726 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 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 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 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 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 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 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 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 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 #[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 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}