Skip to content

Commit b9f53b4

Browse files
committed
'get_any' getter example
1 parent fb18363 commit b9f53b4

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

example-postgres/src/main.rs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// #![feature(trace_macros)]
22
use chrono::{NaiveDateTime, Utc};
33
use ormx::{Insert, Table};
4-
use sqlx::PgPool;
4+
use sqlx::{PgConnection, PgPool};
55

66
// trace_macros!(true);
77

@@ -18,6 +18,7 @@ async fn main() -> anyhow::Result<()> {
1818
.init()?;
1919

2020
let db = PgPool::connect(&dotenv::var("DATABASE_URL")?).await?;
21+
let mut conn = db.acquire().await?;
2122

2223
log::info!("insert a new row into the database");
2324
let mut new = InsertUser {
@@ -28,7 +29,7 @@ async fn main() -> anyhow::Result<()> {
2829
disabled: None,
2930
role: Role::User,
3031
}
31-
.insert(&mut *db.acquire().await?)
32+
.insert(&mut conn)
3233
.await?;
3334

3435
log::info!("update a single field");
@@ -60,15 +61,41 @@ async fn main() -> anyhow::Result<()> {
6061
log::info!("delete the user from the database");
6162
new.delete(&db).await?;
6263

64+
log::info!("inserting 3 dummy users with ids: 1, 2 & 3");
65+
insert_dummy_user(&mut conn, 2).await?;
66+
insert_dummy_user(&mut conn, 3).await?;
67+
insert_dummy_user(&mut conn, 4).await?;
68+
69+
log::info!("getting many users by any user id (using 'get_any' getter)");
70+
let users = User::get_many_by_user_ids(&mut conn, &[2, 4]).await?;
71+
dbg!(&users);
72+
assert_eq!(users.len(), 2);
73+
74+
log::info!("empty user table");
75+
sqlx::query!("DELETE FROM users").execute(&db).await?;
6376
Ok(())
6477
}
6578

79+
async fn insert_dummy_user(conn: &mut PgConnection, id: i32) -> Result<User, sqlx::Error> {
80+
InsertUser {
81+
user_id: id,
82+
first_name: "Dummy".to_owned(),
83+
last_name: "Dummy".to_owned(),
84+
email: format!("dummy{}@mail.com", id),
85+
disabled: None,
86+
role: Role::User,
87+
}
88+
.insert(conn)
89+
.await
90+
}
91+
6692
#[derive(Debug, ormx::Table)]
6793
#[ormx(table = "users", id = user_id, insertable)]
6894
struct User {
6995
// map this field to the column "id"
7096
#[ormx(column = "id")]
7197
#[ormx(get_one = get_by_user_id)]
98+
#[ormx(get_any = get_many_by_user_ids)]
7299
user_id: i32,
73100
first_name: String,
74101
last_name: String,

0 commit comments

Comments
 (0)