add weather infos
This commit is contained in:
56
src/model/weather.rs
Normal file
56
src/model/weather.rs
Normal file
@ -0,0 +1,56 @@
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use rocket::serde::{Deserialize, Serialize};
|
||||
use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
|
||||
|
||||
#[derive(FromRow, Debug, Serialize, Deserialize, PartialEq, Clone)]
|
||||
pub struct Weather {
|
||||
pub id: i64,
|
||||
pub day: NaiveDate,
|
||||
pub max_temp: f64,
|
||||
pub wind_gust: f64,
|
||||
pub rain_mm: f64,
|
||||
}
|
||||
|
||||
impl Weather {
|
||||
pub async fn find_by_day(db: &SqlitePool, day: NaiveDate) -> Option<Self> {
|
||||
sqlx::query_as!(Self, "SELECT * FROM weather WHERE day = ?", day)
|
||||
.fetch_one(db)
|
||||
.await
|
||||
.ok()
|
||||
}
|
||||
pub async fn find_by_id_tx(db: &mut Transaction<'_, Sqlite>, day: NaiveDate) -> Option<Self> {
|
||||
sqlx::query_as!(Self, "SELECT * FROM weather WHERE day = ?", day)
|
||||
.fetch_one(db.deref_mut())
|
||||
.await
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
db: &mut Transaction<'_, Sqlite>,
|
||||
day: NaiveDate,
|
||||
max_temp: f64,
|
||||
wind_gust: f64,
|
||||
rain_mm: f64,
|
||||
) -> Result<(), String> {
|
||||
sqlx::query!(
|
||||
"INSERT INTO weather(day, max_temp, wind_gust, rain_mm) VALUES (?,?,?,?)",
|
||||
day,
|
||||
max_temp,
|
||||
wind_gust,
|
||||
rain_mm
|
||||
)
|
||||
.execute(db.deref_mut())
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete_all(db: &mut Transaction<'_, Sqlite>) {
|
||||
sqlx::query!("DELETE FROM weather;")
|
||||
.execute(db.deref_mut())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user