use quokka::{
helper::database::{
execute, query_all, query_one, query_optional, BaseRepository, PaginationOrder,
},
state::{Database, FromState},
};
#[derive(Clone, sqlx::FromRow, serde::Deserialize, serde::Serialize)]
pub struct User {
pub id: i32,
pub username: String,
pub password: String,
pub email: String,
pub created_at: time::OffsetDateTime,
pub updated_at: time::OffsetDateTime,
}
#[derive(Clone, FromState)]
pub struct UserRepository {
database: Database,
}
impl UserRepository {
#[query_optional(query = "SELECT * FROM \"user\" WHERE username = {username}")]
pub async fn get_user_by_name(&self, username: &str) -> quokka::Result<Option<User>>;
}
impl BaseRepository for UserRepository {
type Entity = User;
type PkType = i32;
#[query_all(
query = "SELECT * FROM \"user\" ORDER BY {#order_by} {#direction.to_string()} LIMIT {#page_size} OFFSET {#page_size * page}"
)]
async fn get_entities(
&self,
page: i32,
page_size: i32,
order_by: &'static str,
direction: PaginationOrder,
) -> quokka::Result<Vec<Self::Entity>>;
#[query_one(query = "SELECT * FROM \"user\" WHERE id = {pk}")]
fn get_entity(&self, pk: Self::PkType) -> quokka::Result<Self::Entity>;
#[execute(
query = "UPDATE \"user\" SET username = {entity.username}, email = {entity.email}, password = {entity.password}, updated_at = NOW() WHERE id = {entity.id}",
write
)]
fn update_entity(&self, entity: Self::Entity) -> quokka::Result<u64>;
#[query_one(
query = "INSERT INTO \"user\" (username, email, password) VALUES ({entity.username}, {entity.email}, {entity.password}) RETURNING *",
write
)]
fn create_entity(&self, entity: Self::Entity) -> quokka::Result<Self::Entity>;
#[execute(query = "DELETE FROM \"user\" WHERE id = {pk}", write)]
fn delete_entity(&self, pk: Self::PkType) -> quokka::Result<u64>;
}