Skip to main content

toasty_driver_integration_suite/tests/
select_projection_belongs_to.rs

1//! `.select(...)` projection through a `BelongsTo` relation field.
2//!
3//! Projects the related-model side of the relation directly: a query rooted
4//! at the source model returns one related-model record per source row.
5
6use crate::prelude::*;
7
8#[driver_test(
9    requires(scan),
10    scenario(crate::scenarios::has_many_belongs_to::id_uuid)
11)]
12pub async fn select_belongs_to(t: &mut Test) -> Result<()> {
13    let mut db = setup(t).await;
14
15    let alice = toasty::create!(User { name: "Alice" })
16        .exec(&mut db)
17        .await?;
18    toasty::create!(Todo {
19        title: "Hello",
20        user: alice
21    })
22    .exec(&mut db)
23    .await?;
24
25    let users: Vec<User> = Todo::all()
26        .select(Todo::fields().user())
27        .exec(&mut db)
28        .await?;
29
30    assert_eq!(users.len(), 1);
31    assert_eq!(users[0].name, "Alice");
32
33    let bob = toasty::create!(User { name: "Bob" }).exec(&mut db).await?;
34    toasty::create!(Todo {
35        title: "Beta",
36        user: bob,
37    })
38    .exec(&mut db)
39    .await?;
40
41    let users: Vec<User> = Todo::filter(Todo::fields().title().eq("Beta"))
42        .select(Todo::fields().user())
43        .exec(&mut db)
44        .await?;
45
46    assert_eq!(users.len(), 1);
47    assert_eq!(users[0].name, "Bob");
48
49    let user: Option<User> = Todo::filter(Todo::fields().title().eq("Hello"))
50        .select(Todo::fields().user())
51        .first()
52        .exec(&mut db)
53        .await?;
54
55    assert_eq!(user.map(|u| u.name).as_deref(), Some("Alice"));
56    Ok(())
57}
58
59#[driver_test(scenario(crate::scenarios::has_many_belongs_to::id_uuid))]
60pub async fn select_belongs_to_in_list(t: &mut Test) -> Result<()> {
61    let mut db = setup(t).await;
62
63    let alice = toasty::create!(User { name: "Alice" })
64        .exec(&mut db)
65        .await?;
66    let todo = toasty::create!(Todo {
67        title: "Hello",
68        user: &alice,
69    })
70    .exec(&mut db)
71    .await?;
72
73    let users: Vec<Vec<User>> = Todo::filter_by_id(todo.id)
74        .select(toasty::stmt::Expr::list([Todo::fields().user()]))
75        .exec(&mut db)
76        .await?;
77
78    assert_struct!(users, [[{ id: == alice.id, name: "Alice" }]]);
79    Ok(())
80}