80 lines
2.2 KiB
Rust
80 lines
2.2 KiB
Rust
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<User>,
|
|
pub training_id: ForeignKey<Training>,
|
|
pub author_id: ForeignKey<User>,
|
|
pub created_at: i64,
|
|
}
|
|
|
|
impl TrainingRecord {
|
|
pub async fn insert_new(&self, pool: &CurrPool) -> Result<Self> {
|
|
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<Self> {
|
|
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<Vec<Self>> {
|
|
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<Vec<Self>> {
|
|
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<Vec<Self>> {
|
|
let session = sqlx::query_as!(
|
|
TrainingRecord,
|
|
"SELECT * FROM records_trainings WHERE training_id = $1",
|
|
id
|
|
)
|
|
.fetch_all(pool)
|
|
.await?;
|
|
Ok(session)
|
|
}
|
|
}
|