Files
packager/rust/src/models/user.rs

82 lines
1.7 KiB
Rust
Raw Normal View History

2023-08-29 21:34:00 +02:00
use super::Error;
use uuid::Uuid;
2023-08-29 21:34:01 +02:00
use crate::sqlite;
2023-08-29 21:34:00 +02:00
#[derive(Debug, Clone)]
pub struct User {
pub id: Uuid,
pub username: String,
pub fullname: String,
}
2023-08-29 21:34:01 +02:00
#[derive(Debug)]
2023-08-29 21:34:00 +02:00
pub struct NewUser<'a> {
pub username: &'a str,
pub fullname: &'a str,
}
2023-08-29 21:34:00 +02:00
#[derive(Debug)]
pub struct DbUserRow {
id: String,
username: String,
fullname: String,
}
impl TryFrom<DbUserRow> for User {
type Error = Error;
fn try_from(row: DbUserRow) -> Result<Self, Self::Error> {
Ok(User {
id: Uuid::try_parse(&row.id)?,
username: row.username,
fullname: row.fullname,
})
}
}
impl User {
#[tracing::instrument]
2023-08-29 21:34:00 +02:00
pub async fn find_by_name(
pool: &sqlx::Pool<sqlx::Sqlite>,
name: &str,
) -> Result<Option<Self>, Error> {
2023-08-29 21:34:01 +02:00
crate::query_one!(
sqlite::QueryClassification {
query_type: sqlite::QueryType::Select,
component: sqlite::Component::User,
},
pool,
2023-08-29 21:34:00 +02:00
DbUserRow,
2023-08-29 21:34:01 +02:00
Self,
2023-08-29 21:34:00 +02:00
"SELECT id,username,fullname FROM users WHERE username = ?",
name
)
2023-08-29 21:34:01 +02:00
.await
2023-08-29 21:34:00 +02:00
}
}
2023-08-29 21:34:00 +02:00
#[tracing::instrument]
2023-08-29 21:34:01 +02:00
pub async fn create(pool: &sqlite::Pool, user: NewUser<'_>) -> Result<Uuid, Error> {
2023-08-29 21:34:00 +02:00
let id = Uuid::new_v4();
let id_param = id.to_string();
2023-08-29 21:34:01 +02:00
crate::execute!(
sqlite::QueryClassification {
query_type: sqlite::QueryType::Insert,
component: sqlite::Component::User,
},
pool,
2023-08-29 21:34:00 +02:00
"INSERT INTO users
(id, username, fullname)
VALUES
(?, ?, ?)",
id_param,
user.username,
user.fullname
)
.await?;
Ok(id)
}