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    id(ID),
10    requires(scan),
11    scenario(crate::scenarios::has_many_belongs_to)
12)]
13pub async fn select_belongs_to_basic(t: &mut Test) -> Result<()> {
14    let mut db = setup(t).await;
15
16    let alice = toasty::create!(User { name: "Alice" })
17        .exec(&mut db)
18        .await?;
19    toasty::create!(Todo {
20        title: "Hello",
21        user: alice
22    })
23    .exec(&mut db)
24    .await?;
25
26    let users: Vec<User> = Todo::all()
27        .select(Todo::fields().user())
28        .exec(&mut db)
29        .await?;
30
31    assert_eq!(users.len(), 1);
32    assert_eq!(users[0].name, "Alice");
33    Ok(())
34}
35
36#[driver_test(
37    id(ID),
38    requires(scan),
39    scenario(crate::scenarios::has_many_belongs_to)
40)]
41pub async fn select_belongs_to_with_filter(t: &mut Test) -> Result<()> {
42    let mut db = setup(t).await;
43
44    let alice = toasty::create!(User { name: "Alice" })
45        .exec(&mut db)
46        .await?;
47    let bob = toasty::create!(User { name: "Bob" }).exec(&mut db).await?;
48    toasty::create!(Todo::[
49        { title: "Alpha", user: alice },
50        { title: "Beta",  user: bob },
51    ])
52    .exec(&mut db)
53    .await?;
54
55    let users: Vec<User> = Todo::filter(Todo::fields().title().eq("Beta"))
56        .select(Todo::fields().user())
57        .exec(&mut db)
58        .await?;
59
60    assert_eq!(users.len(), 1);
61    assert_eq!(users[0].name, "Bob");
62    Ok(())
63}
64
65#[driver_test(
66    id(ID),
67    requires(scan),
68    scenario(crate::scenarios::has_many_belongs_to)
69)]
70pub async fn select_belongs_to_first(t: &mut Test) -> Result<()> {
71    let mut db = setup(t).await;
72
73    let alice = toasty::create!(User { name: "Alice" })
74        .exec(&mut db)
75        .await?;
76    toasty::create!(Todo {
77        title: "Hello",
78        user: alice
79    })
80    .exec(&mut db)
81    .await?;
82
83    let user: Option<User> = Todo::filter(Todo::fields().title().eq("Hello"))
84        .select(Todo::fields().user())
85        .first()
86        .exec(&mut db)
87        .await?;
88
89    assert_eq!(user.map(|u| u.name).as_deref(), Some("Alice"));
90    Ok(())
91}