use anyhow::Result; use persmgr_derive::TableMeta; use sqlx::prelude::FromRow; use crate::db::{ CurrPool, tables::{ForeignKey, TableMeta, assignables::awards::Award, user::User}, }; #[derive(Debug, Default, Clone, FromRow, TableMeta)] #[meta(table = "records_awards")] pub struct AwardRecord { pub id: i64, pub user_id: ForeignKey, pub award_id: ForeignKey, pub author_id: ForeignKey, pub created_at: i64, } impl AwardRecord { pub async fn insert_new(&self, pool: &CurrPool) -> Result { let session = sqlx::query_as!( AwardRecord, r#" INSERT INTO records_awards (user_id, award_id, author_id, created_at) VALUES ($1, $2, $3, $4) RETURNING * "#, *self.user_id, *self.award_id, *self.author_id, self.created_at, ) .fetch_one(pool) .await?; let user = self.author_id.extract(pool).await?; Ok(session) } pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result { let session = sqlx::query_as!( AwardRecord, "SELECT * FROM records_awards WHERE id = $1", id ) .fetch_one(pool) .await?; Ok(session) } pub async fn get_by_user_id(pool: &CurrPool, id: i64) -> anyhow::Result> { let session = sqlx::query_as!( AwardRecord, "SELECT * FROM records_awards WHERE user_id = $1", id ) .fetch_all(pool) .await?; Ok(session) } pub async fn get_by_author_id(pool: &CurrPool, id: i64) -> anyhow::Result> { let session = sqlx::query_as!( AwardRecord, "SELECT * FROM records_awards WHERE author_id = $1", id ) .fetch_all(pool) .await?; Ok(session) } pub async fn get_by_award_id(pool: &CurrPool, id: i64) -> anyhow::Result> { let session = sqlx::query_as!( AwardRecord, "SELECT * FROM records_awards WHERE award_id = $1", id ) .fetch_all(pool) .await?; Ok(session) } }