ddstats/src/database/models/race.rs

91 lines
2.4 KiB
Rust

use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use crate::database::DatabaseHandler;
use super::search_result::{SearchResult, ROWS_PER_PAGE};
#[derive(Debug, Clone, sqlx::FromRow, Serialize, Deserialize)]
pub struct Race {
pub name: String,
pub map: String,
pub time: f32,
pub timestamp: NaiveDateTime,
pub server: String,
pub checkpoints: Option<Vec<f64>>,
pub gameid: Option<String>,
pub ddnet7: bool,
}
impl Race {
/// This gets all the races from the database by a given player.
/// It is paginated into a SearchResult<Race>!
/// FIXME: Returns empty array for non-existent player.
pub async fn get_races_by_player(
db: &DatabaseHandler,
player: &str,
page: i32,
) -> Result<SearchResult<Race>, sqlx::Error> {
let results = sqlx::query_file_as!(
Race,
"sql/races/get_races_by_player.sql",
player,
page,
ROWS_PER_PAGE
)
.fetch_all(&db.pool)
.await?;
let total_pages = sqlx::query!(
"SELECT ceil(count(*) / $2) + 1 as total_pages FROM record_race WHERE name = $1",
player,
ROWS_PER_PAGE as i64
)
.fetch_one(&db.pool)
.await?
.total_pages
.map_or_else(|| 0, |as_i64| as_i64 as i32);
Ok(SearchResult {
results,
total_pages,
current_page: page,
})
}
/// This gets all the races from the database on a specific map.
/// It is paginated into a SearchResult<Race>!
/// FIXME: Returns empty array for non-existent map.
pub async fn get_races_by_map(
db: &DatabaseHandler,
map: &str,
page: i32,
) -> Result<SearchResult<Race>, sqlx::Error> {
let results = sqlx::query_file_as!(
Race,
"sql/races/get_races_by_map.sql",
map,
page,
ROWS_PER_PAGE
)
.fetch_all(&db.pool)
.await?;
let total_pages = sqlx::query!(
"SELECT ceil(count(*) / $2) + 1 as total_pages FROM record_race WHERE map = $1",
map,
ROWS_PER_PAGE as i64
)
.fetch_one(&db.pool)
.await?
.total_pages
.map_or_else(|| 0, |as_i64| as_i64 as i32);
Ok(SearchResult {
results,
total_pages,
current_page: page,
})
}
}