82 lines
2.2 KiB
Rust
82 lines
2.2 KiB
Rust
use sqlx::{query, PgPool};
|
|
|
|
use super::Area;
|
|
|
|
pub struct Location {
|
|
pub id: i32,
|
|
pub name: String,
|
|
pub area_id: i32,
|
|
pub area: Option<Area>,
|
|
}
|
|
|
|
impl Location {
|
|
pub async fn create(pool: &PgPool, name: &str, area_id: i32) -> anyhow::Result<i32> {
|
|
let result = query!(
|
|
"INSERT INTO location (name, areaId) VALUES ($1, $2) RETURNING id;",
|
|
name,
|
|
area_id
|
|
)
|
|
.fetch_one(pool)
|
|
.await?;
|
|
|
|
Ok(result.id)
|
|
}
|
|
|
|
pub async fn read_by_area(pool: &PgPool, area_id: i32) -> anyhow::Result<Vec<Location>> {
|
|
let records = query!("SELECT * FROM location WHERE areaId = $1;", area_id)
|
|
.fetch_all(pool)
|
|
.await?;
|
|
|
|
let locations = records
|
|
.iter()
|
|
.map(|lr| Location {
|
|
id: lr.id,
|
|
name: lr.name.to_string(),
|
|
area_id: lr.areaid,
|
|
area: None,
|
|
})
|
|
.collect();
|
|
|
|
Ok(locations)
|
|
}
|
|
|
|
pub async fn read_all(pool: &PgPool) -> anyhow::Result<Vec<Location>> {
|
|
let records = query!("SELECT * FROM location")
|
|
.fetch_all(pool)
|
|
.await?;
|
|
|
|
let locations = records
|
|
.iter()
|
|
.map(|lr| Location {
|
|
id: lr.id,
|
|
name: lr.name.to_string(),
|
|
area_id: lr.areaid,
|
|
area: None,
|
|
})
|
|
.collect();
|
|
|
|
Ok(locations)
|
|
}
|
|
|
|
pub async fn read_all_including_area(pool: &PgPool) -> anyhow::Result<Vec<Location>> {
|
|
let records = query!("SELECT location.id AS locationId, location.name, location.areaId, area.id, area.name AS areaName FROM location JOIN area ON location.areaId = area.id;")
|
|
.fetch_all(pool)
|
|
.await?;
|
|
|
|
let locations = records
|
|
.iter()
|
|
.map(|lr| Location {
|
|
id: lr.locationid,
|
|
name: lr.name.to_string(),
|
|
area_id: lr.areaid,
|
|
area: Some(Area {
|
|
id: lr.id,
|
|
name: lr.areaname.to_string(),
|
|
}),
|
|
})
|
|
.collect();
|
|
|
|
Ok(locations)
|
|
}
|
|
}
|