101 lines
2.7 KiB
Rust
101 lines
2.7 KiB
Rust
use crate::database::DatabaseHandler;
|
|
use serde::{Deserialize, Serialize};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct Location {
|
|
pub id: Uuid,
|
|
pub map: String,
|
|
pub has_entities: bool,
|
|
}
|
|
|
|
impl Location {
|
|
/// Get a random location. Use the `has_entities` option to specify whether the location should be returned with entities. No entities = harder.
|
|
pub async fn get_random(
|
|
db: &DatabaseHandler,
|
|
has_entities: bool,
|
|
) -> Result<Location, sqlx::Error> {
|
|
sqlx::query_as!(
|
|
Location,
|
|
"SELECT id, map, has_entities FROM locations WHERE has_entities = $1 ORDER BY RANDOM() LIMIT 1",
|
|
has_entities
|
|
)
|
|
.fetch_one(&db.pool)
|
|
.await
|
|
}
|
|
|
|
pub async fn get_by_id(db: &DatabaseHandler, id: &Uuid) -> Result<Location, sqlx::Error> {
|
|
sqlx::query_as!(
|
|
Location,
|
|
"SELECT id, map, has_entities FROM locations WHERE id = $1",
|
|
id
|
|
)
|
|
.fetch_one(&db.pool)
|
|
.await
|
|
}
|
|
|
|
pub async fn get_all_map_names(db: &DatabaseHandler) -> Result<Vec<String>, sqlx::Error> {
|
|
struct LocationOnlyName {
|
|
map: String,
|
|
}
|
|
|
|
let locations: Vec<LocationOnlyName> = sqlx::query_as!(
|
|
LocationOnlyName,
|
|
"SELECT DISTINCT(map) AS map FROM locations"
|
|
)
|
|
.fetch_all(&db.pool)
|
|
.await?;
|
|
|
|
let names = locations.iter().map(|map| map.map.to_owned()).collect();
|
|
|
|
Ok(names)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
async fn get_db() -> DatabaseHandler {
|
|
match DatabaseHandler::create().await {
|
|
Ok(db) => db,
|
|
Err(err) => panic!("Error while connecting to database! {:?}", err),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_get_random_location() {
|
|
async fn test() {
|
|
let db = get_db().await;
|
|
|
|
let location = match Location::get_random(&db, false).await {
|
|
Ok(location) => location,
|
|
Err(err) => panic!("Error while getting random location! {:?}", err),
|
|
};
|
|
|
|
println!("Location: {:?}", location);
|
|
}
|
|
|
|
tokio_test::block_on(test());
|
|
}
|
|
|
|
#[test]
|
|
fn test_get_all_map_names() {
|
|
async fn test() {
|
|
let db = get_db().await;
|
|
|
|
let map_names = match Location::get_all_map_names(&db).await {
|
|
Ok(names) => names,
|
|
Err(err) => panic!("Error while getting random location! {:?}", err),
|
|
};
|
|
|
|
println!("Found maps:");
|
|
map_names
|
|
.iter()
|
|
.for_each(|map_name| println!("{}", map_name));
|
|
}
|
|
|
|
tokio_test::block_on(test());
|
|
}
|
|
}
|