use anyhow::Result; use persmgr_derive::TableMeta; use sqlx::prelude::FromRow; use crate::db::{ CurrPool, tables::{ForeignKey, TableMeta, assignables::trainings::Training, user::User}, }; #[derive(Debug, Default, Clone, FromRow, TableMeta)] #[meta(table = "records_trainings")] pub struct TrainingRecord { pub id: i64, pub user_id: ForeignKey, pub training_id: ForeignKey, pub author_id: ForeignKey, pub created_at: i64, } impl TrainingRecord { pub async fn insert_new(&self, pool: &CurrPool) -> Result { let session = sqlx::query_as!( TrainingRecord, r#" INSERT INTO records_trainings (user_id, training_id, author_id, created_at) VALUES ($1, $2, $3, $4) RETURNING * "#, *self.user_id, *self.training_id, *self.author_id, self.created_at, ) .fetch_one(pool) .await?; Ok(session) } pub async fn get_by_id(pool: &CurrPool, id: i64) -> anyhow::Result { let session = sqlx::query_as!( TrainingRecord, "SELECT * FROM records_trainings 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!( TrainingRecord, "SELECT * FROM records_trainings 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!( TrainingRecord, "SELECT * FROM records_trainings WHERE author_id = $1", id ) .fetch_all(pool) .await?; Ok(session) } pub async fn get_by_training_id(pool: &CurrPool, id: i64) -> anyhow::Result> { let session = sqlx::query_as!( TrainingRecord, "SELECT * FROM records_trainings WHERE training_id = $1", id ) .fetch_all(pool) .await?; Ok(session) } }