summaryrefslogtreecommitdiffstats
path: root/src/db/users.rs
blob: 0fc7c64642182fa001482cf101f129fd8352c597 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use sqlx::{Pool, Postgres};

use crate::users::User;
use crate::Result;

#[derive(Clone)]
pub struct Users(Pool<Postgres>);
// code code code code code code code code code code code code code code
impl Users {
    pub fn new(pool: Pool<Postgres>) -> Self {
        Self(pool)
    }

    pub async fn create(&self, user: User) -> Result<()> {
        sqlx::query!(
            r#"insert into users (username, password, email, bio, site, privacy, admin) values ($1, $2, $3, $4, $5, $6, $7)"#,
            user.username,
            user.password,
            user.email,
            user.bio,
            user.site,
            user.privacy as _,
            user.admin
        )
        .execute(&self.0)
        .await?;
        Ok(())
    }

    pub async fn read(&self, user_id: i32) -> Result<User> {
        Ok(
            sqlx::query_as!(
                User,
                "select username, password, email, bio, site, privacy as \"privacy: _\", admin from users where id = $1",
                user_id
            )
            .fetch_one(&self.0)
            .await?
        )
    }

    pub async fn read_username(&self, username: &str) -> Result<User> {
        Ok(
            sqlx::query_as!(
                User,
                "select username, password, email, bio, site, privacy as \"privacy: _\", admin from users where username = $1",
                username
            )
            .fetch_one(&self.0)
            .await?
        )
    }

    pub async fn get_id(&self, username: &str) -> Result<i32> {
        Ok(
            sqlx::query!("select id from users where username = $1", username)
                .fetch_one(&self.0)
                .await?
                .id,
        )
    }

    pub async fn read_all(&self) -> Result<Vec<User>> {
        Ok(sqlx::query_as("select * from users")
            .fetch_all(&self.0)
            .await?)
    }
}