use sqlx::{query, PgPool}; use super::Area; pub struct Location { pub id: i32, pub name: String, pub area_id: i32, pub area: Option, } impl Location { pub async fn create(pool: &PgPool, name: &str, area_id: i32) -> anyhow::Result { 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> { 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> { 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> { 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) } }