diff options
author | cel 🌸 <cel@blos.sm> | 2023-12-12 18:20:56 +0000 |
---|---|---|
committer | cel 🌸 <cel@blos.sm> | 2023-12-12 18:20:56 +0000 |
commit | a587459a1817c0fc57b46df3f9c69567e1e775b7 (patch) | |
tree | ab99c6aaa7c2b3245c83db6332e4ca54006831b3 /src/db/users.rs | |
parent | 370a25e5a0cbb95e2aa1cec55305b22aeaf99aa0 (diff) | |
download | pinussy-a587459a1817c0fc57b46df3f9c69567e1e775b7.tar.gz pinussy-a587459a1817c0fc57b46df3f9c69567e1e775b7.tar.bz2 pinussy-a587459a1817c0fc57b46df3f9c69567e1e775b7.zip |
refactor: separate model and controller
Diffstat (limited to 'src/db/users.rs')
-rw-r--r-- | src/db/users.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/db/users.rs b/src/db/users.rs new file mode 100644 index 0000000..0fc7c64 --- /dev/null +++ b/src/db/users.rs @@ -0,0 +1,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?) + } +} |