Add stock market calendar
Signed-off-by: Nikolaos Karaolidis <nick@karaolidis.com>
This commit is contained in:
54
backend/src/database/calendar.rs
Normal file
54
backend/src/database/calendar.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
Reference in New Issue
Block a user