55 lines
1.6 KiB
Rust
55 lines
1.6 KiB
Rust
use crate::types::CalendarDate;
|
|
use sqlx::{query_as, PgPool};
|
|
use std::error::Error;
|
|
|
|
pub async fn add_calendar_dates(
|
|
postgres_pool: &PgPool,
|
|
calendar_dates: &Vec<CalendarDate>,
|
|
) -> Result<Vec<CalendarDate>, Box<dyn Error + Send + Sync>> {
|
|
let mut dates = Vec::with_capacity(calendar_dates.len());
|
|
let mut opens = Vec::with_capacity(calendar_dates.len());
|
|
let mut closes = Vec::with_capacity(calendar_dates.len());
|
|
|
|
for calendar_date in calendar_dates {
|
|
dates.push(calendar_date.date);
|
|
opens.push(calendar_date.open);
|
|
closes.push(calendar_date.close);
|
|
}
|
|
|
|
query_as!(
|
|
CalendarDate,
|
|
r#"INSERT INTO calendar (date, open, close)
|
|
SELECT * FROM UNNEST($1::date[], $2::time[], $3::time[])
|
|
RETURNING date, open, close"#,
|
|
&dates,
|
|
&opens,
|
|
&closes
|
|
)
|
|
.fetch_all(postgres_pool)
|
|
.await
|
|
.map_err(|e| e.into())
|
|
}
|
|
|
|
pub async fn delete_all_calendar_dates(
|
|
postgres_pool: &PgPool,
|
|
) -> Result<Vec<CalendarDate>, Box<dyn Error + Send + Sync>> {
|
|
query_as!(
|
|
CalendarDate,
|
|
"DELETE FROM calendar RETURNING date, open, close"
|
|
)
|
|
.fetch_all(postgres_pool)
|
|
.await
|
|
.map_err(|e| e.into())
|
|
}
|
|
|
|
pub async fn reset_calendar_dates(
|
|
postgres_pool: &PgPool,
|
|
calendar_dates: &Vec<CalendarDate>,
|
|
) -> Result<Vec<CalendarDate>, Box<dyn Error + Send + Sync>> {
|
|
let transaction = postgres_pool.begin().await?;
|
|
delete_all_calendar_dates(postgres_pool).await?;
|
|
let calendar_dates = add_calendar_dates(postgres_pool, calendar_dates).await;
|
|
transaction.commit().await?;
|
|
calendar_dates
|
|
}
|