Skip to content

Commit c7f47c3

Browse files
committed
Add a function for loading a user from the DB
1 parent d62132e commit c7f47c3

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

src/db/users.rs

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
use crate::github::User;
12
use anyhow::Context;
23
use tokio_postgres::Client as DbClient;
34

4-
/// Add a new user (if not existing)
5+
/// Add a new user.
6+
/// If an user already exists, updates their username.
57
pub async fn record_username(db: &DbClient, user_id: u64, username: &str) -> anyhow::Result<()> {
68
db.execute(
79
r"
@@ -15,9 +17,30 @@ DO UPDATE SET username = $2",
1517
Ok(())
1618
}
1719

20+
/// Return a user from the DB.
21+
pub async fn get_user(db: &DbClient, user_id: u64) -> anyhow::Result<Option<User>> {
22+
let row = db
23+
.query_opt(
24+
r"
25+
SELECT username
26+
FROM users
27+
WHERE user_id = $1;",
28+
&[&(user_id as i64)],
29+
)
30+
.await
31+
.context("cannot load user from DB")?;
32+
Ok(row.map(|row| {
33+
let username: &str = row.get(0);
34+
User {
35+
id: user_id,
36+
login: username.to_string(),
37+
}
38+
}))
39+
}
40+
1841
#[cfg(test)]
1942
mod tests {
20-
use crate::db::users::record_username;
43+
use crate::db::users::{get_user, record_username};
2144
use crate::tests::run_test;
2245

2346
#[tokio::test]
@@ -28,12 +51,7 @@ mod tests {
2851
record_username(&db, 1, "Foo").await?;
2952
record_username(&db, 1, "Bar").await?;
3053

31-
let row = db
32-
.query_one("SELECT username FROM users WHERE user_id = 1", &[])
33-
.await
34-
.unwrap();
35-
let name: &str = row.get(0);
36-
assert_eq!(name, "Bar");
54+
assert_eq!(get_user(&db, 1).await?.unwrap().login, "Bar");
3755

3856
Ok(ctx)
3957
})

0 commit comments

Comments
 (0)