toasty_driver_integration_suite/tests/
select_projection_has_one.rs1use crate::prelude::*;
12
13#[driver_test(requires(sql))]
14pub async fn select_has_one(t: &mut Test) -> Result<()> {
15 #[derive(Debug, toasty::Model)]
16 struct User {
17 #[key]
18 #[auto]
19 id: uuid::Uuid,
20 name: String,
21
22 #[has_one]
23 profile: toasty::Deferred<Profile>,
24 }
25
26 #[derive(Debug, toasty::Model)]
27 struct Profile {
28 #[key]
29 #[auto]
30 id: uuid::Uuid,
31
32 #[unique]
33 user_id: Option<uuid::Uuid>,
34
35 #[belongs_to(key = user_id, references = id)]
36 user: toasty::Deferred<Option<User>>,
37
38 bio: String,
39 }
40
41 let mut db = t.setup_db(models!(User, Profile)).await;
42
43 toasty::create!(User {
44 name: "Alice",
45 profile: Profile::create().bio("apple a day"),
46 })
47 .exec(&mut db)
48 .await?;
49
50 let profiles: Vec<Profile> = User::all()
51 .select(User::fields().profile())
52 .exec(&mut db)
53 .await?;
54
55 assert_eq!(profiles.len(), 1);
56 assert_eq!(profiles[0].bio, "apple a day");
57
58 let bios: Vec<String> = User::all()
59 .select(User::fields().profile().bio())
60 .exec(&mut db)
61 .await?;
62
63 assert_eq!(bios, ["apple a day"]);
64
65 toasty::create!(User {
66 name: "Bob",
67 profile: Profile::create().bio("beta bio"),
68 })
69 .exec(&mut db)
70 .await?;
71
72 let profiles: Vec<Profile> = User::filter(User::fields().name().eq("Bob"))
73 .select(User::fields().profile())
74 .exec(&mut db)
75 .await?;
76
77 assert_eq!(profiles.len(), 1);
78 assert_eq!(profiles[0].bio, "beta bio");
79
80 let profile: Option<Profile> = User::filter(User::fields().name().eq("Alice"))
81 .select(User::fields().profile())
82 .first()
83 .exec(&mut db)
84 .await?;
85
86 assert_eq!(profile.map(|p| p.bio).as_deref(), Some("apple a day"));
87
88 Ok(())
89}