Skip to main content

toasty_driver_integration_suite/tests/
relation_has_many_crud.rs

1//! Test basic has_many associations without any preloading of associations
2//! during query time. All associations are accessed via queries on demand.
3
4use crate::prelude::*;
5use hashbrown::HashMap;
6
7#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
8pub async fn crud_user_todos(test: &mut Test) -> Result<()> {
9    let mut db = setup(test).await;
10
11    // Create a user
12    let user = User::create().name("User 1").exec(&mut db).await?;
13
14    // No TODOs
15    assert_eq!(0, user.todos().exec(&mut db).await?.len());
16
17    // Create a Todo associated with the user
18    let todo = user
19        .todos()
20        .create()
21        .title("hello world")
22        .exec(&mut db)
23        .await?;
24
25    // Find the todo by ID
26    let list = Todo::filter_by_id(todo.id).exec(&mut db).await?;
27
28    assert_eq!(1, list.len());
29    assert_eq!(todo.id, list[0].id);
30
31    // Find the TODO by user ID
32    let list = Todo::filter_by_user_id(user.id).exec(&mut db).await?;
33
34    assert_eq!(1, list.len());
35    assert_eq!(todo.id, list[0].id);
36
37    // Find the User using the Todo
38    let user_reload = User::get_by_id(&mut db, &todo.user_id).await?;
39    assert_eq!(user.id, user_reload.id);
40
41    let mut created = HashMap::new();
42    let mut ids = vec![todo.id];
43    created.insert(todo.id, todo);
44
45    // Create a few more TODOs
46    for i in 0..5 {
47        let title = format!("hello world {i}");
48
49        let todo = if i.is_even() {
50            // Create via user
51            user.todos().create().title(title).exec(&mut db).await?
52        } else {
53            // Create via todo builder
54            Todo::create()
55                .user(&user)
56                .title(title)
57                .exec(&mut db)
58                .await?
59        };
60
61        ids.push(todo.id);
62        assert_none!(created.insert(todo.id, todo));
63    }
64
65    // Load all TODOs
66    let list = user.todos().exec(&mut db).await?;
67
68    assert_eq!(6, list.len());
69
70    let loaded: HashMap<_, _> = list.into_iter().map(|todo| (todo.id, todo)).collect();
71    assert_eq!(6, loaded.len());
72
73    for (id, expect) in &created {
74        assert_eq!(expect.title, loaded[id].title);
75    }
76
77    // Find all TODOs by user (using the belongs_to queries)
78    let list = Todo::filter_by_user_id(user.id).exec(&mut db).await?;
79    assert_eq!(6, list.len());
80
81    let by_id: HashMap<_, _> = list.into_iter().map(|todo| (todo.id, todo)).collect();
82
83    assert_eq!(6, by_id.len());
84
85    for (id, expect) in by_id {
86        assert_eq!(expect.title, loaded[&id].title);
87    }
88
89    // Create a second user
90    let user2 = User::create().name("User 2").exec(&mut db).await?;
91
92    // No TODOs associated with `user2`
93    assert_eq!(0, user2.todos().exec(&mut db).await?.len());
94
95    // Create a TODO for user2
96    let u2_todo = user2
97        .todos()
98        .create()
99        .title("user 2 todo")
100        .exec(&mut db)
101        .await?;
102
103    {
104        let u1_todos = user.todos().exec(&mut db).await?;
105
106        for todo in u1_todos {
107            assert_ne!(u2_todo.id, todo.id);
108        }
109    }
110
111    // Delete a TODO by value
112    let todo = Todo::get_by_id(&mut db, &ids[0]).await?;
113    todo.delete().exec(&mut db).await?;
114
115    // Can no longer get the todo via id
116    assert_err!(Todo::get_by_id(&mut db, &ids[0]).await);
117
118    // Can no longer get the todo scoped
119    assert_err!(user.todos().get_by_id(&mut db, &ids[0]).await);
120
121    // Delete a TODO by scope
122    user.todos()
123        .filter_by_id(ids[1])
124        .delete()
125        .exec(&mut db)
126        .await?;
127
128    // Can no longer get the todo via id
129    assert_err!(Todo::get_by_id(&mut db, &ids[1]).await);
130
131    // Can no longer get the todo scoped
132    assert_err!(user.todos().get_by_id(&mut db, &ids[1]).await);
133
134    // Successfuly a todo by scope
135    user.todos()
136        .filter_by_id(ids[2])
137        .update()
138        .title("batch update 1")
139        .exec(&mut db)
140        .await?;
141
142    let todo = Todo::get_by_id(&mut db, &ids[2]).await?;
143    assert_eq!(todo.title, "batch update 1");
144
145    // Now fail to update it by scoping by other user
146    user2
147        .todos()
148        .filter_by_id(ids[2])
149        .update()
150        .title("batch update 2")
151        .exec(&mut db)
152        .await?;
153
154    let todo = Todo::get_by_id(&mut db, &ids[2]).await?;
155    assert_eq!(todo.title, "batch update 1");
156
157    let id = user.id;
158
159    // Delete the user and associated TODOs are deleted
160    user.delete().exec(&mut db).await?;
161    assert_err!(User::get_by_id(&mut db, &id).await);
162    assert_err!(Todo::get_by_id(&mut db, &ids[2]).await);
163    Ok(())
164}
165
166#[driver_test(id(ID), scenario(crate::scenarios::has_many_belongs_to))]
167pub async fn has_many_insert_on_update(test: &mut Test) -> Result<()> {
168    let mut db = setup(test).await;
169
170    // Create a user, no TODOs
171    let mut user = User::create().name("Alice").exec(&mut db).await?;
172    assert!(user.todos().exec(&mut db).await?.is_empty());
173
174    // Update the user and create a todo in a batch
175    user.update()
176        .name("Bob")
177        .todos(toasty::stmt::insert(Todo::create().title("change name")))
178        .exec(&mut db)
179        .await?;
180
181    assert_eq!("Bob", user.name);
182    let todos: Vec<_> = user.todos().exec(&mut db).await?;
183    assert_eq!(1, todos.len());
184    assert_eq!(todos[0].title, "change name");
185    Ok(())
186}
187
188/// `stmt::apply([])` on a has-many is a no-op: the surface API's empty
189/// Apply loop adds no entry to the assignments map, so the relation
190/// field is treated as unchanged. Run alongside a separate scalar
191/// change because the engine verifier rejects updates with no
192/// assignments at all.
193#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
194pub async fn has_many_apply_empty_is_noop(test: &mut Test) -> Result<()> {
195    let mut db = setup(test).await;
196
197    let mut user = User::create().name("Alice").exec(&mut db).await?;
198    user.todos()
199        .create()
200        .title("existing")
201        .exec(&mut db)
202        .await?;
203
204    user.update()
205        .name("Bob")
206        .todos(toasty::stmt::apply::<toasty::stmt::List<Todo>>([]))
207        .exec(&mut db)
208        .await?;
209
210    assert_eq!(user.name, "Bob");
211    let todos: Vec<_> = user.todos().exec(&mut db).await?;
212    assert_eq!(todos.len(), 1);
213    assert_eq!(todos[0].title, "existing");
214    Ok(())
215}
216
217#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
218pub async fn has_many_apply_multiple_inserts(test: &mut Test) -> Result<()> {
219    let mut db = setup(test).await;
220
221    let mut user = User::create().name("Alice").exec(&mut db).await?;
222
223    user.update()
224        .todos(toasty::stmt::apply([
225            toasty::stmt::insert(Todo::create().title("Buy groceries")),
226            toasty::stmt::insert(Todo::create().title("Walk the dog")),
227        ]))
228        .exec(&mut db)
229        .await?;
230
231    let mut titles: Vec<_> = user
232        .todos()
233        .exec(&mut db)
234        .await?
235        .into_iter()
236        .map(|t| t.title)
237        .collect();
238    titles.sort();
239    assert_eq!(titles, ["Buy groceries", "Walk the dog"]);
240    Ok(())
241}
242
243/// Sanity check for plain `update().todos(stmt::remove(..))` — no
244/// `apply` involved. With a required FK, Remove deletes the child row.
245#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
246pub async fn has_many_update_remove(test: &mut Test) -> Result<()> {
247    let mut db = setup(test).await;
248
249    let mut user = User::create().name("Alice").exec(&mut db).await?;
250    let old_todo = user.todos().create().title("old").exec(&mut db).await?;
251
252    user.update()
253        .todos(toasty::stmt::remove(&old_todo))
254        .exec(&mut db)
255        .await?;
256
257    assert_eq!(0, user.todos().exec(&mut db).await?.len());
258    Ok(())
259}
260
261/// `stmt::apply([insert(..), remove(..)])` mixes Insert and Remove on a
262/// has-many in one update. Each entry dispatches as its own Mutation:
263/// the Insert associates the new child; the Remove dissociates the old
264/// one (and for a required FK, deletes it).
265#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
266pub async fn has_many_apply_insert_and_remove(test: &mut Test) -> Result<()> {
267    let mut db = setup(test).await;
268
269    let mut user = User::create().name("Alice").exec(&mut db).await?;
270    let old_todo = user.todos().create().title("old").exec(&mut db).await?;
271
272    user.update()
273        .todos(toasty::stmt::apply([
274            toasty::stmt::insert(Todo::create().title("new")),
275            toasty::stmt::remove(&old_todo),
276        ]))
277        .exec(&mut db)
278        .await?;
279
280    let titles: Vec<_> = user
281        .todos()
282        .exec(&mut db)
283        .await?
284        .into_iter()
285        .map(|t| t.title)
286        .collect();
287    assert_eq!(titles, ["new"]);
288    Ok(())
289}
290
291/// `stmt::apply([remove(..), insert(..)])` — the reverse of
292/// `has_many_apply_insert_and_remove`. `flatten_relation_batch` always
293/// emits the merged Insert first, so the final state is order-independent:
294/// the new child is associated and the old one is removed.
295#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
296pub async fn has_many_apply_remove_then_insert(test: &mut Test) -> Result<()> {
297    let mut db = setup(test).await;
298
299    let mut user = User::create().name("Alice").exec(&mut db).await?;
300    let old_todo = user.todos().create().title("old").exec(&mut db).await?;
301
302    user.update()
303        .todos(toasty::stmt::apply([
304            toasty::stmt::remove(&old_todo),
305            toasty::stmt::insert(Todo::create().title("new")),
306        ]))
307        .exec(&mut db)
308        .await?;
309
310    let titles: Vec<_> = user
311        .todos()
312        .exec(&mut db)
313        .await?
314        .into_iter()
315        .map(|t| t.title)
316        .collect();
317    assert_eq!(titles, ["new"]);
318    Ok(())
319}
320
321/// `stmt::apply([insert(a), insert(b), remove(c)])` — multiple inserts
322/// merge into one multi-row INSERT, dispatched alongside a separate
323/// Remove. Exercises the Insert-merge path plus a sibling disassociate.
324#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
325pub async fn has_many_apply_two_inserts_and_remove(test: &mut Test) -> Result<()> {
326    let mut db = setup(test).await;
327
328    let mut user = User::create().name("Alice").exec(&mut db).await?;
329    let old_todo = user.todos().create().title("old").exec(&mut db).await?;
330
331    user.update()
332        .todos(toasty::stmt::apply([
333            toasty::stmt::insert(Todo::create().title("a")),
334            toasty::stmt::insert(Todo::create().title("b")),
335            toasty::stmt::remove(&old_todo),
336        ]))
337        .exec(&mut db)
338        .await?;
339
340    let mut titles: Vec<_> = user
341        .todos()
342        .exec(&mut db)
343        .await?
344        .into_iter()
345        .map(|t| t.title)
346        .collect();
347    titles.sort();
348    assert_eq!(titles, ["a", "b"]);
349    Ok(())
350}
351
352/// `stmt::apply([remove(a), remove(b)])` — only disassociations, no
353/// Insert. `flatten_relation_batch` pushes no merged Insert, so both
354/// entries dispatch as standalone Disassociate mutations.
355#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
356pub async fn has_many_apply_multiple_removes(test: &mut Test) -> Result<()> {
357    let mut db = setup(test).await;
358
359    let mut user = User::create().name("Alice").exec(&mut db).await?;
360    let t1 = user.todos().create().title("t1").exec(&mut db).await?;
361    let t2 = user.todos().create().title("t2").exec(&mut db).await?;
362    let t3 = user.todos().create().title("keep").exec(&mut db).await?;
363
364    user.update()
365        .todos(toasty::stmt::apply([
366            toasty::stmt::remove(&t1),
367            toasty::stmt::remove(&t2),
368        ]))
369        .exec(&mut db)
370        .await?;
371
372    let titles: Vec<_> = user
373        .todos()
374        .exec(&mut db)
375        .await?
376        .into_iter()
377        .map(|t| t.title)
378        .collect();
379    assert_eq!(titles, ["keep"]);
380
381    // Required FK: removed todos are deleted, not just unlinked.
382    assert_err!(Todo::get_by_id(&mut db, &t1.id).await);
383    assert_err!(Todo::get_by_id(&mut db, &t2.id).await);
384    assert_ok!(Todo::get_by_id(&mut db, &t3.id).await);
385    Ok(())
386}
387
388/// `stmt::apply([insert(..), remove(..)])` on a has-many with a *nullable*
389/// foreign key. Unlike the required-FK case (which deletes the child),
390/// Remove here takes the disassociate-nullify branch: the old todo
391/// persists with its FK set to NULL.
392#[driver_test(scenario(crate::scenarios::has_many_nullable_fk))]
393pub async fn has_many_apply_insert_and_remove_nullable_fk(test: &mut Test) -> Result<()> {
394    let mut db = setup(test).await;
395
396    let mut user = User::create().exec(&mut db).await?;
397    let old_todo = user.todos().create().title("old").exec(&mut db).await?;
398
399    user.update()
400        .todos(toasty::stmt::apply([
401            toasty::stmt::insert(Todo::create().title("new")),
402            toasty::stmt::remove(&old_todo),
403        ]))
404        .exec(&mut db)
405        .await?;
406
407    let titles: Vec<_> = user
408        .todos()
409        .exec(&mut db)
410        .await?
411        .into_iter()
412        .map(|t| t.title)
413        .collect();
414    assert_eq!(titles, ["new"]);
415
416    // Nullable FK: the removed todo is unlinked, not deleted.
417    let reloaded = Todo::get_by_id(&mut db, &old_todo.id).await?;
418    assert_none!(reloaded.user_id);
419    Ok(())
420}
421
422/// Order-sensitive swap: the child has a `#[unique]` title and we replace
423/// the "X" todo by removing the old one and inserting a fresh "X". With a
424/// required FK, `remove` deletes the old row (freeing the unique title), so
425/// the insert can reuse it — but only if the delete runs first.
426///
427/// `flatten_relation_batch` dispatches the merged Insert after the batch's
428/// removes, so the delete lands before the insert and the swap succeeds
429/// regardless of the order the caller wrote the entries.
430#[driver_test(scenario(crate::scenarios::has_many_unique_title))]
431pub async fn has_many_apply_swap_unique_required_fk(test: &mut Test) -> Result<()> {
432    let mut db = setup(test).await;
433
434    let mut user = User::create().exec(&mut db).await?;
435    let old = user.todos().create().title("X").exec(&mut db).await?;
436
437    user.update()
438        .todos(toasty::stmt::apply([
439            toasty::stmt::remove(&old),
440            toasty::stmt::insert(Todo::create().title("X")),
441        ]))
442        .exec(&mut db)
443        .await?;
444
445    let titles: Vec<_> = user
446        .todos()
447        .exec(&mut db)
448        .await?
449        .into_iter()
450        .map(|t| t.title)
451        .collect();
452    assert_eq!(titles, ["X"]);
453    Ok(())
454}
455
456/// Same unique-title swap, but with an unrelated `insert` at the *front* of
457/// the batch. `flatten_relation_batch` merges all inserts into one multi-row
458/// INSERT, so the unrelated "Y" insert and the swap's new "X" insert become a
459/// single statement. That merged INSERT must still be dispatched after the
460/// `remove`, or the new "X" collides with the old one on the unique
461/// constraint — i.e. coalescing inserts must not pull them ahead of removes.
462#[driver_test(scenario(crate::scenarios::has_many_unique_title))]
463pub async fn has_many_apply_swap_unique_with_extra_insert(test: &mut Test) -> Result<()> {
464    let mut db = setup(test).await;
465
466    let mut user = User::create().exec(&mut db).await?;
467    let old = user.todos().create().title("X").exec(&mut db).await?;
468
469    user.update()
470        .todos(toasty::stmt::apply([
471            toasty::stmt::insert(Todo::create().title("Y")),
472            toasty::stmt::remove(&old),
473            toasty::stmt::insert(Todo::create().title("X")),
474        ]))
475        .exec(&mut db)
476        .await?;
477
478    let mut titles: Vec<_> = user
479        .todos()
480        .exec(&mut db)
481        .await?
482        .into_iter()
483        .map(|t| t.title)
484        .collect();
485    titles.sort();
486    assert_eq!(titles, ["X", "Y"]);
487    Ok(())
488}
489
490/// Inserting and removing the *same existing* record in one batch honors
491/// entry order. `insert(&t)` (associate an existing row) and `remove(&t)`
492/// (dissociate it) both lower to UPDATEs on the same row; the batch sequences
493/// its entries so the last-written op wins, instead of the two UPDATEs racing
494/// in the dependency graph.
495///
496/// Note this is orthogonal to `flatten_relation_batch`'s insert-last reorder —
497/// that only moves create-new inserts (`Todo::create()`), not
498/// associate-existing inserts (`&todo`), which keep their written position.
499#[driver_test(scenario(crate::scenarios::has_many_nullable_fk))]
500pub async fn has_many_apply_insert_remove_same_item(test: &mut Test) -> Result<()> {
501    use toasty_core::{
502        driver::Operation,
503        stmt::{Assignment, ExprSet, Statement, Update},
504    };
505
506    // Drain the op log into one marker per FK-writing UPDATE: "unlink" for
507    // `Set(NULL)` (dissociate), "link" otherwise (associate). Transaction,
508    // savepoint, and read (COUNT/EXISTS) ops are ignored. SQL drivers only —
509    // key-value drivers emit a different op shape.
510    fn fk_writes(test: &Test) -> Vec<&'static str> {
511        fn classify(update: &Update, out: &mut Vec<&'static str>) {
512            for (_, assignment) in update.assignments.iter() {
513                if let Assignment::Set(expr) = assignment {
514                    out.push(if expr.is_value_null() {
515                        "unlink"
516                    } else {
517                        "link"
518                    });
519                }
520            }
521        }
522
523        let mut out = vec![];
524        while !test.log().is_empty() {
525            let Operation::QuerySql(q) = test.log().pop().0 else {
526                continue;
527            };
528            match &q.stmt {
529                // The associate update, plus the dissociate's write half on
530                // drivers without `cte_with_update` (its conditional update
531                // lowers to a read-modify-write with a bare UPDATE).
532                Statement::Update(update) => classify(update, &mut out),
533                // On a `cte_with_update` driver (e.g. PostgreSQL), the
534                // conditional dissociate folds its count check and UPDATE into
535                // a single CTE query; the UPDATE lives in a `With` CTE.
536                Statement::Query(query) => {
537                    for cte in query.with.iter().flat_map(|with| &with.ctes) {
538                        if let ExprSet::Update(update) = &cte.query.body {
539                            classify(update, &mut out);
540                        }
541                    }
542                }
543                _ => {}
544            }
545        }
546        out
547    }
548
549    let mut db = setup(test).await;
550
551    // remove then insert → insert wins → still associated.
552    let mut keep = User::create().exec(&mut db).await?;
553    let kt = keep.todos().create().title("t").exec(&mut db).await?;
554    test.log().clear();
555    keep.update()
556        .todos(toasty::stmt::apply([
557            toasty::stmt::remove(&kt),
558            toasty::stmt::insert(&kt),
559        ]))
560        .exec(&mut db)
561        .await?;
562    if test.capability().sql() {
563        // Dissociate executes before associate.
564        assert_eq!(fk_writes(test), ["unlink", "link"]);
565    }
566    assert_eq!(keep.todos().exec(&mut db).await?.len(), 1);
567
568    // insert then remove → remove wins → dissociated.
569    let mut drop = User::create().exec(&mut db).await?;
570    let dt = drop.todos().create().title("t").exec(&mut db).await?;
571    test.log().clear();
572    drop.update()
573        .todos(toasty::stmt::apply([
574            toasty::stmt::insert(&dt),
575            toasty::stmt::remove(&dt),
576        ]))
577        .exec(&mut db)
578        .await?;
579    if test.capability().sql() {
580        // Associate executes before dissociate.
581        assert_eq!(fk_writes(test), ["link", "unlink"]);
582    }
583    assert_eq!(drop.todos().exec(&mut db).await?.len(), 0);
584    Ok(())
585}
586
587/// Nested `stmt::apply([apply([..]), ..])`. The surface API flattens
588/// nested applies into a single flat `Batch` (the engine never sees
589/// nesting), so this must behave identically to the equivalent flat
590/// batch. Guards the flattening contract — if nesting ever stopped
591/// flattening, the engine's `flatten_relation_batch` dispatch would hit
592/// its `unreachable!` arm.
593#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
594pub async fn has_many_apply_nested(test: &mut Test) -> Result<()> {
595    let mut db = setup(test).await;
596
597    let mut user = User::create().name("Alice").exec(&mut db).await?;
598    let old1 = user.todos().create().title("old1").exec(&mut db).await?;
599    let old2 = user.todos().create().title("old2").exec(&mut db).await?;
600
601    user.update()
602        .todos(toasty::stmt::apply([
603            toasty::stmt::apply([
604                toasty::stmt::insert(Todo::create().title("a")),
605                toasty::stmt::insert(Todo::create().title("b")),
606            ]),
607            toasty::stmt::apply([toasty::stmt::remove(&old1), toasty::stmt::remove(&old2)]),
608            toasty::stmt::insert(Todo::create().title("c")),
609        ]))
610        .exec(&mut db)
611        .await?;
612
613    let mut titles: Vec<_> = user
614        .todos()
615        .exec(&mut db)
616        .await?
617        .into_iter()
618        .map(|t| t.title)
619        .collect();
620    titles.sort();
621    assert_eq!(titles, ["a", "b", "c"]);
622    Ok(())
623}
624
625/// Deterministic matrix over batch shapes. For each
626/// `(existing, insert, remove)` combination, build one
627/// `stmt::apply([...])` carrying `insert` new children plus `remove`
628/// dissociations, then compare the resulting association set against a
629/// reference computed in memory. This covers larger batches and more
630/// combinations than the targeted tests above without the
631/// non-determinism (and sync/async friction) of a `proptest` runner.
632#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
633pub async fn has_many_apply_combinations(test: &mut Test) -> Result<()> {
634    let mut db = setup(test).await;
635
636    for num_existing in 0..=3usize {
637        for num_insert in 0..=3usize {
638            for num_remove in 0..=num_existing {
639                // An empty batch produces no assignments, which the engine
640                // rejects as an empty update. Covered by
641                // `has_many_apply_empty_is_noop`.
642                if num_insert == 0 && num_remove == 0 {
643                    continue;
644                }
645
646                let mut user = User::create()
647                    .name(format!("u-{num_existing}-{num_insert}-{num_remove}"))
648                    .exec(&mut db)
649                    .await?;
650
651                // Seed existing children: e0..e{num_existing}.
652                let mut existing = Vec::new();
653                for i in 0..num_existing {
654                    existing.push(
655                        user.todos()
656                            .create()
657                            .title(format!("e{i}"))
658                            .exec(&mut db)
659                            .await?,
660                    );
661                }
662
663                // One batch: `num_insert` inserts + `num_remove` removes.
664                let mut ops: Vec<toasty::stmt::Assignment<toasty::stmt::List<Todo>>> = Vec::new();
665                for i in 0..num_insert {
666                    ops.push(toasty::stmt::insert(Todo::create().title(format!("n{i}"))));
667                }
668                for todo in &existing[..num_remove] {
669                    ops.push(toasty::stmt::remove(todo));
670                }
671
672                user.update()
673                    .todos(toasty::stmt::apply(ops))
674                    .exec(&mut db)
675                    .await?;
676
677                // Reference: surviving existing + inserted.
678                let mut expected: Vec<String> = existing[num_remove..]
679                    .iter()
680                    .map(|t| t.title.clone())
681                    .collect();
682                for i in 0..num_insert {
683                    expected.push(format!("n{i}"));
684                }
685                expected.sort();
686
687                let mut actual: Vec<String> = user
688                    .todos()
689                    .exec(&mut db)
690                    .await?
691                    .into_iter()
692                    .map(|t| t.title)
693                    .collect();
694                actual.sort();
695
696                assert_eq!(
697                    actual, expected,
698                    "existing={num_existing} insert={num_insert} remove={num_remove}"
699                );
700            }
701        }
702    }
703    Ok(())
704}
705
706#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
707pub async fn scoped_find_by_id(test: &mut Test) -> Result<()> {
708    let mut db = setup(test).await;
709
710    // Create a couple of users
711    let user1 = User::create().name("User 1").exec(&mut db).await?;
712    let user2 = User::create().name("User 2").exec(&mut db).await?;
713
714    // Create a todo
715    let todo = user1
716        .todos()
717        .create()
718        .title("hello world")
719        .exec(&mut db)
720        .await?;
721
722    // Find it scoped by user1
723    let reloaded = user1.todos().get_by_id(&mut db, &todo.id).await?;
724    assert_eq!(reloaded.id, todo.id);
725    assert_eq!(reloaded.title, todo.title);
726
727    // Trying to find the same todo scoped by user2 is missing
728    assert_none!(
729        user2
730            .todos()
731            .filter_by_id(todo.id)
732            .first()
733            .exec(&mut db)
734            .await?
735    );
736
737    let reloaded = User::filter_by_id(user1.id)
738        .todos()
739        .get_by_id(&mut db, &todo.id)
740        .await?;
741
742    assert_eq!(reloaded.id, todo.id);
743    assert_eq!(reloaded.title, todo.title);
744
745    // Deleting the TODO from the user 2 scope fails
746    user2
747        .todos()
748        .filter_by_id(todo.id)
749        .delete()
750        .exec(&mut db)
751        .await?;
752    let reloaded = user1.todos().get_by_id(&mut db, &todo.id).await?;
753    assert_eq!(reloaded.id, todo.id);
754    Ok(())
755}
756
757// When the FK is composite, things should still work
758#[driver_test(scenario(crate::scenarios::composite_has_many_belongs_to))]
759pub async fn has_many_when_fk_is_composite(test: &mut Test) -> Result<()> {
760    let mut db = setup(test).await;
761
762    // Create a user
763    let user = User::create().name("User 1").exec(&mut db).await?;
764
765    // No TODOs
766    assert_eq!(0, user.todos().exec(&mut db).await?.len());
767
768    // Create a Todo associated with the user
769    let todo = user
770        .todos()
771        .create()
772        .title("hello world")
773        .exec(&mut db)
774        .await?;
775
776    // Find the todo by ID
777    let list = Todo::filter_by_user_id_and_id(user.id, todo.id)
778        .exec(&mut db)
779        .await?;
780
781    assert_eq!(1, list.len());
782    assert_eq!(todo.id, list[0].id);
783
784    // Find the TODO by user ID
785    let list = Todo::filter_by_user_id(user.id).exec(&mut db).await?;
786
787    assert_eq!(1, list.len());
788    assert_eq!(todo.id, list[0].id);
789
790    let mut created = HashMap::new();
791    let mut ids = vec![todo.id];
792    created.insert(todo.id, todo);
793
794    // Create a few more TODOs
795    for i in 0..5 {
796        let title = format!("hello world {i}");
797
798        let todo = if i.is_even() {
799            // Create via user
800            user.todos().create().title(title).exec(&mut db).await?
801        } else {
802            // Create via todo builder
803            Todo::create()
804                .user(&user)
805                .title(title)
806                .exec(&mut db)
807                .await?
808        };
809
810        ids.push(todo.id);
811        assert_none!(created.insert(todo.id, todo));
812    }
813
814    // Load all TODOs
815    let list = user.todos().exec(&mut db).await?;
816
817    assert_eq!(6, list.len());
818
819    let loaded: HashMap<_, _> = list.into_iter().map(|todo| (todo.id, todo)).collect();
820    assert_eq!(6, loaded.len());
821
822    for (id, expect) in &created {
823        assert_eq!(expect.title, loaded[id].title);
824    }
825
826    // Find all TODOs by user (using the belongs_to queries)
827    let list = Todo::filter_by_user_id(user.id).exec(&mut db).await?;
828    assert_eq!(6, list.len());
829
830    let by_id: HashMap<_, _> = list.into_iter().map(|todo| (todo.id, todo)).collect();
831
832    assert_eq!(6, by_id.len());
833
834    for (id, expect) in by_id {
835        assert_eq!(expect.title, loaded[&id].title);
836    }
837
838    // Create a second user
839    let user2 = User::create().name("User 2").exec(&mut db).await?;
840
841    // No TODOs associated with `user2`
842    assert_eq!(0, user2.todos().exec(&mut db).await?.len());
843
844    // Create a TODO for user2
845    let u2_todo = user2
846        .todos()
847        .create()
848        .title("user 2 todo")
849        .exec(&mut db)
850        .await?;
851
852    let u1_todos = user.todos().exec(&mut db).await?;
853
854    for todo in u1_todos {
855        assert_ne!(u2_todo.id, todo.id);
856    }
857
858    // Delete a TODO by value
859    let todo = Todo::get_by_user_id_and_id(&mut db, &user.id, &ids[0]).await?;
860    todo.delete().exec(&mut db).await?;
861
862    // Can no longer get the todo via id
863    assert_err!(Todo::get_by_user_id_and_id(&mut db, &user.id, &ids[0]).await);
864
865    // Can no longer get the todo scoped
866    assert_err!(user.todos().get_by_id(&mut db, &ids[0]).await);
867
868    // Delete a TODO by scope
869    user.todos()
870        .filter_by_id(ids[1])
871        .delete()
872        .exec(&mut db)
873        .await?;
874
875    // Can no longer get the todo via id
876    assert_err!(Todo::get_by_user_id_and_id(&mut db, &user.id, &ids[1]).await);
877
878    // Can no longer get the todo scoped
879    assert_err!(user.todos().get_by_id(&mut db, &ids[1]).await);
880
881    // Successfuly a todo by scope
882    user.todos()
883        .filter_by_id(ids[2])
884        .update()
885        .title("batch update 1")
886        .exec(&mut db)
887        .await?;
888    let todo = Todo::get_by_user_id_and_id(&mut db, &user.id, &ids[2]).await?;
889    assert_eq!(todo.title, "batch update 1");
890
891    // Now fail to update it by scoping by other user
892    user2
893        .todos()
894        .filter_by_id(ids[2])
895        .update()
896        .title("batch update 2")
897        .exec(&mut db)
898        .await?;
899    let todo = Todo::get_by_user_id_and_id(&mut db, &user.id, &ids[2]).await?;
900    assert_eq!(todo.title, "batch update 1");
901    Ok(())
902}
903
904#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
905pub async fn belongs_to_required(test: &mut Test) {
906    let mut db = setup(test).await;
907
908    assert_err!(Todo::create().exec(&mut db).await);
909}
910
911#[driver_test(scenario(crate::scenarios::has_many_nullable_fk))]
912pub async fn delete_when_belongs_to_optional(test: &mut Test) -> Result<()> {
913    let mut db = setup(test).await;
914
915    let user = User::create().exec(&mut db).await?;
916    let mut ids = vec![];
917
918    for _ in 0..3 {
919        let todo = user.todos().create().title("todo").exec(&mut db).await?;
920        ids.push(todo.id);
921    }
922
923    // Delete the user
924    user.delete().exec(&mut db).await?;
925
926    // All the todos still exist and `user` is set to `None`.
927    for id in ids {
928        let todo = Todo::get_by_id(&mut db, id).await?;
929        assert_none!(todo.user_id);
930    }
931
932    // Deleting a user leaves the todo in place.
933    Ok(())
934}
935
936#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
937pub async fn associate_new_user_with_todo_on_update_via_creation(test: &mut Test) -> Result<()> {
938    let mut db = setup(test).await;
939
940    // Create a user with a todo
941    let u1 = User::create()
942        .name("User 1")
943        .todos([Todo::create().title("hello world")])
944        .exec(&mut db)
945        .await?;
946
947    // Get the todo
948    let todos: Vec<_> = u1.todos().exec(&mut db).await?;
949    assert_eq!(1, todos.len());
950    let mut todo = todos.into_iter().next().unwrap();
951
952    todo.update()
953        .user(User::create().name("User 2"))
954        .exec(&mut db)
955        .await?;
956    Ok(())
957}
958
959#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
960pub async fn associate_new_user_with_todo_on_update_query_via_creation(
961    test: &mut Test,
962) -> Result<()> {
963    let mut db = setup(test).await;
964
965    // Create a user with a todo
966    let u1 = User::create()
967        .name("User 1")
968        .todos([Todo::create().title("a todo")])
969        .exec(&mut db)
970        .await?;
971
972    // Get the todo
973    let todos: Vec<_> = u1.todos().exec(&mut db).await?;
974    assert_eq!(1, todos.len());
975    let todo = todos.into_iter().next().unwrap();
976
977    Todo::filter_by_id(todo.id)
978        .update()
979        .user(User::create().name("User 2"))
980        .exec(&mut db)
981        .await?;
982    Ok(())
983}
984
985#[driver_test]
986#[should_panic]
987pub async fn update_user_with_null_todo_is_err(test: &mut Test) -> Result<()> {
988    #[derive(Debug, toasty::Model)]
989    struct User {
990        #[key]
991        #[auto]
992        id: uuid::Uuid,
993
994        #[has_many]
995        todos: toasty::Deferred<Vec<Todo>>,
996    }
997
998    #[derive(Debug, toasty::Model)]
999    struct Todo {
1000        #[key]
1001        #[auto]
1002        id: uuid::Uuid,
1003
1004        #[index]
1005        user_id: uuid::Uuid,
1006
1007        #[belongs_to(key = user_id, references = id)]
1008        user: toasty::Deferred<User>,
1009    }
1010
1011    use toasty::stmt::{self, IntoExpr};
1012
1013    let mut db = test.setup_db(models!(User, Todo)).await;
1014
1015    // Create a user with a todo
1016    let u1 = User::create().todos([Todo::create()]).exec(&mut db).await?;
1017
1018    // Get the todo
1019    let todos: Vec<_> = u1.todos().exec(&mut db).await?;
1020    assert_eq!(1, todos.len());
1021    let todo = todos.into_iter().next().unwrap();
1022
1023    // Updating the todo w/ null is an error. Thus requires a bit of a hack to make work
1024    let mut stmt: stmt::Update<Todo> =
1025        stmt::Update::new(stmt::Query::from_expr((&todo).into_expr()));
1026    stmt.set(2, toasty_core::stmt::Value::Null);
1027    stmt.exec(&mut db).await?;
1028
1029    // User is not deleted
1030    let u1_reloaded = User::get_by_id(&mut db, &u1.id).await?;
1031    assert_eq!(u1_reloaded.id, u1.id);
1032    Ok(())
1033}
1034
1035#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
1036pub async fn assign_todo_that_already_has_user_on_create(test: &mut Test) -> Result<()> {
1037    let mut db = setup(test).await;
1038
1039    let todo = Todo::create()
1040        .title("a todo")
1041        .user(User::create().name("User 1"))
1042        .exec(&mut db)
1043        .await?;
1044
1045    let u1 = todo.user().exec(&mut db).await?;
1046
1047    let u2 = User::create()
1048        .name("User 2")
1049        .todos([&todo])
1050        .exec(&mut db)
1051        .await?;
1052
1053    let todo_reload = Todo::get_by_id(&mut db, &todo.id).await?;
1054
1055    assert_eq!(u2.id, todo_reload.user_id);
1056
1057    // First user has no todos
1058    let todos: Vec<_> = u1.todos().exec(&mut db).await?;
1059    assert_eq!(0, todos.len());
1060
1061    // Second user has the todo
1062    let todos: Vec<_> = u2.todos().exec(&mut db).await?;
1063    assert_eq!(1, todos.len());
1064    assert_eq!(todo.id, todos[0].id);
1065    Ok(())
1066}
1067
1068#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
1069pub async fn assign_todo_that_already_has_user_on_update(test: &mut Test) -> Result<()> {
1070    let mut db = setup(test).await;
1071
1072    let todo = Todo::create()
1073        .title("a todo")
1074        .user(User::create().name("User 1"))
1075        .exec(&mut db)
1076        .await?;
1077
1078    let u1 = todo.user().exec(&mut db).await?;
1079
1080    let mut u2 = User::create().name("User 2").exec(&mut db).await?;
1081
1082    // Update the user
1083    u2.update()
1084        .todos(toasty::stmt::insert(&todo))
1085        .exec(&mut db)
1086        .await?;
1087
1088    let todo_reload = Todo::get_by_id(&mut db, &todo.id).await?;
1089
1090    assert_eq!(u2.id, todo_reload.user_id);
1091
1092    // First user has no todos
1093    let todos: Vec<_> = u1.todos().exec(&mut db).await?;
1094    assert_eq!(0, todos.len());
1095
1096    // Second user has the todo
1097    let todos: Vec<_> = u2.todos().exec(&mut db).await?;
1098    assert_eq!(1, todos.len());
1099    assert_eq!(todo.id, todos[0].id);
1100    Ok(())
1101}
1102
1103#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
1104pub async fn assign_existing_user_to_todo(test: &mut Test) -> Result<()> {
1105    let mut db = setup(test).await;
1106
1107    let mut todo = Todo::create()
1108        .title("hello")
1109        .user(User::create().name("User 1"))
1110        .exec(&mut db)
1111        .await?;
1112
1113    let u1 = todo.user().exec(&mut db).await?;
1114
1115    let u2 = User::create().name("User 2").exec(&mut db).await?;
1116
1117    // Update the todo
1118    todo.update().user(&u2).exec(&mut db).await?;
1119
1120    let todo_reload = Todo::get_by_id(&mut db, &todo.id).await?;
1121
1122    assert_eq!(u2.id, todo_reload.user_id);
1123
1124    // First user has no todos
1125    let todos: Vec<_> = u1.todos().exec(&mut db).await?;
1126    assert_eq!(0, todos.len());
1127
1128    // Second user has the todo
1129    let todos: Vec<_> = u2.todos().exec(&mut db).await?;
1130    assert_eq!(1, todos.len());
1131    assert_eq!(todo.id, todos[0].id);
1132    Ok(())
1133}
1134
1135#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
1136pub async fn assign_todo_to_user_on_update_query(test: &mut Test) -> Result<()> {
1137    let mut db = setup(test).await;
1138
1139    let user = User::create().name("User 1").exec(&mut db).await?;
1140
1141    User::filter_by_id(user.id)
1142        .update()
1143        .todos(toasty::stmt::insert(Todo::create().title("hello")))
1144        .exec(&mut db)
1145        .await?;
1146
1147    let todos: Vec<_> = user.todos().exec(&mut db).await?;
1148    assert_eq!(1, todos.len());
1149    assert_eq!("hello", todos[0].title);
1150    Ok(())
1151}
1152
1153#[driver_test(scenario(crate::scenarios::composite_has_many_belongs_to))]
1154pub async fn has_many_when_fk_is_composite_with_snippets(test: &mut Test) -> Result<()> {
1155    let mut db = setup(test).await;
1156
1157    // Create users
1158    let user1 = User::create().name("User 1").exec(&mut db).await?;
1159    let user2 = User::create().name("User 2").exec(&mut db).await?;
1160
1161    // Create a Todo associated with the user
1162    user1
1163        .todos()
1164        .create()
1165        .title("hello world")
1166        .exec(&mut db)
1167        .await?;
1168
1169    let todo2 = user2
1170        .todos()
1171        .create()
1172        .title("hello world")
1173        .exec(&mut db)
1174        .await?;
1175
1176    // Update the Todos with the snippets
1177    Todo::update_by_user_id(user1.id)
1178        .title("Title 2")
1179        .exec(&mut db)
1180        .await?;
1181
1182    let todo = Todo::get_by_user_id(&mut db, user1.id).await?;
1183    assert!(todo.title == "Title 2");
1184
1185    Todo::update_by_user_id_and_id(user2.id, todo2.id)
1186        .title("Title 3")
1187        .exec(&mut db)
1188        .await?;
1189
1190    let todo = Todo::get_by_user_id_and_id(&mut db, user2.id, todo2.id).await?;
1191    assert!(todo.title == "Title 3");
1192
1193    // Delete the Todos with the snippets
1194    Todo::delete_by_user_id(&mut db, user1.id).await?;
1195    assert_err!(Todo::get_by_user_id(&mut db, user1.id).await);
1196
1197    Todo::delete_by_user_id_and_id(&mut db, user2.id, todo2.id).await?;
1198    assert_err!(Todo::get_by_user_id_and_id(&mut db, user2.id, todo2.id).await);
1199
1200    Ok(())
1201}