rowt/src/model/rower.rs

94 lines
2.3 KiB
Rust
Raw Normal View History

2023-07-24 13:01:39 +02:00
use serde::{Deserialize, Serialize};
2023-07-25 13:22:11 +02:00
use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
2023-07-24 13:01:39 +02:00
2023-07-31 16:33:44 +02:00
use super::{logbook::Logbook, user::User};
2023-07-24 13:01:39 +02:00
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Rower {
pub logbook_id: i64,
pub rower_id: i64,
}
impl Rower {
pub async fn for_log(db: &SqlitePool, log: &Logbook) -> Vec<User> {
2023-07-31 16:33:44 +02:00
sqlx::query_as!(
User,
2023-07-24 13:01:39 +02:00
"
2023-11-02 12:15:10 +01:00
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
2023-07-31 16:25:07 +02:00
FROM user
WHERE id in (SELECT rower_id FROM rower WHERE logbook_id=?)
",
2023-07-24 13:01:39 +02:00
log.id
)
.fetch_all(db)
.await
.unwrap()
}
pub async fn create(
db: &mut Transaction<'_, Sqlite>,
logbook_id: i64,
rower_id: i64,
) -> Result<(), String> {
//TODO: Check if rower is allowed to row
sqlx::query!(
2023-10-23 09:36:38 +02:00
"INSERT INTO rower(logbook_id, rower_id) VALUES (?,?);",
2023-07-24 13:01:39 +02:00
logbook_id,
rower_id
)
.execute(db)
.await
2023-09-06 14:39:36 +02:00
.map_err(|e| e.to_string())?;
Ok(())
}
}
#[cfg(test)]
mod test {
use sqlx::SqlitePool;
use super::Logbook;
use crate::model::{rower::Rower, user::User};
use crate::testdb;
#[sqlx::test]
fn test_for_log() {
let pool = testdb!();
let logbook = Logbook::find_by_id(&pool, 3).await.unwrap();
let rowers = Rower::for_log(&pool, &logbook).await;
let expected = User::find_by_id(&pool, 3).await.unwrap();
assert_eq!(rowers, vec![expected]);
}
#[sqlx::test]
fn test_for_log_none() {
let pool = testdb!();
let logbook = Logbook::find_by_id(&pool, 2).await.unwrap();
let rowers = Rower::for_log(&pool, &logbook).await;
assert_eq!(rowers, vec![]);
}
#[sqlx::test]
fn test_create() {
let pool = testdb!();
let logbook = Logbook::find_by_id(&pool, 3).await.unwrap();
let mut tx = pool.begin().await.unwrap();
Rower::create(&mut tx, logbook.id, 2).await.unwrap();
tx.commit().await.unwrap();
let rowers = Rower::for_log(&pool, &logbook).await;
assert_eq!(
rowers,
vec![
User::find_by_id(&pool, 2).await.unwrap(),
User::find_by_id(&pool, 3).await.unwrap()
]
);
2023-07-24 13:01:39 +02:00
}
}