96 lines
2.9 KiB
Rust
96 lines
2.9 KiB
Rust
use tokio_postgres::Client as PgClient;
|
|
use std::sync::Arc;
|
|
use crate::models::car_station::{BindingCarStation, CarStation};
|
|
use crate::storages::traits::CarStationRepository;
|
|
use async_trait::async_trait;
|
|
|
|
pub struct PostgresCarStationRepository {
|
|
pub connection: Arc<PgClient>
|
|
}
|
|
|
|
#[async_trait]
|
|
impl CarStationRepository for PostgresCarStationRepository {
|
|
async fn create(&self, car_station: BindingCarStation) -> Result<CarStation, String> {
|
|
let result = self.connection.query(
|
|
"INSERT INTO Car_Station(address) \
|
|
VALUES ($1) RETURNING *",
|
|
&[&car_station.address]
|
|
).await;
|
|
if let Ok(rows) = result {
|
|
let row = rows.get(0).unwrap();
|
|
Ok(CarStation {
|
|
id: row.get("id"),
|
|
address: row.get("address")
|
|
})
|
|
} else {
|
|
Err(result.unwrap_err().to_string())
|
|
}
|
|
}
|
|
|
|
async fn read(&self, id: i32) -> Result<CarStation, String> {
|
|
let result = self.connection.query(
|
|
"SELECT * FROM Car_Station WHERE id = $1", &[&id]
|
|
).await;
|
|
|
|
if let Ok(rows) = result {
|
|
let row = rows.get(0).ok_or("CarStation not found".to_owned())?;
|
|
Ok(CarStation {
|
|
id: row.get("id"),
|
|
address: row.get("address")
|
|
})
|
|
} else {
|
|
Err(result.unwrap_err().to_string())
|
|
}
|
|
}
|
|
|
|
async fn read_all(&self) -> Result<Vec<CarStation>, String> {
|
|
let result = self.connection.query(
|
|
"SELECT * FROM Car_Station", &[]
|
|
).await;
|
|
|
|
if let Ok(rows) = result {
|
|
Ok(
|
|
rows.into_iter().map(|r| CarStation {
|
|
id: r.get("id"),
|
|
address: r.get("address")
|
|
}).collect()
|
|
)
|
|
} else {
|
|
Err(result.unwrap_err().to_string())
|
|
}
|
|
}
|
|
|
|
async fn update(&self, id: i32, car_station: BindingCarStation) -> Result<CarStation, String> {
|
|
let result = self.connection.query(
|
|
"UPDATE Car_Station SET address = $1 WHERE id = $2 RETURNING *",
|
|
&[&car_station.address, &id]
|
|
).await;
|
|
|
|
if let Ok(rows) = result {
|
|
let row = rows.get(0).unwrap();
|
|
Ok(CarStation {
|
|
id: row.get("id"),
|
|
address: row.get("address")
|
|
})
|
|
} else {
|
|
Err(result.unwrap_err().to_string())
|
|
}
|
|
}
|
|
|
|
async fn delete(&self, id: i32) -> Result<(), String> {
|
|
let result = self.connection.execute(
|
|
"DELETE FROM Car_Station WHERE id = $1",
|
|
&[&id]
|
|
).await;
|
|
|
|
if let Ok(rows) = result {
|
|
if rows == 0 {
|
|
Err("CarStation not found".to_owned())
|
|
} else {
|
|
Ok(())
|
|
}
|
|
} else {
|
|
Err(result.unwrap_err().to_string())
|
|
}
|
|
}
|
|
} |