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(|o| o.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 match C::COLUMNS
752 .iter()
753 .find(|c| c.field == ord && c.sql == SqlType::Real)
754 {
755 Some(c) => ord_col = Some(c.name),
756 None => {
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
768 let read_fk = Box::new(move |h: u64| {
769 child_store.with_untracked(|k| k.get(h).and_then(|c| fk_of::<P, C>(c, inverse)))
770 });
771 let write_fk = Box::new(move |h: u64, parent: Option<u64>| {
772 if child_store.write_field(h, inverse, One::<P>::from_handle_opt(parent)) {
773 return true;
774 }
775 let opt: Option<One<P>> = parent.map(One::<P>::from_handle);
776 child_store.write_field(h, inverse, opt)
777 });
778 let delete_child = Box::new(move |h: u64| {
779 child_store.restructure("cascade", Op::Delete, h, |k| {
780 k.remove(h);
781 });
782 });
783 let mat_container = container.clone();
784 let materialize = Box::new(move |keys: &[u64]| {
785 let _ = mat_container.ensure_resident::<C>(keys);
786 });
787 let read_ord_cached: Box<dyn Fn(u64) -> Option<f64>> = match ordered {
788 Some(ord) => Box::new(move |h| {
789 child_store.with_untracked(|k| {
790 k.get(h)
791 .and_then(|c| ApplyField::read_field(c, ord))
792 .and_then(|v| v.downcast_ref::<f64>().copied())
793 })
794 }),
795 None => Box::new(|_| None),
796 };
797 let write_ord: Box<dyn Fn(u64, f64) -> bool> = match ordered {
798 Some(ord) => Box::new(move |h, v| child_store.write_field(h, ord, v)),
799 None => Box::new(|_, _| false),
800 };
801
802 let rel = Rc::new(ToOneRel {
803 container: Rc::downgrade(&container.inner),
804 parent_store: parent_store.store_id(),
805 parent_table: P::TABLE,
806 parent_field: field,
807 parent_key_col: P::KEY,
808 child_store: child_store.store_id(),
809 child_table: C::TABLE,
810 child_sql: TableName::of::<C>().sql(),
811 child_key_col: C::KEY,
812 fk_field: inverse,
813 fk_col: col.name,
814 delete,
815 ordered,
816 ord_col,
817 read_fk,
818 write_fk,
819 delete_child,
820 materialize,
821 read_ord_cached,
822 write_ord,
823 memo: RefCell::new(HashMap::new()),
824 memo_parent: RefCell::new(HashMap::new()),
825 });
826
827 container.inner.relations.borrow_mut().push(rel);
828}
829
830#[derive(Clone, Default, PartialEq, Debug)]
839pub(crate) struct JoinRow {
840 pub(crate) parent: u64,
841 pub(crate) child: u64,
842 pub(crate) position: f64,
844}
845
846impl day_model::Identified for JoinRow {
847 fn key(&self) -> day_model::Key {
848 day_model::Key::Pair(self.parent, self.child)
849 }
850}
851
852impl ApplyField for JoinRow {
853 fn apply_field(&mut self, label: &str, value: &dyn std::any::Any) -> bool {
854 match (label, value.downcast_ref::<f64>()) {
855 ("position", Some(v)) => {
856 self.position = *v;
857 true
858 }
859 _ => false,
860 }
861 }
862 fn read_field(&self, label: &str) -> Option<Rc<dyn std::any::Any>> {
863 match label {
864 "position" => Some(Rc::new(self.position)),
865 _ => None,
866 }
867 }
868}
869
870pub(crate) struct JoinRel {
877 pub(crate) container: Weak<ContainerInner>,
878 pub(crate) join_table: &'static str,
879 pub(crate) join_sql: String,
881 pub(crate) parent_col: &'static str,
882 pub(crate) child_col: &'static str,
883 pub(crate) a_store: u64,
885 pub(crate) a_table: &'static str,
886 pub(crate) a_field: &'static str,
887 pub(crate) a_key_col: &'static str,
888 pub(crate) a_delete: DeleteRule,
889 pub(crate) b_store: u64,
893 pub(crate) b_table: &'static str,
894 pub(crate) b_key_col: &'static str,
895 pub(crate) b_field: Cell<Option<&'static str>>,
896 pub(crate) b_delete: Cell<DeleteRule>,
897 pub(crate) join_store: u64,
898 pub(crate) ordered: bool,
900 store: Store<Keyed<JoinRow>>,
901 delete_a: Box<dyn Fn(u64)>,
902 delete_b: Box<dyn Fn(u64)>,
903 memo_fwd: RefCell<HashMap<u64, Vec<u64>>>,
905 memo_rev: RefCell<HashMap<u64, Vec<u64>>>,
906}
907
908impl JoinRel {
909 fn with_container<R>(&self, f: impl FnOnce(&ModelContainer) -> R) -> Option<R> {
910 self.container.upgrade().map(|inner| {
911 let c = ModelContainer { inner };
912 f(&c)
913 })
914 }
915
916 pub(crate) fn members_of(&self, key: u64, forward: bool) -> Vec<u64> {
920 {
921 let memo = if forward {
922 &self.memo_fwd
923 } else {
924 &self.memo_rev
925 };
926 if let Some(hit) = memo.borrow().get(&key) {
927 return hit.clone();
928 }
929 }
930 let own_store = if forward { self.a_store } else { self.b_store };
932 if self.with_container(|c| c.dirty_state_of(own_store, key)) == Some(Some(DirtyRow::Delete))
933 {
934 return Vec::new();
935 }
936 self.members_of_raw(key, forward)
937 }
938
939 fn members_of_raw(&self, key: u64, forward: bool) -> Vec<u64> {
941 let (own_col, other_col) = if forward {
942 (self.parent_col, self.child_col)
943 } else {
944 (self.child_col, self.parent_col)
945 };
946 let (other_col, own_col) = (ident(other_col), ident(own_col));
947 let order = if self.ordered && forward {
948 format!("position, {other_col}")
949 } else {
950 other_col.clone()
951 };
952 let Some(mut ids) = self.with_container(|c| {
953 c.select_id_column(
954 &format!(
955 "SELECT {other_col} FROM {t} WHERE {own_col} = ? ORDER BY {order}",
956 t = self.join_sql,
957 ),
958 &[key_param(key)],
959 )
960 }) else {
961 return Vec::new();
962 };
963 self.overlay_members(key, forward, &mut ids);
964 let memo = if forward {
965 &self.memo_fwd
966 } else {
967 &self.memo_rev
968 };
969 memo.borrow_mut().insert(key, ids.clone());
970 ids
971 }
972
973 fn overlay_members(&self, key: u64, forward: bool, ids: &mut Vec<u64>) {
975 let other_store = if forward { self.b_store } else { self.a_store };
978 ids.retain(|id| {
979 self.with_container(|c| c.dirty_state_of(other_store, *id))
980 != Some(Some(DirtyRow::Delete))
981 });
982 let Some(dirty) = self.with_container(|c| c.dirty_rows_of(self.join_store)) else {
983 return;
984 };
985 for (handle, state) in dirty {
986 let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) else {
987 continue;
988 };
989 let (own, other) = if forward { (p, c) } else { (c, p) };
990 if own != key {
991 continue;
992 }
993 let at = ids.iter().position(|m| *m == other);
994 let other_deleted = self.with_container(|c| c.dirty_state_of(other_store, other))
995 == Some(Some(DirtyRow::Delete));
996 match (state != DirtyRow::Delete && !other_deleted, at) {
997 (false, Some(i)) => {
998 ids.remove(i);
999 }
1000 (true, None) => {
1001 if self.ordered && forward {
1002 let pos = self.position_of(p, c);
1003 let at = ids
1004 .iter()
1005 .position(|m| self.position_of(key, *m) > pos)
1006 .unwrap_or(ids.len());
1007 ids.insert(at, other);
1008 } else {
1009 let at = ids.partition_point(|m| *m < other);
1010 ids.insert(at, other);
1011 }
1012 }
1013 _ => {}
1014 }
1015 }
1016 }
1017
1018 pub(crate) fn holders_of(&self, key: u64, forward: bool) -> Vec<u64> {
1020 self.members_of(key, !forward)
1022 }
1023
1024 pub(crate) fn position_of(&self, parent: u64, child: u64) -> f64 {
1025 let cached = self.store.with_untracked(|k| {
1026 k.get(day_model::Key::Pair(parent, child).handle())
1027 .map(|r| r.position)
1028 });
1029 if let Some(p) = cached {
1030 return p;
1031 }
1032 if !self.ordered {
1033 return 0.0;
1034 }
1035 self.with_container(|c| {
1036 c.select_real(
1037 &format!(
1038 "SELECT position FROM {t} WHERE {pc} = ? AND {cc} = ?",
1039 t = self.join_sql,
1040 pc = ident(self.parent_col),
1041 cc = ident(self.child_col),
1042 ),
1043 &[key_param(parent), key_param(child)],
1044 )
1045 })
1046 .flatten()
1047 .unwrap_or(0.0)
1048 }
1049
1050 fn is_member(&self, parent: u64, child: u64) -> bool {
1052 let handle = day_model::Key::Pair(parent, child).handle();
1053 if let Some(state) = self.with_container(|c| c.dirty_state_of(self.join_store, handle))
1054 && let Some(state) = state
1055 {
1056 return state != DirtyRow::Delete;
1057 }
1058 if self.store.with_untracked(|k| k.get(handle).is_some()) {
1059 return true;
1060 }
1061 let fresh = self.with_container(|c| {
1065 c.dirty_state_of(self.a_store, parent) == Some(DirtyRow::Insert)
1066 || c.dirty_state_of(self.b_store, child) == Some(DirtyRow::Insert)
1067 });
1068 if fresh == Some(true) {
1069 return false;
1070 }
1071 self.with_container(|c| {
1072 !c.select_id_column(
1073 &format!(
1074 "SELECT 1 FROM {t} WHERE {pc} = ? AND {cc} = ?",
1075 t = self.join_sql,
1076 pc = ident(self.parent_col),
1077 cc = ident(self.child_col),
1078 ),
1079 &[key_param(parent), key_param(child)],
1080 )
1081 .is_empty()
1082 })
1083 .unwrap_or(false)
1084 }
1085
1086 fn announce_pair(&self, parent: u64, child: u64) {
1088 announce(
1089 &[self.a_store, parent, field_id(self.a_field)],
1090 self.a_field,
1091 );
1092 if let Some(bf) = self.b_field.get() {
1093 announce(&[self.b_store, child, field_id(bf)], bf);
1094 }
1095 }
1096
1097 fn forget_pair(&self, parent: u64, child: u64) {
1098 self.memo_fwd.borrow_mut().remove(&parent);
1099 self.memo_rev.borrow_mut().remove(&child);
1100 }
1101
1102 pub(crate) fn invalidate_all(&self) {
1103 self.memo_fwd.borrow_mut().clear();
1104 self.memo_rev.borrow_mut().clear();
1105 }
1106
1107 pub(crate) fn row_added(&self, handle: u64) {
1109 if let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) {
1110 self.forget_pair(p, c);
1111 self.announce_pair(p, c);
1112 }
1113 }
1114
1115 pub(crate) fn row_removed(&self, handle: u64) {
1116 if let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) {
1117 self.forget_pair(p, c);
1118 self.announce_pair(p, c);
1119 }
1120 }
1121
1122 pub(crate) fn row_moved(&self, handle: u64) {
1124 if let Some(day_model::Key::Pair(p, c)) = day_model::Key::of_handle(handle) {
1125 self.forget_pair(p, c);
1126 self.announce_pair(p, c);
1127 }
1128 }
1129
1130 fn forget_side(&self, is_a: bool, key: u64) {
1135 let (own, others) = if is_a {
1136 (&self.memo_fwd, &self.memo_rev)
1137 } else {
1138 (&self.memo_rev, &self.memo_fwd)
1139 };
1140 own.borrow_mut().remove(&key);
1141 others
1142 .borrow_mut()
1143 .retain(|_, members| !members.contains(&key));
1144 }
1145
1146 pub(crate) fn side_deleted(&self, is_a: bool, key: u64) {
1147 let engine = self
1148 .with_container(|c| c.engine_cascade_allowed())
1149 .unwrap_or(false);
1150 let rule = if is_a {
1151 self.a_delete
1152 } else {
1153 self.b_delete.get()
1154 };
1155 if engine {
1156 self.forget_side(is_a, key);
1160 self.with_container(|c| c.note_engine_cascade(self.join_table));
1161 if rule != DeleteRule::Cascade {
1162 return;
1163 }
1164 }
1165 let others = self.members_of_raw(key, is_a);
1166 if others.is_empty() {
1167 return;
1168 }
1169 let capture = day_model::record_capture_active();
1172 for other in others.iter().filter(|_| !engine) {
1173 let (p, c) = if is_a { (key, *other) } else { (*other, key) };
1174 let handle = day_model::Key::Pair(p, c).handle();
1175 if capture && self.store.with_untracked(|k| k.get(handle).is_none()) {
1176 let position = self.position_of(p, c);
1179 self.store.populate(vec![JoinRow {
1180 parent: p,
1181 child: c,
1182 position,
1183 }]);
1184 }
1185 self.store.restructure("unlink", Op::Delete, handle, |k| {
1186 k.remove(handle);
1187 });
1188 }
1189 if rule == DeleteRule::Cascade {
1190 for other in others {
1195 let holders = self.holders_of(other, is_a);
1196 let still_held = holders.iter().any(|h| *h != key);
1197 if !still_held {
1198 if is_a {
1199 (self.delete_b)(other);
1200 } else {
1201 (self.delete_a)(other);
1202 }
1203 }
1204 }
1205 }
1206 }
1207
1208 fn link(&self, parent: u64, child: u64, position: f64) -> bool {
1209 if self.is_member(parent, child) {
1210 return false; }
1212 let handle = day_model::Key::Pair(parent, child).handle();
1213 self.store.restructure("link", Op::Insert, handle, |k| {
1214 k.push(JoinRow {
1215 parent,
1216 child,
1217 position,
1218 })
1219 });
1220 true
1221 }
1222
1223 fn unlink(&self, parent: u64, child: u64) -> bool {
1224 if !self.is_member(parent, child) {
1225 return false;
1226 }
1227 let handle = day_model::Key::Pair(parent, child).handle();
1228 if day_model::record_capture_active()
1229 && self.store.with_untracked(|k| k.get(handle).is_none())
1230 {
1231 let position = self.position_of(parent, child);
1232 self.store.populate(vec![JoinRow {
1233 parent,
1234 child,
1235 position,
1236 }]);
1237 }
1238 self.store.restructure("unlink", Op::Delete, handle, |k| {
1239 k.remove(handle);
1240 });
1241 true
1242 }
1243}
1244
1245pub fn wire_join<P: Model, C: Model>(
1247 reg: &mut Registrar<'_>,
1248 field: &'static str,
1249 join_table: &'static str,
1250 ordered: Option<&'static str>,
1251 delete: DeleteRule,
1252) {
1253 let container = reg.container.clone();
1254 let (Some(parent_store), Some(child_store)) =
1255 (container.try_cache::<P>(), container.try_cache::<C>())
1256 else {
1257 reg.fail(format!(
1258 "relation `{}.{field}` targets `{}`, which is not in this container's schema!",
1259 P::TABLE,
1260 C::TABLE
1261 ));
1262 return;
1263 };
1264
1265 {
1268 let joins = container.inner.joins.borrow();
1269 if let Some(existing) = joins.iter().find(|j| j.join_table == join_table) {
1270 let ok = existing.a_store == child_store.store_id()
1271 && existing.b_store == parent_store.store_id();
1272 if !ok {
1273 let msg = format!(
1274 "join table `{join_table}` is declared by `{}.{field}` and by another \
1275 relation over different models — a join table belongs to exactly one pair",
1276 P::TABLE
1277 );
1278 drop(joins);
1279 reg.fail(msg);
1280 return;
1281 }
1282 if existing.b_field.get().is_some() {
1283 let msg = format!(
1284 "join table `{join_table}` is declared twice on `{}` — one field per side",
1285 P::TABLE
1286 );
1287 drop(joins);
1288 reg.fail(msg);
1289 return;
1290 }
1291 if ordered.is_some() && !existing.ordered {
1292 let msg = format!(
1293 "relation `{}.{field}` asks for order, but `{join_table}`'s other side \
1294 declared it unordered — a membership has ONE position, so order is \
1295 declared on one side only",
1296 P::TABLE
1297 );
1298 drop(joins);
1299 reg.fail(msg);
1300 return;
1301 }
1302 existing.b_field.set(Some(field));
1303 existing.b_delete.set(delete);
1304 return;
1305 }
1306 }
1307
1308 if ordered.is_some_and(|o| o != "position") {
1309 reg.fail(format!(
1310 "relation `{}.{field}` is a join relation: its order lives on the join row, so \
1311 `ordered` takes no field name (a child can sit at different positions under \
1312 different parents)",
1313 P::TABLE
1314 ));
1315 return;
1316 }
1317 let ordered = ordered.is_some();
1318
1319 let parent_col: &'static str = Box::leak(format!("{}_id", singular(P::TABLE)).into_boxed_str());
1321 let child_col: &'static str = Box::leak(format!("{}_id", singular(C::TABLE)).into_boxed_str());
1322 if parent_col == child_col {
1323 reg.fail(format!(
1324 "relation `{}.{field}`: a self-join needs distinct column names, which the \
1325 derived `{parent_col}` pair cannot give",
1326 P::TABLE
1327 ));
1328 return;
1329 }
1330
1331 if let Err(e) =
1332 container.ensure_join_table::<P, C>(join_table, parent_col, child_col, ordered, delete)
1333 {
1334 reg.error.get_or_insert(e);
1335 return;
1336 }
1337
1338 let store = Store::new(Keyed::new(Vec::new()));
1341 let delete_a = Box::new(move |h: u64| {
1342 parent_store.restructure("cascade", Op::Delete, h, |k| {
1343 k.remove(h);
1344 });
1345 });
1346 let delete_b = Box::new(move |h: u64| {
1347 child_store.restructure("cascade", Op::Delete, h, |k| {
1348 k.remove(h);
1349 });
1350 });
1351 let rel = Rc::new(JoinRel {
1352 container: Rc::downgrade(&container.inner),
1353 join_table,
1354 join_sql: ident(join_table),
1355 parent_col,
1356 child_col,
1357 a_store: parent_store.store_id(),
1358 a_table: P::TABLE,
1359 a_field: field,
1360 a_key_col: P::KEY,
1361 a_delete: delete,
1362 b_store: child_store.store_id(),
1363 b_table: C::TABLE,
1364 b_key_col: C::KEY,
1365 b_field: Cell::new(None),
1366 b_delete: Cell::new(DeleteRule::Nullify),
1367 join_store: store.store_id(),
1368 ordered,
1369 store,
1370 delete_a,
1371 delete_b,
1372 memo_fwd: RefCell::new(HashMap::new()),
1373 memo_rev: RefCell::new(HashMap::new()),
1374 });
1375
1376 container.register_join_hooks(join_table, parent_col, child_col, ordered, store);
1377 container.inner.joins.borrow_mut().push(rel);
1378}
1379
1380fn singular(table: &str) -> String {
1382 if let Some(stem) = table.strip_suffix("ies") {
1383 return format!("{stem}y");
1384 }
1385 for suffix in ["ses", "xes", "zes", "ches", "shes"] {
1386 if let Some(stem) = table.strip_suffix(suffix) {
1387 return format!("{stem}{}", &suffix[..suffix.len() - 2]);
1388 }
1389 }
1390 table.strip_suffix('s').unwrap_or(table).to_string()
1391}
1392
1393day_reactive::tls_group! {
1398 static CONTAINERS: RefCell<Vec<Weak<ContainerInner>>> = const { RefCell::new(Vec::new()) };
1401
1402}
1403
1404pub(crate) fn container_for_store(store: u64) -> Option<ModelContainer> {
1407 CONTAINERS.with(|c| {
1408 c.borrow()
1409 .iter()
1410 .filter_map(Weak::upgrade)
1411 .find(|inner| inner.tables.borrow().contains_key(&store))
1412 .map(|inner| ModelContainer { inner })
1413 })
1414}
1415
1416pub(crate) fn register_container(inner: &Rc<ContainerInner>) {
1417 CONTAINERS.with(|c| {
1418 let mut v = c.borrow_mut();
1419 v.retain(|w| w.strong_count() > 0);
1420 v.push(Rc::downgrade(inner));
1421 });
1422}
1423
1424enum Wired {
1427 ToOne(Rc<ToOneRel>),
1428 Join(Rc<JoinRel>, bool),
1429}
1430
1431fn find_relation(parent_store: u64, field: &str) -> Option<Wired> {
1432 CONTAINERS.with(|c| {
1433 c.borrow()
1434 .iter()
1435 .filter_map(Weak::upgrade)
1436 .find_map(|inner| {
1437 if let Some(r) = inner
1438 .relations
1439 .borrow()
1440 .iter()
1441 .find(|r| r.parent_store == parent_store && r.parent_field == field)
1442 {
1443 return Some(Wired::ToOne(r.clone()));
1444 }
1445 inner.joins.borrow().iter().find_map(|r| {
1446 if r.a_store == parent_store && r.a_field == field {
1447 Some(Wired::Join(r.clone(), true))
1448 } else if r.b_store == parent_store && r.b_field.get() == Some(field) {
1449 Some(Wired::Join(r.clone(), false))
1450 } else {
1451 None
1452 }
1453 })
1454 })
1455 })
1456}
1457
1458type Materialize = Box<dyn Fn(&[u64])>;
1460
1461type ReadOrder = Box<dyn Fn(u64) -> f64>;
1464type WriteOrder = Box<dyn Fn(u64, f64) -> bool>;
1465
1466struct Placement {
1469 ordered: bool,
1470 read_ord: ReadOrder,
1471 write_ord: WriteOrder,
1472 is_member: bool,
1473}
1474
1475pub struct RelationRef<S: Copy + 'static, P: 'static, T: 'static> {
1480 field: day_model::Field<S, P, Many<T>>,
1481}
1482
1483impl<S: Copy + 'static, P: 'static, T: 'static> Clone for RelationRef<S, P, T> {
1484 fn clone(&self) -> Self {
1485 *self
1486 }
1487}
1488impl<S: Copy + 'static, P: 'static, T: 'static> Copy for RelationRef<S, P, T> {}
1489
1490impl<S: day_model::Source<P>, P: 'static, T: 'static> RelationRef<S, P, T> {
1491 pub fn new(field: day_model::Field<S, P, Many<T>>) -> Self {
1492 RelationRef { field }
1493 }
1494
1495 fn resolve(&self) -> Option<(Wired, u64)> {
1496 let mut parts = Vec::new();
1497 day_model::Source::components(self.field, &mut parts);
1498 if parts.len() < 2 {
1499 return None;
1500 }
1501 find_relation(parts[0], self.field.label()).map(|r| (r, parts[1]))
1502 }
1503
1504 fn members(&self) -> Vec<u64> {
1506 match self.resolve() {
1507 Some((Wired::ToOne(r), p)) => r.children_of(p),
1508 Some((Wired::Join(r, forward), p)) => r.members_of(p, forward),
1509 None => Vec::new(),
1510 }
1511 }
1512
1513 pub fn ids(&self) -> Vec<ModelId<T>> {
1516 self.field.with(|_| ());
1517 self.members()
1518 .into_iter()
1519 .map(ModelId::from_handle)
1520 .collect()
1521 }
1522
1523 pub fn count(&self) -> usize {
1525 self.field.with(|_| ());
1526 self.members().len()
1527 }
1528
1529 pub fn is_empty(&self) -> bool {
1530 self.count() == 0
1531 }
1532
1533 pub fn contains(&self, id: impl Into<ModelId<T>>) -> bool {
1535 let h = id.into().handle();
1536 self.field.with(|_| ());
1537 self.members().contains(&h)
1538 }
1539
1540 pub fn add(&self, child: impl Into<ModelId<T>>) -> bool {
1545 let h = child.into().handle();
1546 match self.resolve() {
1547 Some((Wired::ToOne(r), parent)) => {
1548 if !r.set_fk(h, Some(parent)) {
1549 return false;
1550 }
1551 if r.ordered.is_some() {
1552 let last = r
1553 .children_of(parent)
1554 .iter()
1555 .filter(|c| **c != h)
1556 .map(|c| r.read_order(*c))
1557 .fold(f64::NEG_INFINITY, f64::max);
1558 let next = if last.is_finite() { last + 1.0 } else { 1.0 };
1559 (r.write_ord)(h, next);
1560 }
1561 true
1562 }
1563 Some((Wired::Join(r, forward), key)) => {
1564 let (a, b) = if forward { (key, h) } else { (h, key) };
1566 let next = if r.ordered {
1567 let last = r
1568 .members_of(a, true)
1569 .iter()
1570 .map(|c| r.position_of(a, *c))
1571 .fold(f64::NEG_INFINITY, f64::max);
1572 if last.is_finite() { last + 1.0 } else { 1.0 }
1573 } else {
1574 0.0
1575 };
1576 r.link(a, b, next)
1577 }
1578 None => false,
1579 }
1580 }
1581
1582 pub fn insert_at(&self, child: impl Into<ModelId<T>>, index: usize) -> bool {
1588 let h = child.into().handle();
1589 let Some((wired, parent)) = self.resolve() else {
1590 return false;
1591 };
1592 let Placement {
1595 ordered,
1596 read_ord,
1597 write_ord,
1598 is_member,
1599 } = match &wired {
1600 Wired::ToOne(r) => {
1601 let (r1, r2) = (r.clone(), r.clone());
1602 Placement {
1603 ordered: r.ordered.is_some(),
1604 read_ord: Box::new(move |c| r1.read_order(c)),
1605 write_ord: Box::new(move |c, v| {
1606 (r2.materialize)(&[c]);
1607 (r2.write_ord)(c, v)
1608 }),
1609 is_member: r.parent_of(h) == Some(parent) && {
1610 r.children_of(parent).contains(&h)
1613 },
1614 }
1615 }
1616 Wired::Join(r, forward) => {
1617 let (r1, r2) = (r.clone(), r.clone());
1618 Placement {
1619 ordered: r.ordered && *forward,
1622 read_ord: Box::new(move |c| r1.position_of(parent, c)),
1623 write_ord: Box::new(move |c, v| {
1624 let handle = day_model::Key::Pair(parent, c).handle();
1625 if r2.store.with_untracked(|k| k.get(handle).is_none()) {
1626 let position = r2.position_of(parent, c);
1627 r2.store.populate(vec![JoinRow {
1628 parent,
1629 child: c,
1630 position,
1631 }]);
1632 }
1633 r2.store.write_field(handle, "position", v)
1634 }),
1635 is_member: r.members_of(parent, *forward).contains(&h),
1636 }
1637 }
1638 };
1639 if !ordered {
1640 return false;
1641 }
1642 if !is_member && !self.add(ModelId::<T>::from_handle(h)) {
1643 return false;
1644 }
1645 let siblings: Vec<u64> = match &wired {
1646 Wired::ToOne(r) => r.children_of(parent),
1647 Wired::Join(r, forward) => r.members_of(parent, *forward),
1648 }
1649 .into_iter()
1650 .filter(|c| *c != h)
1651 .collect();
1652 let index = index.min(siblings.len());
1653 let prev = index.checked_sub(1).and_then(|i| siblings.get(i).copied());
1654 let next = siblings.get(index).copied();
1655 let ord = match (prev.map(&read_ord), next.map(&read_ord)) {
1656 (None, None) => 1.0,
1657 (Some(a), None) => a + 1.0,
1658 (None, Some(b)) => b - 1.0,
1659 (Some(a), Some(b)) => {
1660 let mid = a + (b - a) / 2.0;
1661 if mid > a && mid < b {
1662 mid
1663 } else {
1664 for (i, c) in siblings.iter().enumerate() {
1667 write_ord(*c, (i + 1) as f64);
1668 }
1669 index as f64 + 0.5
1670 }
1671 }
1672 };
1673 write_ord(h, ord)
1674 }
1675
1676 pub fn move_to(&self, child: impl Into<ModelId<T>>, index: usize) -> bool {
1678 self.insert_at(child, index)
1679 }
1680
1681 pub fn remove(&self, child: impl Into<ModelId<T>>) -> bool {
1685 let h = child.into().handle();
1686 match self.resolve() {
1687 Some((Wired::ToOne(r), p)) => {
1688 if !r.children_of(p).contains(&h) {
1689 return false; }
1691 r.set_fk(h, None)
1692 }
1693 Some((Wired::Join(r, forward), key)) => {
1694 let (a, b) = if forward { (key, h) } else { (h, key) };
1695 r.unlink(a, b)
1696 }
1697 None => false,
1698 }
1699 }
1700
1701 pub fn clear(&self) {
1703 match self.resolve() {
1704 Some((Wired::ToOne(r), p)) => {
1705 let children = r.children_of(p);
1706 (r.materialize)(&children);
1707 for child in children {
1708 (r.write_fk)(child, None);
1709 }
1710 }
1711 Some((Wired::Join(r, forward), key)) => {
1712 for other in r.members_of(key, forward) {
1713 let (a, b) = if forward { (key, other) } else { (other, key) };
1714 r.unlink(a, b);
1715 }
1716 }
1717 None => {}
1718 }
1719 }
1720}
1721
1722impl ModelContainer {
1727 pub(crate) fn relations_on_change(&self, change: &day_model::Change) {
1731 let Some(&store) = change.components.first() else {
1732 return;
1733 };
1734 if self.inner.relations.borrow().is_empty() && self.inner.joins.borrow().is_empty() {
1735 return;
1736 }
1737 let rels: Vec<Rc<ToOneRel>> = self.inner.relations.borrow().iter().cloned().collect();
1738 for rel in rels {
1739 if rel.child_store == store {
1740 match (change.components.get(1).copied(), change.op) {
1741 (Some(k), _) if k == day_model::STRUCTURE => {}
1742 (Some(child), Op::Set) if change.components.len() >= 3 => {
1743 if change.label == rel.fk_field {
1744 rel.reparent(child);
1745 } else if Some(change.label) == rel.ordered {
1746 rel.order_changed(child);
1747 }
1748 }
1749 (Some(child), Op::Insert) if change.components.len() == 2 => {
1750 rel.child_added(child);
1751 }
1752 (Some(child), Op::Delete) if change.components.len() == 2 => {
1753 rel.child_removed(child);
1754 }
1755 _ => {}
1756 }
1757 }
1758 if rel.parent_store == store
1759 && change.components.len() == 2
1760 && change.op == Op::Delete
1761 && change.components[1] != day_model::STRUCTURE
1762 {
1763 rel.parent_deleted(self, change.components[1]);
1764 }
1765 }
1766
1767 let joins: Vec<Rc<JoinRel>> = self.inner.joins.borrow().iter().cloned().collect();
1768 for rel in joins {
1769 let Some(&key) = change.components.get(1) else {
1770 continue;
1771 };
1772 if key == day_model::STRUCTURE {
1773 continue;
1774 }
1775 if rel.join_store == store {
1776 match change.op {
1777 Op::Insert if change.components.len() == 2 => rel.row_added(key),
1778 Op::Delete if change.components.len() == 2 => rel.row_removed(key),
1779 Op::Set if change.components.len() >= 3 && change.label == "position" => {
1780 rel.row_moved(key)
1781 }
1782 _ => {}
1783 }
1784 }
1785 if change.op == Op::Delete && change.components.len() == 2 {
1788 if rel.a_store == store {
1789 rel.side_deleted(true, key);
1790 } else if rel.b_store == store {
1791 rel.side_deleted(false, key);
1792 }
1793 }
1794 }
1795 }
1796
1797 pub(crate) fn invalidate_relation_memos(&self) {
1799 for r in self.inner.relations.borrow().iter() {
1800 r.invalidate_all();
1801 }
1802 for j in self.inner.joins.borrow().iter() {
1803 j.invalidate_all();
1804 }
1805 }
1806
1807 pub(crate) fn invalidate_relation_memos_of(&self, tables: &[&'static str]) {
1810 for r in self.inner.relations.borrow().iter() {
1811 if tables.contains(&r.parent_table) || tables.contains(&r.child_table) {
1812 r.invalidate_all();
1813 }
1814 }
1815 for j in self.inner.joins.borrow().iter() {
1816 if tables.contains(&j.join_table)
1817 || tables.contains(&j.a_table)
1818 || tables.contains(&j.b_table)
1819 {
1820 j.invalidate_all();
1821 }
1822 }
1823 }
1824
1825 pub fn try_cache<M: Model>(&self) -> Option<Store<Keyed<M>>> {
1828 self.inner
1829 .stores
1830 .borrow()
1831 .get(&std::any::TypeId::of::<M>())
1832 .and_then(|a| a.downcast_ref::<Store<Keyed<M>>>())
1833 .copied()
1834 }
1835
1836 pub fn delete<M: Model>(&self, id: impl Into<ModelId<M>>) -> Result<(), DbError> {
1841 let h = id.into().handle();
1842 let store = self.cache::<M>();
1843 let rels: Vec<Rc<ToOneRel>> = self.inner.relations.borrow().iter().cloned().collect();
1844 for r in rels
1845 .iter()
1846 .filter(|r| r.parent_store == store.store_id() && r.delete == DeleteRule::Deny)
1847 {
1848 let n = r.children_of(h).len();
1849 if n > 0 {
1850 return Err(DbError::new(
1851 DbErrorKind::Deny,
1852 format!(
1853 "`{}` row still referenced by {n} `{}` row(s) through `{}` — \
1854 delete or reparent them first",
1855 M::TABLE,
1856 r.fk_field,
1857 r.parent_field
1858 ),
1859 ));
1860 }
1861 }
1862 let joins: Vec<Rc<JoinRel>> = self.inner.joins.borrow().iter().cloned().collect();
1863 for r in joins.iter().filter(|r| {
1864 (r.a_store == store.store_id() && r.a_delete == DeleteRule::Deny)
1865 || (r.b_store == store.store_id() && r.b_delete.get() == DeleteRule::Deny)
1866 }) {
1867 let forward = r.a_store == store.store_id();
1868 let n = r.members_of(h, forward).len();
1869 if n > 0 {
1870 return Err(DbError::new(
1871 DbErrorKind::Deny,
1872 format!(
1873 "`{}` row still holds {n} membership(s) through `{}` — unlink them \
1874 first",
1875 M::TABLE,
1876 if forward {
1877 r.a_field
1878 } else {
1879 r.b_field.get().unwrap_or(r.a_field)
1880 }
1881 ),
1882 ));
1883 }
1884 }
1885 if day_model::record_capture_active() {
1888 let _ = self.ensure_resident::<M>(&[h]);
1889 }
1890 store.restructure("delete", Op::Delete, h, |k| {
1891 k.remove(h);
1892 });
1893 Ok(())
1894 }
1895
1896 pub(crate) fn ensure_join_table<P: Model, C: Model>(
1900 &self,
1901 table: &str,
1902 parent_col: &str,
1903 child_col: &str,
1904 ordered: bool,
1905 delete: DeleteRule,
1906 ) -> Result<(), DbError> {
1907 let position = if ordered {
1911 ", position REAL NOT NULL"
1912 } else {
1913 ""
1914 };
1915 let index = ident(&format!("day_idx_{table}_{child_col}"));
1916 let (table, parent_col, child_col) = (ident(table), ident(parent_col), ident(child_col));
1917 let body = format!(
1918 "CREATE TABLE IF NOT EXISTS {table} (\
1919 {parent_col} {} NOT NULL REFERENCES {}({}) ON DELETE {} DEFERRABLE INITIALLY DEFERRED, \
1920 {child_col} {} NOT NULL REFERENCES {}({}) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED\
1921 {position}, PRIMARY KEY ({parent_col}, {child_col}))",
1922 P::KEY_SQL.ddl(),
1923 TableName::of::<P>().sql(),
1924 ident(P::KEY),
1925 if delete == DeleteRule::Deny {
1926 "RESTRICT"
1927 } else {
1928 "CASCADE"
1929 },
1930 C::KEY_SQL.ddl(),
1931 TableName::of::<C>().sql(),
1932 ident(C::KEY),
1933 );
1934 if self.conn().execute(&format!("{body} STRICT"), &[]).is_err() {
1935 self.conn().execute(&body, &[])?;
1936 }
1937 self.conn().execute(
1938 &format!("CREATE INDEX IF NOT EXISTS {index} ON {table}({child_col})"),
1939 &[],
1940 )?;
1941 Ok(())
1942 }
1943
1944 pub(crate) fn register_join_hooks(
1947 &self,
1948 table: &'static str,
1949 parent_col: &'static str,
1950 child_col: &'static str,
1951 ordered: bool,
1952 store: Store<Keyed<JoinRow>>,
1953 ) {
1954 let mut columns = vec![parent_col.to_string(), child_col.to_string()];
1955 let mut column_names = vec![parent_col, child_col];
1956 let mut fields = vec![parent_col.to_string(), child_col.to_string()];
1957 if ordered {
1958 columns.push("position".into());
1959 column_names.push("position");
1960 fields.push("position".into());
1961 }
1962 let to_row = move |r: &JoinRow| {
1963 let mut v = vec![key_param(r.parent), key_param(r.child)];
1964 if ordered {
1965 v.push(Value::Real(r.position));
1966 }
1967 v
1968 };
1969 let decode = move |r: &Vec<Value>| -> Result<JoinRow, DbError> {
1970 match (
1971 value_to_handle(&Row::get(r, 0)),
1972 value_to_handle(&Row::get(r, 1)),
1973 ) {
1974 (Some(p), Some(c)) => Ok(JoinRow {
1975 parent: p,
1976 child: c,
1977 position: if ordered {
1978 Row::get(r, 2).as_real().unwrap_or(0.0)
1979 } else {
1980 0.0
1981 },
1982 }),
1983 _ => Err(DbError::new(
1984 DbErrorKind::Decode,
1985 format!("`{table}` holds a membership whose ids will not read as keys"),
1986 )),
1987 }
1988 };
1989 let (pc, cc) = (ident(parent_col), ident(child_col));
1990 let hooks = crate::TableHooks {
1991 table,
1992 name: TableName::plain(table),
1993 key_cols: vec![parent_col.to_string(), child_col.to_string()],
1994 key_where: Rc::new(move |h| match day_model::Key::of_handle(h) {
1995 Some(day_model::Key::Pair(p, c)) => (
1996 format!("{pc} = ? AND {cc} = ?"),
1997 vec![key_param(p), key_param(c)],
1998 ),
1999 _ => (format!("{pc} IS NULL"), Vec::new()),
2000 }),
2001 columns,
2002 column_names,
2003 fields,
2004 lazy: vec![false; if ordered { 3 } else { 2 }],
2005 settle: Rc::new(|_| Vec::new()),
2006 fts: None,
2007 fts_key: "rowid",
2008 spatial: None,
2009 row_for: Rc::new(move |h| store.with_untracked(|k| k.get(h).map(to_row))),
2010 all_rows: Rc::new(move || {
2011 store.with_untracked(|k| {
2012 k.items()
2013 .iter()
2014 .map(|r| (day_model::Identified::handle(r), to_row(r)))
2015 .collect()
2016 })
2017 }),
2018 resident_keys: Rc::new(move || store.with_untracked(|k| k.keys())),
2019 resident_len: Rc::new(move || store.with_untracked(|k| k.len())),
2020 is_resident: Rc::new(move |h| store.with_untracked(|k| k.get(h).is_some())),
2021 absorb: Rc::new(move |raw| {
2022 let mut rows = Vec::with_capacity(raw.len());
2023 for r in &raw {
2024 rows.push(decode(r)?);
2025 }
2026 let keys = rows
2027 .iter()
2028 .map(day_model::Identified::handle)
2029 .collect::<Vec<_>>();
2030 store.populate(rows);
2031 Ok(keys)
2032 }),
2033 refresh: Rc::new(move |raw| {
2034 let mut fresh: Vec<JoinRow> = Vec::with_capacity(raw.len());
2037 for r in &raw {
2038 fresh.push(decode(r)?);
2039 }
2040 let existing: Vec<u64> = store.with_untracked(|k| k.keys());
2041 let arriving: std::collections::HashSet<u64> =
2042 fresh.iter().map(day_model::Identified::handle).collect();
2043 let mut changed = false;
2044 day_model::with_author(ModelContainer::EXTERNAL_AUTHOR, || {
2045 for row in fresh {
2046 let h = day_model::Identified::handle(&row);
2047 match store.with_untracked(|k| k.get(h).cloned()) {
2048 None => {
2049 changed = true;
2050 store.restructure("external", Op::Insert, h, |k| k.push(row));
2051 }
2052 Some(old) if ordered && old.position != row.position => {
2053 changed = true;
2054 store.write_field(h, "position", row.position);
2055 }
2056 Some(_) => {}
2057 }
2058 }
2059 for gone in existing.into_iter().filter(|h| !arriving.contains(h)) {
2060 changed = true;
2061 store.restructure("external", Op::Delete, gone, |k| {
2062 k.remove(gone);
2063 });
2064 }
2065 });
2066 Ok(changed)
2067 }),
2068 #[cfg(not(target_arch = "wasm32"))]
2069 dispose_cache: Rc::new(move || store.dispose_contents()),
2070 evict: Rc::new(move |candidates, want| {
2071 let doomed: Vec<u64> = candidates
2072 .iter()
2073 .copied()
2074 .filter(|h| !store.is_observed(*h))
2075 .take(want)
2076 .collect();
2077 store.depopulate_many(&doomed)
2078 }),
2079 watch_undo: Rc::new(move |stack: &day_model::UndoStack| stack.watch(store)),
2080 };
2081 self.inner
2082 .tables
2083 .borrow_mut()
2084 .insert(store.store_id(), hooks);
2085 }
2086}