day-persistence 0.4.1

SQLite persistence for the Day observable model.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Relations: maintained inverses over one stored column (the child's foreign key), delete
//! rules that flow through the normal pipeline, ordered to-many over a visible order field,
//! and the SQL-level clauses that hold another process to the same rules.

use day_model::{ModelId, Op, Uuid};
use day_persistence::{
    DbErrorKind, DeleteRule, Many, Model, ModelContainer, One, Sqlite, SqliteConnection,
    SqliteDriver, schema,
};
use day_reactive::Binding;

// --- the travel app: one-to-many, cascade --------------------------------------------------

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "trips")]
struct Trip {
    #[model(id)]
    id: u32,
    name: String,
    #[model(relation(target = Lodging, inverse = "trip", delete = "cascade"))]
    lodging: Many<Lodging>,
}

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "lodging")]
struct Lodging {
    #[model(id)]
    id: u32,
    name: String,
    trip: One<Trip>,
}

// --- the library: nullify over an optional reference ---------------------------------------

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "authors")]
struct Author {
    #[model(id)]
    id: u32,
    name: String,
    #[model(relation(target = Book, inverse = "author", delete = "nullify"))]
    books: Many<Book>,
}

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "books")]
struct Book {
    #[model(id)]
    id: u32,
    title: String,
    author: Option<One<Author>>,
}

// --- the sketch: an ordered self-referential tree, the ungroup fold regression --------------

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "layers")]
struct Layer {
    #[model(id)]
    id: u32,
    z: f64,
    parent: Option<One<Layer>>,
    #[model(relation(target = Layer, inverse = "parent", delete = "cascade", ordered = "z"))]
    children: Many<Layer>,
}

// --- the drawing: a self-referential tree, uuid-keyed, cascade ------------------------------

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "nodes")]
struct Node {
    #[model(id)]
    id: Uuid,
    name: String,
    parent: Option<One<Node>>,
    #[model(relation(target = Node, inverse = "parent", delete = "cascade"))]
    children: Many<Node>,
}

// --- the playlist: ordered to-many over a visible `REAL` field ------------------------------

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "playlists")]
struct Playlist {
    #[model(id)]
    id: u32,
    title: String,
    #[model(relation(target = Track, inverse = "playlist", delete = "cascade", ordered = "position"))]
    tracks: Many<Track>,
}

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "tracks")]
struct Track {
    #[model(id)]
    id: u32,
    title: String,
    playlist: One<Playlist>,
    position: f64,
}

// --- the ledger: deny -----------------------------------------------------------------------

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "invoices")]
struct Invoice {
    #[model(id)]
    id: u32,
    number: String,
    #[model(relation(target = LineItem, inverse = "invoice", delete = "deny"))]
    items: Many<LineItem>,
}

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "line_items")]
struct LineItem {
    #[model(id)]
    id: u32,
    what: String,
    invoice: One<Invoice>,
}

// --------------------------------------------------------------------------------------------

fn temp_db(name: &str) -> std::path::PathBuf {
    let path = std::env::temp_dir().join(format!(
        "day-persistence-rel-{}-{}.db",
        std::process::id(),
        name
    ));
    let _ = std::fs::remove_file(&path);
    let _ = std::fs::remove_file(path.with_extension("sqlite-wal"));
    let _ = std::fs::remove_file(path.with_extension("sqlite-shm"));
    path
}

fn travel() -> ModelContainer {
    let c = ModelContainer::open(Sqlite::memory(), schema![Trip, Lodging]).expect("open");
    let trips = c.cache::<Trip>();
    trips.restructure("add", Op::Insert, 1, |v| {
        v.push(Trip {
            id: 1,
            name: "Kyoto".into(),
            ..Default::default()
        });
    });
    trips.restructure("add", Op::Insert, 2, |v| {
        v.push(Trip {
            id: 2,
            name: "Oslo".into(),
            ..Default::default()
        });
    });
    let lodging = c.cache::<Lodging>();
    for (id, name, trip) in [
        (10, "Ryokan", 1),
        (11, "Machiya", 1),
        (12, "Fjord cabin", 2),
    ] {
        lodging.restructure("add", Op::Insert, id, |v| {
            v.push(Lodging {
                id: id as u32,
                name: name.into(),
                trip: One::to(trip as u32),
            });
        });
    }
    // Land the setup, so a `record_sql` below sees only the operation under test.
    c.save().expect("seed");
    c
}

#[test]
fn the_index_answers_from_loaded_foreign_keys() {
    let c = travel();
    let trips = c.cache::<Trip>();
    assert_eq!(trips.elem(1).lodging().ids(), [10, 11]);
    assert_eq!(trips.elem(2).lodging().ids(), [12]);
    assert_eq!(trips.elem(1).lodging().count(), 2);
    assert!(trips.elem(1).lodging().contains(11));
    assert!(!trips.elem(2).lodging().contains(11));
}

#[test]
fn writing_a_child_foreign_key_wakes_the_parents_many() {
    let c = travel();
    let trips = c.cache::<Trip>();
    let lodging = c.cache::<Lodging>();

    // Direction one of the maintained inverse: the child's One is the truth, and setting it
    // announces the affected parents' Many fields.
    let ((), changes) = day_model::record_changes(|| {
        lodging.elem(12).trip().write(One::to(1u32));
    });
    assert_eq!(trips.elem(1).lodging().ids(), [10, 11, 12]);
    assert!(trips.elem(2).lodging().is_empty());
    let labels: Vec<_> = changes.iter().map(|c| c.label).collect();
    assert!(labels.contains(&"trip"), "the FK write itself: {labels:?}");
    assert_eq!(
        labels.iter().filter(|l| **l == "lodging").count(),
        2,
        "both the old and the new parent announced: {labels:?}"
    );
}

#[test]
fn adding_through_the_many_writes_the_foreign_key() {
    let c = travel();
    let trips = c.cache::<Trip>();
    let lodging = c.cache::<Lodging>();

    // Direction two: the Many side is sugar over the same truth.
    let sql = c
        .record_sql(|| {
            assert!(trips.elem(2).lodging().add(10));
        })
        .expect("flush");
    assert_eq!(
        sql,
        ["UPDATE \"lodging\" SET \"trip\" = ? WHERE \"id\" = ?"]
    );
    assert_eq!(lodging.elem(10).trip().peek().id(), Some(ModelId::of(2u32)));
    assert_eq!(trips.elem(1).lodging().ids(), [11]);
    assert_eq!(trips.elem(2).lodging().ids(), [10, 12], "ascending by id");

    // remove() clears the optional-free reference. A required One surfaces at flush, so
    // reparent instead; here we only assert the membership left.
    assert!(trips.elem(2).lodging().remove(10));
    assert_eq!(trips.elem(2).lodging().ids(), [12]);
}

#[test]
fn cascade_deletes_children_with_the_parent_in_one_flush() {
    let c = travel();
    let trips = c.cache::<Trip>();
    let lodging = c.cache::<Lodging>();

    let sql = c
        .record_sql(|| {
            trips.restructure("delete", Op::Delete, 1, |v| {
                v.remove(1);
            });
        })
        .expect("flush");
    assert!(lodging.with_untracked(|k| k.get(10).is_none()), "cascaded");
    assert!(lodging.with_untracked(|k| k.get(11).is_none()), "cascaded");
    assert!(
        lodging.with_untracked(|k| k.get(12).is_some()),
        "other trip's"
    );
    // One statement: with no undo stack installed the engine's ON DELETE CASCADE takes the
    // children in the flush, and the resident ones were re-read away afterwards.
    assert_eq!(sql, ["DELETE FROM \"trips\" WHERE \"id\" = ?"]);
    assert_eq!(c.table_count::<Lodging>().expect("count"), 1);
}

#[test]
fn cascade_recurses_through_a_self_referential_tree() {
    let c = ModelContainer::open(Sqlite::memory(), schema![Node]).expect("open");
    let nodes = c.cache::<Node>();
    let (root, group, leaf_a, leaf_b, other) = (
        Uuid::now_v7(),
        Uuid::now_v7(),
        Uuid::now_v7(),
        Uuid::now_v7(),
        Uuid::now_v7(),
    );
    let add = |id: Uuid, name: &str, parent: Option<Uuid>| {
        let node = Node {
            id,
            name: name.into(),
            parent: parent.map(One::to),
            ..Default::default()
        };
        nodes.restructure("add", Op::Insert, id, |v| v.push(node));
    };
    add(root, "root", None);
    add(group, "group", Some(root));
    add(leaf_a, "leaf a", Some(group));
    add(leaf_b, "leaf b", Some(group));
    add(other, "elsewhere", None);

    assert_eq!(nodes.elem(root).children().count(), 1);
    assert_eq!(nodes.elem(group).children().count(), 2);

    nodes.restructure("delete", Op::Delete, root, |v| {
        v.remove(ModelId::<Node>::of(root).handle());
    });
    // The flush takes three generations through the engine; the unrelated root stayed.
    c.save().expect("flush");
    assert_eq!(nodes.keys().len(), 1);
    assert_eq!(c.table_count::<Node>().expect("count"), 1);
    assert!(nodes.with_untracked(|k| k.get(ModelId::<Node>::of(other).handle()).is_some()));
}

#[test]
fn a_mid_batch_parent_delete_spares_the_children_the_batch_detached() {
    // The ungroup shape: both children detach and the parent dies in one turn. The first
    // detach's ordered-relation upkeep dirties the parent row, so first-dirty order puts
    // the parent between the children, and `ON DELETE CASCADE` fires per statement
    // (`DEFERRABLE` defers the check, never the action), so a mid-batch DELETE would take
    // every child whose detach had not landed yet. The fold must emit deletes last.
    let c = ModelContainer::open(Sqlite::memory(), schema![Layer]).expect("open");
    let _undo = c.undo(10);
    let layers = c.cache::<Layer>();
    let add = |id: u32, z: f64, parent: Option<u32>| {
        let node = Layer {
            id,
            z,
            parent: parent.map(One::to),
            ..Default::default()
        };
        layers.restructure("add", Op::Insert, id, move |v| v.push(node));
    };
    add(1, 1.0, None); // the group
    add(2, 1.0, Some(1));
    add(3, 2.0, Some(1));
    c.save().expect("seed flush");
    assert_eq!(c.table_count::<Layer>().expect("count"), 3);

    // One batch, the app's ungroup: detach each child (parent + a fresh z), delete the group.
    for (i, child) in [2u32, 3u32].into_iter().enumerate() {
        layers.elem(u64::from(child)).parent().write(None);
        layers
            .elem(u64::from(child))
            .z()
            .write(1.0 + (i as f64 + 1.0) / 1024.0);
    }
    layers.restructure("ungroup", Op::Delete, 1, |v| {
        v.remove(1);
    });
    c.save().expect("ungroup flush");

    assert_eq!(
        c.table_count::<Layer>().expect("count"),
        2,
        "the mid-batch cascade must not take the detached children"
    );
}

#[test]
fn a_cascade_is_one_undo_unit_that_restores_the_subtree() {
    let c = travel();
    let undo = c.undo(10);
    let trips = c.cache::<Trip>();
    let lodging = c.cache::<Lodging>();

    trips.restructure("delete", Op::Delete, 1, |v| {
        v.remove(1);
    });
    day_reactive::flush_sync();
    assert!(lodging.with_untracked(|k| k.get(10).is_none()));

    assert!(undo.undo(), "parent and cascaded children seal as one turn");
    assert_eq!(trips.elem(1).name().peek(), "Kyoto");
    assert_eq!(lodging.elem(10).name().peek(), "Ryokan");
    assert_eq!(lodging.elem(11).name().peek(), "Machiya");
    assert_eq!(
        trips.elem(1).lodging().ids(),
        [10, 11],
        "the index followed the replayed inserts"
    );
}

#[test]
fn nullify_clears_optional_references_and_the_children_survive() {
    let c = ModelContainer::open(Sqlite::memory(), schema![Author, Book]).expect("open");
    let authors = c.cache::<Author>();
    let books = c.cache::<Book>();
    authors.restructure("add", Op::Insert, 1, |v| {
        v.push(Author {
            id: 1,
            name: "Le Guin".into(),
            ..Default::default()
        });
    });
    for (id, title) in [(10, "Dispossessed"), (11, "Left Hand")] {
        books.restructure("add", Op::Insert, id, |v| {
            v.push(Book {
                id: id as u32,
                title: title.into(),
                author: Some(One::to(1u32)),
            });
        });
    }
    assert_eq!(authors.elem(1).books().count(), 2);
    c.save().expect("seed");

    let sql = c
        .record_sql(|| {
            authors.restructure("delete", Op::Delete, 1, |v| {
                v.remove(1);
            });
        })
        .expect("flush");
    assert!(books.with_untracked(|k| k.get(10).is_some()), "survived");
    assert_eq!(books.elem(10).author().peek(), None, "reference cleared");
    assert_eq!(books.elem(11).author().peek(), None, "reference cleared");
    // The engine's ON DELETE SET NULL did the clearing: one statement, and the resident
    // children were re-read with their references gone.
    assert_eq!(sql, ["DELETE FROM \"authors\" WHERE \"id\" = ?"]);
    assert_eq!(c.table_count::<Book>().expect("count"), 2);
}

#[test]
fn deny_refuses_through_the_checked_door() {
    let c = ModelContainer::open(Sqlite::memory(), schema![Invoice, LineItem]).expect("open");
    let invoices = c.cache::<Invoice>();
    let items = c.cache::<LineItem>();
    invoices.restructure("add", Op::Insert, 1, |v| {
        v.push(Invoice {
            id: 1,
            number: "INV-0001".into(),
            ..Default::default()
        });
    });
    items.restructure("add", Op::Insert, 10, |v| {
        v.push(LineItem {
            id: 10,
            what: "consulting".into(),
            invoice: One::to(1u32),
        });
    });

    let err = c.delete::<Invoice>(1u32).expect_err("still referenced");
    assert_eq!(err.kind, DbErrorKind::Deny);
    assert!(invoices.with_untracked(|k| k.get(1).is_some()), "refused");

    items.restructure("delete", Op::Delete, 10, |v| {
        v.remove(10);
    });
    c.delete::<Invoice>(1u32).expect("no children left");
    assert!(invoices.with_untracked(|k| k.get(1).is_none()));
}

#[test]
fn ordered_children_read_in_order_and_a_move_writes_one_row() {
    let c = ModelContainer::open(Sqlite::memory(), schema![Playlist, Track]).expect("open");
    let lists = c.cache::<Playlist>();
    let tracks = c.cache::<Track>();
    lists.restructure("add", Op::Insert, 1, |v| {
        v.push(Playlist {
            id: 1,
            title: "Road trip".into(),
            ..Default::default()
        });
    });
    for (id, title) in [(10, "Opening"), (11, "Middle"), (12, "Closer")] {
        tracks.restructure("add", Op::Insert, id, |v| {
            v.push(Track {
                id: id as u32,
                title: title.into(),
                playlist: One::to(1u32),
                position: 0.0,
            });
        });
        // Append through the relation, so positions assign.
        lists.elem(1).tracks().add(id as u32);
    }
    assert_eq!(lists.elem(1).tracks().ids(), [10, 11, 12]);
    c.save().expect("seed");

    // Moving the closer to the front is one update of one row's position.
    let sql = c
        .record_sql(|| {
            assert!(lists.elem(1).tracks().move_to(12u32, 0));
        })
        .expect("flush");
    assert_eq!(lists.elem(1).tracks().ids(), [12, 10, 11]);
    assert_eq!(sql.len(), 1, "{sql:?}");
    assert!(sql[0].starts_with("UPDATE \"tracks\" SET \"position\" = ?"));
}

#[test]
fn a_spent_gap_rebalances_and_order_stays_true() {
    let c = ModelContainer::open(Sqlite::memory(), schema![Playlist, Track]).expect("open");
    let lists = c.cache::<Playlist>();
    let tracks = c.cache::<Track>();
    lists.restructure("add", Op::Insert, 1, |v| {
        v.push(Playlist {
            id: 1,
            title: "Bisection".into(),
            ..Default::default()
        });
    });
    for id in 10..14u32 {
        tracks.restructure("add", Op::Insert, id, |v| {
            v.push(Track {
                id,
                title: format!("t{id}"),
                playlist: One::to(1u32),
                position: 0.0,
            });
        });
        lists.elem(1).tracks().add(id);
    }
    // Hammer the same slot until the fractional gap between two neighbors is spent; the
    // rebalance path must keep the order exact throughout.
    for _ in 0..70 {
        assert!(lists.elem(1).tracks().move_to(13u32, 1));
        assert!(lists.elem(1).tracks().move_to(12u32, 1));
    }
    assert_eq!(lists.elem(1).tracks().ids(), [10, 12, 13, 11]);
}

#[test]
fn fk_columns_carry_references_clauses_for_external_writers() {
    let path = temp_db("ddl");
    {
        let _c = ModelContainer::open(Sqlite::at(&path), schema![Trip, Lodging]).expect("open");
    }
    let conn = rusqlite::Connection::open(&path).expect("raw open");
    let (table, from, to, on_delete): (String, String, String, String) = conn
        .query_row(
            "SELECT \"table\", \"from\", \"to\", on_delete FROM pragma_foreign_key_list('lodging')",
            [],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
        )
        .expect("the clause exists");
    assert_eq!(
        (table.as_str(), from.as_str(), to.as_str()),
        ("trips", "trip", "id")
    );
    assert_eq!(on_delete, "CASCADE");
    let _ = std::fs::remove_file(&path);
}

#[test]
fn an_external_cascade_merges_cleanly() {
    let path = temp_db("external");
    let c = ModelContainer::open(Sqlite::at(&path), schema![Trip, Lodging]).expect("open");
    let trips = c.cache::<Trip>();
    let lodging = c.cache::<Lodging>();
    trips.restructure("add", Op::Insert, 1, |v| {
        v.push(Trip {
            id: 1,
            name: "Kyoto".into(),
            ..Default::default()
        });
    });
    lodging.restructure("add", Op::Insert, 10, |v| {
        v.push(Lodging {
            id: 10,
            name: "Ryokan".into(),
            trip: One::to(1u32),
        });
    });
    c.save().expect("save");

    {
        // Another process deletes the trip; that process's engine runs the ON DELETE CASCADE
        // clause.
        let mut other = Sqlite::at(&path).open().expect("second connection");
        other
            .execute("DELETE FROM trips WHERE id = 1", &[])
            .expect("external delete");
    }
    assert!(c.check_external().expect("check"));
    assert!(
        trips.with_untracked(|k| k.get(1).is_none()),
        "parent merged away"
    );
    assert!(
        lodging.with_untracked(|k| k.get(10).is_none()),
        "the file's cascade merged too"
    );
    let _ = std::fs::remove_file(&path);
}

#[test]
fn relations_rebuild_from_a_reopened_file() {
    let path = temp_db("reopen");
    {
        let c = travel_at(&path);
        c.save().expect("save");
    }
    {
        let c = ModelContainer::open(Sqlite::at(&path), schema![Trip, Lodging]).expect("reopen");
        assert_eq!(c.cache::<Trip>().elem(1).lodging().ids(), [10, 11]);
        assert_eq!(c.cache::<Trip>().elem(2).lodging().ids(), [12]);
    }
    let _ = std::fs::remove_file(&path);
}

fn travel_at(path: &std::path::Path) -> ModelContainer {
    let c = ModelContainer::open(Sqlite::at(path), schema![Trip, Lodging]).expect("open");
    let trips = c.cache::<Trip>();
    trips.restructure("add", Op::Insert, 1, |v| {
        v.push(Trip {
            id: 1,
            name: "Kyoto".into(),
            ..Default::default()
        });
    });
    trips.restructure("add", Op::Insert, 2, |v| {
        v.push(Trip {
            id: 2,
            name: "Oslo".into(),
            ..Default::default()
        });
    });
    let lodging = c.cache::<Lodging>();
    for (id, name, trip) in [
        (10, "Ryokan", 1),
        (11, "Machiya", 1),
        (12, "Fjord cabin", 2),
    ] {
        lodging.restructure("add", Op::Insert, id, |v| {
            v.push(Lodging {
                id: id as u32,
                name: name.into(),
                trip: One::to(trip as u32),
            });
        });
    }
    c
}

#[test]
#[expect(
    clippy::items_after_statements,
    reason = "each miswired model sits beside the assertion that names its problem"
)]
fn wiring_validations_name_the_problem() {
    // The relation's target is not in the schema.
    let err = ModelContainer::open(Sqlite::memory(), schema![Trip])
        .err()
        .expect("target missing");
    assert!(err.message.contains("lodging"), "{}", err.message);

    // Nullify needs an Option<One<…>>: a required reference cannot hold nothing.
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "shelves")]
    struct Shelf {
        #[model(id)]
        id: u32,
        #[model(relation(target = Jar, inverse = "shelf", delete = "nullify"))]
        jars: Many<Jar>,
    }
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "jars")]
    struct Jar {
        #[model(id)]
        id: u32,
        shelf: One<Shelf>,
    }
    let err = ModelContainer::open(Sqlite::memory(), schema![Shelf, Jar])
        .err()
        .expect("nullify over required must refuse");
    assert!(err.message.contains("Option"), "{}", err.message);

    // Ordered must name a `REAL` field of the child.
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "racks")]
    struct Rack {
        #[model(id)]
        id: u32,
        #[model(relation(target = Disc, inverse = "rack", delete = "cascade", ordered = "title"))]
        discs: Many<Disc>,
    }
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "discs")]
    struct Disc {
        #[model(id)]
        id: u32,
        title: String,
        rack: One<Rack>,
    }
    let err = ModelContainer::open(Sqlite::memory(), schema![Rack, Disc])
        .err()
        .expect("ordered over TEXT must refuse");
    assert!(err.message.contains("REAL"), "{}", err.message);
}

#[test]
fn queries_filter_by_the_fk_column() {
    let c = travel();
    let q = c
        .query::<Lodging>()
        .filter(Lodging::trip().eq(One::to(1u32)))
        .sort(Lodging::name().asc())
        .live();
    assert_eq!(q.ids(), [11, 10], "Machiya, Ryokan");

    // Reparenting moves the row between result sets.
    c.cache::<Lodging>().elem(12).trip().write(One::to(1u32));
    assert_eq!(q.count(), 3);
    // Renaming re-sorts: name is the sort key.
    c.cache::<Lodging>().elem(12).name().write("Renamed".into());
    assert_eq!(q.ids(), [11, 12, 10], "Machiya, Renamed, Ryokan");
}

#[test]
fn a_dangling_reference_reads_as_a_missing_parent() {
    let c = travel();
    let trips = c.cache::<Trip>();
    let lodging = c.cache::<Lodging>();

    // Bypass the rules: a raw delete of the parent with cascade runs the rule…
    trips.restructure("delete", Op::Delete, 2, |v| {
        v.remove(2);
    });
    // …so nothing dangles. The degrade case is a reference to a key that never loaded:
    lodging.restructure("add", Op::Insert, 99, |v| {
        v.push(Lodging {
            id: 99,
            name: "Orphan".into(),
            trip: One::to(777u32),
        });
    });
    let parent = lodging.elem(99).trip().peek().id().expect("set");
    assert!(!trips.elem(parent).exists(), "deleted-row semantics apply");
}

#[test]
fn delete_rules_are_declared_data() {
    // The derive's const table is API: a tool (or a test) can read the rules.
    assert_eq!(Trip::RELATIONS.len(), 1);
    assert_eq!(Trip::RELATIONS[0].field, "lodging");
    assert_eq!(Trip::RELATIONS[0].inverse, "trip");
    assert_eq!(Trip::RELATIONS[0].delete, DeleteRule::Cascade);
    assert_eq!(Playlist::RELATIONS[0].ordered, Some("position"));
    assert_eq!(Author::RELATIONS[0].delete, DeleteRule::Nullify);
}

#[test]
fn a_renamed_foreign_key_column_still_wires_and_folds() {
    // `#[model(column = …)]` renames the column; the relation names the field. Both halves
    // have to meet (the DDL clause on the renamed column, the change log's field label in
    // the fold), which is what the derive's per-column `field` entry is for.
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "crates_")]
    struct Crate {
        #[model(id)]
        id: u32,
        #[model(relation(target = Bottle, inverse = "holder", delete = "cascade"))]
        bottles: Many<Bottle>,
    }
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "bottles")]
    struct Bottle {
        #[model(id)]
        id: u32,
        label: String,
        #[model(column = "crate_id")]
        holder: One<Crate>,
    }

    let path = temp_db("renamed");
    {
        let c = ModelContainer::open(Sqlite::at(&path), schema![Crate, Bottle]).expect("open");
        let crates = c.cache::<Crate>();
        for id in [1u32, 2] {
            crates.restructure("add", Op::Insert, id, |v| {
                v.push(Crate {
                    id,
                    ..Default::default()
                });
            });
        }
        c.cache::<Bottle>().restructure("add", Op::Insert, 10, |v| {
            v.push(Bottle {
                id: 10,
                label: "Riesling".into(),
                holder: One::to(1u32),
            });
        });
        c.save().expect("seed");
        assert_eq!(crates.elem(1).bottles().ids(), [10]);

        // The fold writes the RENAMED column. (Reparent rather than remove: the inverse is a
        // required `One<…>`, so clearing it is the constraint violation `remove` documents.)
        let sql = c
            .record_sql(|| {
                assert!(crates.elem(2).bottles().add(10));
            })
            .expect("flush");
        assert_eq!(
            sql,
            ["UPDATE \"bottles\" SET \"crate_id\" = ? WHERE \"id\" = ?"]
        );
        assert_eq!(crates.elem(2).bottles().ids(), [10]);
        assert!(crates.elem(1).bottles().is_empty());
    }
    // …and the DDL hung its clause there too.
    let conn = rusqlite::Connection::open(&path).expect("raw open");
    let from: String = conn
        .query_row(
            "SELECT \"from\" FROM pragma_foreign_key_list('bottles')",
            [],
            |r| r.get(0),
        )
        .expect("the clause exists");
    assert_eq!(from, "crate_id");
    let _ = std::fs::remove_file(&path);
}

#[test]
fn ordered_edges_place_correctly() {
    let c = ModelContainer::open(Sqlite::memory(), schema![Playlist, Track]).expect("open");
    let lists = c.cache::<Playlist>();
    let tracks = c.cache::<Track>();
    lists.restructure("add", Op::Insert, 1, |v| {
        v.push(Playlist {
            id: 1,
            title: "Edges".into(),
            ..Default::default()
        });
    });
    let add = |id: u32| {
        tracks.restructure("add", Op::Insert, id, |v| {
            v.push(Track {
                id,
                title: format!("t{id}"),
                playlist: One::to(1u32),
                position: 0.0,
            });
        });
    };

    // insert_at into an empty relation, then before the first, then past the end.
    add(10);
    assert!(lists.elem(1).tracks().insert_at(10u32, 0));
    assert_eq!(lists.elem(1).tracks().ids(), [10]);

    add(11);
    assert!(lists.elem(1).tracks().insert_at(11u32, 0));
    assert_eq!(lists.elem(1).tracks().ids(), [11, 10]);

    add(12);
    assert!(
        lists.elem(1).tracks().insert_at(12u32, 99),
        "an index past the end clamps to last"
    );
    assert_eq!(lists.elem(1).tracks().ids(), [11, 10, 12]);

    // Moving a row to its current index leaves the order as it is, not corrupted.
    assert!(lists.elem(1).tracks().move_to(10u32, 1));
    assert_eq!(lists.elem(1).tracks().ids(), [11, 10, 12]);
}

#[test]
fn a_self_referential_cascade_flushes_as_one_statement() {
    // The shape Day-Sketch has: one table whose rows parent each other. The existing
    // self-referential test asserts which ROWS survive; this one asserts the STATEMENTS,
    // which is where a duplicate would hide.
    let c = ModelContainer::open(Sqlite::memory(), schema![Node]).expect("open");
    let nodes = c.cache::<Node>();
    let ids: Vec<Uuid> = (0..5).map(|_| Uuid::now_v7()).collect();
    // ids[0] is a group holding the other four.
    for (i, id) in ids.iter().enumerate() {
        let parent = (i > 0).then(|| One::to(ids[0]));
        nodes.restructure("add", Op::Insert, *id, |v| {
            v.push(Node {
                id: *id,
                name: format!("n{i}"),
                parent,
                ..Default::default()
            });
        });
    }
    c.save().expect("seed");
    assert_eq!(nodes.elem(ids[0]).children().count(), 4);

    let sql = c
        .record_sql(|| {
            nodes.restructure("delete", Op::Delete, ids[0], |v| {
                v.remove(ModelId::<Node>::of(ids[0]).handle());
            });
        })
        .expect("flush");

    assert!(nodes.keys().is_empty(), "the whole subtree went");
    // One statement for the group; the engine's cascade takes the four it held.
    assert_eq!(sql, ["DELETE FROM \"nodes\" WHERE \"id\" = ?"]);
    assert_eq!(c.table_count::<Node>().expect("count"), 0);
}

#[test]
fn the_engines_own_cascade_is_traced_as_frames() {
    // Diagnosing a report of "the same DELETE five times" in a trace: the fold wrote one
    // statement, and the engine's cascade inside it must not read as four more.
    let path = temp_db("trace-cascade");
    let seen: std::rc::Rc<std::cell::RefCell<Vec<String>>> = std::rc::Rc::default();
    let sink = seen.clone();
    let c = ModelContainer::open(
        Sqlite::at(&path).trace_sql(move |s| sink.borrow_mut().push(s.to_string())),
        schema![Node],
    )
    .expect("open");
    let nodes = c.cache::<Node>();
    let ids: Vec<Uuid> = (0..5).map(|_| Uuid::now_v7()).collect();
    for (i, id) in ids.iter().enumerate() {
        let parent = (i > 0).then(|| One::to(ids[0]));
        nodes.restructure("add", Op::Insert, *id, |v| {
            v.push(Node {
                id: *id,
                name: format!("n{i}"),
                parent,
                ..Default::default()
            });
        });
    }
    c.save().expect("seed");
    seen.borrow_mut().clear();

    let folded = c
        .record_sql(|| {
            nodes.restructure("delete", Op::Delete, ids[0], |v| {
                v.remove(ModelId::<Node>::of(ids[0]).handle());
            });
        })
        .expect("flush");

    let traced: Vec<String> = seen
        .borrow()
        .iter()
        .filter(|s| s.starts_with("DELETE"))
        .cloned()
        .collect();

    // The fold writes one statement for the whole subtree; no row is written twice.
    assert_eq!(folded.len(), 1, "{folded:?}");

    // The engine's own `ON DELETE CASCADE` runs once per child inside that statement. The
    // trace reports the statement once, and each cascaded row as a foreign-key-action frame,
    // so a reader counting DELETE lines counts statements, not rows.
    assert_eq!(
        traced.len(),
        folded.len(),
        "the parent's DELETE is traced once: {traced:?}"
    );
    let parent_hex = format!("x'{}'", hex(ids[0].as_bytes()));
    assert!(
        traced[0].contains(&parent_hex),
        "the traced line is the batched statement with its values expanded: {traced:?}"
    );
    let frames = seen
        .borrow()
        .iter()
        .filter(|s| *s == "-- foreign-key action")
        .count();
    // One action program per deleted parent row (the root's takes all four children, then
    // each child's runs for its own, empty, subtree): frames, never the DELETE again.
    assert!(
        frames >= 1,
        "the cascade is reported as foreign-key-action frames: {:?}",
        seen.borrow()
    );
    let _ = std::fs::remove_file(&path);
}

/// Lowercase hex, for comparing against SQLite's `x'…'` blob literals in a trace.
fn hex(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    bytes.iter().fold(String::new(), |mut out, b| {
        let _ = write!(out, "{b:02x}");
        out
    })
}

#[test]
fn identical_updates_across_rows_flush_as_one_statement() {
    // What a multi-selection edit produces: the same column set to the same value on many
    // rows. They merge; rows written different values keep their own statement, because a
    // single `SET … WHERE id IN (…)` can only carry one value.
    let c = travel();
    let lodging = c.cache::<Lodging>();

    let sql = c
        .record_sql(|| {
            for id in [10u32, 11, 12] {
                lodging.elem(id).name().write("Renamed".into());
            }
        })
        .expect("flush");
    assert_eq!(sql.len(), 1, "{sql:?}");
    assert_eq!(
        sql[0],
        "UPDATE \"lodging\" SET \"name\" = ? WHERE \"id\" IN (?, ?, ?)"
    );

    // Different values cannot share a statement.
    let sql = c
        .record_sql(|| {
            lodging.elem(10).name().write("A".into());
            lodging.elem(11).name().write("B".into());
        })
        .expect("flush");
    assert_eq!(sql.len(), 2, "{sql:?}");
    assert!(
        sql.iter()
            .all(|s| s == "UPDATE \"lodging\" SET \"name\" = ? WHERE \"id\" = ?")
    );

    // A different column set is a different statement too, and the values still land.
    let sql = c
        .record_sql(|| {
            lodging.elem(10).trip().write(One::to(2u32));
            lodging.elem(11).name().write("Shared".into());
            lodging.elem(12).name().write("Shared".into());
        })
        .expect("flush");
    assert_eq!(sql.len(), 2, "{sql:?}");
    assert_eq!(lodging.elem(11).name().peek(), "Shared");
    assert_eq!(lodging.elem(12).name().peek(), "Shared");
}

#[test]
fn a_batched_update_reaches_the_file_for_every_row() {
    // The batching is only worth having if it actually writes every row it names.
    let path = temp_db("batched-update");
    {
        let c = ModelContainer::open(Sqlite::at(&path), schema![Trip, Lodging]).expect("open");
        let trips = c.cache::<Trip>();
        for id in [1u32, 2] {
            trips.restructure("add", Op::Insert, id, |v| {
                v.push(Trip {
                    id,
                    name: "before".into(),
                    ..Default::default()
                });
            });
        }
        c.save().expect("seed");
        let sql = c
            .record_sql(|| {
                trips.elem(1).name().write("after".into());
                trips.elem(2).name().write("after".into());
            })
            .expect("flush");
        assert_eq!(
            sql,
            ["UPDATE \"trips\" SET \"name\" = ? WHERE \"id\" IN (?, ?)"]
        );
    }
    {
        let c = ModelContainer::open(Sqlite::at(&path), schema![Trip, Lodging]).expect("reopen");
        assert_eq!(c.get::<Trip>(1u32).expect("faults").name().peek(), "after");
        assert_eq!(c.get::<Trip>(2u32).expect("faults").name().peek(), "after");
    }
    let _ = std::fs::remove_file(&path);
}

#[test]
fn a_join_rows_composite_key_keeps_its_own_statement() {
    // A membership is addressed by a pair of columns, which no single-column `IN` expresses,
    // so those stay one statement each rather than being merged wrongly.
    let c = ModelContainer::open(Sqlite::memory(), schema![Crate2, Bottle2]).expect("open");
    c.cache::<Crate2>()
        .restructure("add", Op::Insert, 1u32, |v| {
            v.push(Crate2 {
                id: 1,
                ..Default::default()
            });
        });
    for id in [10u32, 11] {
        c.cache::<Bottle2>()
            .restructure("add", Op::Insert, id, |v| {
                v.push(Bottle2 {
                    id,
                    label: format!("b{id}"),
                });
            });
        c.cache::<Crate2>().elem(1u32).bottles().add(id);
    }
    c.save().expect("seed");

    let sql = c
        .record_sql(|| {
            c.cache::<Crate2>().elem(1u32).bottles().clear();
        })
        .expect("flush");
    assert_eq!(sql.len(), 2, "one per membership: {sql:?}");
    assert!(sql.iter().all(|s| s.contains(" AND ")), "{sql:?}");
}

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "crates2")]
struct Crate2 {
    #[model(id)]
    id: u32,
    #[model(relation(target = Bottle2, join = "crate_bottles"))]
    bottles: Many<Bottle2>,
}

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "bottles2")]
struct Bottle2 {
    #[model(id)]
    id: u32,
    label: String,
}