Make use of pool.acquire to prevent out-of-order db-actions

This commit is contained in:
Tobias Reisinger 2023-11-21 03:42:33 +01:00
parent f3d08aab80
commit 271b24b70d
8 changed files with 248 additions and 131 deletions

View file

@ -1,11 +1,11 @@
use log::{info, trace}; use log::{info, trace};
use sqlx::migrate::Migrator; use sqlx::migrate::Migrator;
use sqlx::{Pool, Sqlite};
use sqlx::sqlite::SqlitePoolOptions; use sqlx::sqlite::SqlitePoolOptions;
use sqlx::{Pool, Sqlite};
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::model_utils::Period; use crate::db::model_utils::Period;
use crate::db::models::{Schedule, Periods}; use crate::db::models::{Periods, Schedule};
use crate::types::EmgauwaUid; use crate::types::EmgauwaUid;
pub mod errors; pub mod errors;
@ -19,20 +19,24 @@ static MIGRATOR: Migrator = sqlx::migrate!(); // defaults to "./migrations"
pub async fn run_migrations(pool: &Pool<Sqlite>) { pub async fn run_migrations(pool: &Pool<Sqlite>) {
info!("Running migrations"); info!("Running migrations");
MIGRATOR MIGRATOR.run(pool).await.expect("Failed to run migrations.");
.run(pool)
.await
.expect("Failed to run migrations.");
} }
async fn init_schedule(pool: &Pool<Sqlite>, uid: &EmgauwaUid, name: &str, periods: Periods) -> Result<(), DatabaseError> { async fn init_schedule(
pool: &Pool<Sqlite>,
uid: &EmgauwaUid,
name: &str,
periods: Periods,
) -> Result<(), DatabaseError> {
trace!("Initializing schedule {:?}", name); trace!("Initializing schedule {:?}", name);
match schedules::get_schedule_by_uid(pool, uid).await { match schedules::get_schedule_by_uid(&mut pool.acquire().await.unwrap(), uid).await {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => match err { Err(err) => match err {
DatabaseError::NotFound => { DatabaseError::NotFound => {
trace!("Schedule {:?} not found, inserting", name); trace!("Schedule {:?} not found, inserting", name);
sqlx::query_as!(Schedule, "INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *", sqlx::query_as!(
Schedule,
"INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
uid, uid,
name, name,
periods, periods,
@ -47,7 +51,6 @@ async fn init_schedule(pool: &Pool<Sqlite>, uid: &EmgauwaUid, name: &str, period
} }
} }
pub async fn init(db: &str) -> Pool<Sqlite> { pub async fn init(db: &str) -> Pool<Sqlite> {
let pool: Pool<Sqlite> = SqlitePoolOptions::new() let pool: Pool<Sqlite> = SqlitePoolOptions::new()
.acquire_timeout(std::time::Duration::from_secs(1)) .acquire_timeout(std::time::Duration::from_secs(1))
@ -58,12 +61,7 @@ pub async fn init(db: &str) -> Pool<Sqlite> {
run_migrations(&pool).await; run_migrations(&pool).await;
init_schedule( init_schedule(&pool, &EmgauwaUid::Off, "Off", Periods(vec![]))
&pool,
&EmgauwaUid::Off,
"Off",
Periods(vec![])
)
.await .await
.expect("Error initializing schedule Off"); .expect("Error initializing schedule Off");
@ -71,7 +69,7 @@ pub async fn init(db: &str) -> Pool<Sqlite> {
&pool, &pool,
&EmgauwaUid::On, &EmgauwaUid::On,
"On", "On",
Periods(vec![Period::new_on()]) Periods(vec![Period::new_on()]),
) )
.await .await
.expect("Error initializing schedule On"); .expect("Error initializing schedule On");

View file

@ -1,11 +1,11 @@
use crate::db::models::Periods; use crate::db::models::Periods;
use chrono::{NaiveTime, Timelike}; use chrono::{NaiveTime, Timelike};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{Decode, Encode, Sqlite, Type};
use sqlx::database::HasArguments; use sqlx::database::HasArguments;
use sqlx::encode::IsNull; use sqlx::encode::IsNull;
use sqlx::error::BoxDynError; use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef}; use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
use sqlx::{Decode, Encode, Sqlite, Type};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Period { pub struct Period {
@ -125,7 +125,8 @@ impl<'r> Decode<'r, Sqlite> for Periods {
impl From<&Periods> for Vec<u8> { impl From<&Periods> for Vec<u8> {
fn from(periods: &Periods) -> Vec<u8> { fn from(periods: &Periods) -> Vec<u8> {
periods.0 periods
.0
.iter() .iter()
.flat_map(|period| { .flat_map(|period| {
let vec = vec![ let vec = vec![

View file

@ -1,38 +1,58 @@
use std::borrow::Borrow; use std::borrow::Borrow;
use sqlx::{Pool, Sqlite}; use std::ops::DerefMut;
use crate::types::EmgauwaUid; use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::models::*; use crate::db::models::*;
use crate::db::tag::{create_junction_tag_schedule, create_tag}; use crate::db::tag::{create_junction_tag_schedule, create_tag};
use crate::types::EmgauwaUid;
pub async fn get_schedule_tags(pool: &Pool<Sqlite>, schedule: &Schedule) -> Result<Vec<String>, DatabaseError> { pub async fn get_schedule_tags(
conn: &mut PoolConnection<Sqlite>,
schedule: &Schedule,
) -> Result<Vec<String>, DatabaseError> {
Ok(sqlx::query_scalar!("SELECT tag FROM tags INNER JOIN junction_tag ON junction_tag.tag_id = tags.id WHERE junction_tag.schedule_id = ?", schedule.id) Ok(sqlx::query_scalar!("SELECT tag FROM tags INNER JOIN junction_tag ON junction_tag.tag_id = tags.id WHERE junction_tag.schedule_id = ?", schedule.id)
.fetch_all(pool) .fetch_all(conn.deref_mut())
.await?) .await?)
} }
pub async fn get_schedules(pool: &Pool<Sqlite>) -> Result<Vec<Schedule>, DatabaseError> { pub async fn get_schedules(
conn: &mut PoolConnection<Sqlite>,
) -> Result<Vec<Schedule>, DatabaseError> {
Ok(sqlx::query_as!(Schedule, "SELECT * FROM schedules") Ok(sqlx::query_as!(Schedule, "SELECT * FROM schedules")
.fetch_all(pool) .fetch_all(conn.deref_mut())
.await?) .await?)
} }
pub async fn get_schedule_by_uid(pool: &Pool<Sqlite>, filter_uid: &EmgauwaUid) -> Result<Schedule, DatabaseError> { pub async fn get_schedule_by_uid(
sqlx::query_as!(Schedule, "SELECT * FROM schedules WHERE uid = ?", filter_uid) conn: &mut PoolConnection<Sqlite>,
.fetch_optional(pool) filter_uid: &EmgauwaUid,
) -> Result<Schedule, DatabaseError> {
sqlx::query_as!(
Schedule,
"SELECT * FROM schedules WHERE uid = ?",
filter_uid
)
.fetch_optional(conn.deref_mut())
.await .await
.map(|s| s.ok_or(DatabaseError::NotFound))? .map(|s| s.ok_or(DatabaseError::NotFound))?
} }
pub async fn get_schedules_by_tag(pool: &Pool<Sqlite>, tag: &Tag) -> Result<Vec<Schedule>, DatabaseError> { pub async fn get_schedules_by_tag(
conn: &mut PoolConnection<Sqlite>,
tag: &Tag,
) -> Result<Vec<Schedule>, DatabaseError> {
Ok(sqlx::query_as!(Schedule, "SELECT schedule.* FROM schedules AS schedule INNER JOIN junction_tag ON junction_tag.schedule_id = schedule.id WHERE junction_tag.tag_id = ?", tag.id) Ok(sqlx::query_as!(Schedule, "SELECT schedule.* FROM schedules AS schedule INNER JOIN junction_tag ON junction_tag.schedule_id = schedule.id WHERE junction_tag.tag_id = ?", tag.id)
.fetch_all(pool) .fetch_all(conn.deref_mut())
.await?) .await?)
} }
pub async fn delete_schedule_by_uid(pool: &Pool<Sqlite>, filter_uid: EmgauwaUid) -> Result<(), DatabaseError> { pub async fn delete_schedule_by_uid(
conn: &mut PoolConnection<Sqlite>,
filter_uid: EmgauwaUid,
) -> Result<(), DatabaseError> {
let filter_uid = match filter_uid { let filter_uid = match filter_uid {
EmgauwaUid::Off => Err(DatabaseError::Protected), EmgauwaUid::Off => Err(DatabaseError::Protected),
EmgauwaUid::On => Err(DatabaseError::Protected), EmgauwaUid::On => Err(DatabaseError::Protected),
@ -40,7 +60,7 @@ pub async fn delete_schedule_by_uid(pool: &Pool<Sqlite>, filter_uid: EmgauwaUid)
}?; }?;
sqlx::query!("DELETE FROM schedules WHERE uid = ?", filter_uid) sqlx::query!("DELETE FROM schedules WHERE uid = ?", filter_uid)
.execute(pool) .execute(conn.deref_mut())
.await .await
.map(|res| match res.rows_affected() { .map(|res| match res.rows_affected() {
0 => Err(DatabaseError::DeleteError), 0 => Err(DatabaseError::DeleteError),
@ -48,20 +68,26 @@ pub async fn delete_schedule_by_uid(pool: &Pool<Sqlite>, filter_uid: EmgauwaUid)
})? })?
} }
pub async fn create_schedule(pool: &Pool<Sqlite>, new_name: &str, new_periods: &Periods) -> Result<Schedule, DatabaseError> { pub async fn create_schedule(
conn: &mut PoolConnection<Sqlite>,
new_name: &str,
new_periods: &Periods,
) -> Result<Schedule, DatabaseError> {
let uid = EmgauwaUid::default(); let uid = EmgauwaUid::default();
sqlx::query_as!(Schedule, "INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *", sqlx::query_as!(
Schedule,
"INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
uid, uid,
new_name, new_name,
new_periods, new_periods,
) )
.fetch_optional(pool) .fetch_optional(conn.deref_mut())
.await? .await?
.ok_or(DatabaseError::InsertGetError) .ok_or(DatabaseError::InsertGetError)
} }
pub async fn update_schedule( pub async fn update_schedule(
pool: &Pool<Sqlite>, conn: &mut PoolConnection<Sqlite>,
schedule: &Schedule, schedule: &Schedule,
new_name: &str, new_name: &str,
new_periods: &Periods, new_periods: &Periods,
@ -72,35 +98,41 @@ pub async fn update_schedule(
EmgauwaUid::Any(_) => new_periods, EmgauwaUid::Any(_) => new_periods,
}; };
sqlx::query!("UPDATE schedules SET name = ?, periods = ? WHERE id = ?", sqlx::query!(
"UPDATE schedules SET name = ?, periods = ? WHERE id = ?",
new_name, new_name,
new_periods, new_periods,
schedule.id, schedule.id,
) )
.execute(pool) .execute(conn.deref_mut())
.await?; .await?;
get_schedule_by_uid(pool, &schedule.uid).await get_schedule_by_uid(conn, &schedule.uid).await
} }
pub async fn set_schedule_tags(pool: &Pool<Sqlite>, schedule: &Schedule, new_tags: &[String]) -> Result<(), DatabaseError> { pub async fn set_schedule_tags(
sqlx::query!("DELETE FROM junction_tag WHERE schedule_id = ?", schedule.id) conn: &mut PoolConnection<Sqlite>,
.execute(pool) schedule: &Schedule,
new_tags: &[String],
) -> Result<(), DatabaseError> {
sqlx::query!(
"DELETE FROM junction_tag WHERE schedule_id = ?",
schedule.id
)
.execute(conn.deref_mut())
.await?; .await?;
for new_tag in new_tags { for new_tag in new_tags {
let tag: Option<Tag> = sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", new_tag) let tag: Option<Tag> = sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", new_tag)
.fetch_optional(pool) .fetch_optional(conn.deref_mut())
.await?; .await?;
let tag = match tag { let tag = match tag {
Some(id) => id, Some(id) => id,
None => { None => create_tag(conn, new_tag).await?,
create_tag(pool, new_tag).await?
}
}; };
create_junction_tag_schedule(pool, tag, schedule).await?; create_junction_tag_schedule(conn, tag, schedule).await?;
} }
Ok(()) Ok(())
} }

View file

@ -1,41 +1,62 @@
use sqlx::{Pool, Sqlite};
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::models::*; use crate::db::models::*;
use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use std::ops::DerefMut;
pub async fn create_tag(pool: &Pool<Sqlite>, new_tag: &str) -> Result<Tag, DatabaseError> { pub async fn create_tag(
sqlx::query_as!(Tag, "INSERT INTO tags (tag) VALUES (?) RETURNING *", new_tag) conn: &mut PoolConnection<Sqlite>,
.fetch_optional(pool) new_tag: &str,
) -> Result<Tag, DatabaseError> {
sqlx::query_as!(
Tag,
"INSERT INTO tags (tag) VALUES (?) RETURNING *",
new_tag
)
.fetch_optional(conn.deref_mut())
.await? .await?
.ok_or(DatabaseError::InsertGetError) .ok_or(DatabaseError::InsertGetError)
} }
pub async fn get_tag(pool: &Pool<Sqlite>, target_tag: &str) -> Result<Tag, DatabaseError> { pub async fn get_tag(
conn: &mut PoolConnection<Sqlite>,
target_tag: &str,
) -> Result<Tag, DatabaseError> {
sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", target_tag) sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", target_tag)
.fetch_optional(pool) .fetch_optional(conn.deref_mut())
.await .await
.map(|t| t.ok_or(DatabaseError::NotFound))? .map(|t| t.ok_or(DatabaseError::NotFound))?
} }
#[allow(dead_code)] #[allow(dead_code)]
pub async fn create_junction_tag_relay( pub async fn create_junction_tag_relay(
pool: &Pool<Sqlite>, conn: &mut PoolConnection<Sqlite>,
target_tag: Tag, target_tag: Tag,
target_relay: &Relay, target_relay: &Relay,
) -> Result<JunctionTag, DatabaseError> { ) -> Result<JunctionTag, DatabaseError> {
sqlx::query_as!(
sqlx::query_as!(JunctionTag, "INSERT INTO junction_tag (tag_id, relay_id) VALUES (?, ?) RETURNING *", target_tag.id, target_relay.id) JunctionTag,
.fetch_optional(pool) "INSERT INTO junction_tag (tag_id, relay_id) VALUES (?, ?) RETURNING *",
target_tag.id,
target_relay.id
)
.fetch_optional(conn.deref_mut())
.await? .await?
.ok_or(DatabaseError::InsertGetError) .ok_or(DatabaseError::InsertGetError)
} }
pub async fn create_junction_tag_schedule( pub async fn create_junction_tag_schedule(
pool: &Pool<Sqlite>, conn: &mut PoolConnection<Sqlite>,
target_tag: Tag, target_tag: Tag,
target_schedule: &Schedule, target_schedule: &Schedule,
) -> Result<JunctionTag, DatabaseError> { ) -> Result<JunctionTag, DatabaseError> {
sqlx::query_as!(JunctionTag, "INSERT INTO junction_tag (tag_id, schedule_id) VALUES (?, ?) RETURNING *", target_tag.id, target_schedule.id) sqlx::query_as!(
.fetch_optional(pool) JunctionTag,
"INSERT INTO junction_tag (tag_id, schedule_id) VALUES (?, ?) RETURNING *",
target_tag.id,
target_schedule.id
)
.fetch_optional(conn.deref_mut())
.await? .await?
.ok_or(DatabaseError::InsertGetError) .ok_or(DatabaseError::InsertGetError)
} }

View file

@ -1,10 +1,10 @@
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use actix_web::{delete, get, post, put, web, HttpResponse, Responder}; use actix_web::{delete, get, post, put, web, HttpResponse, Responder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};
use std::borrow::Borrow; use std::borrow::Borrow;
use std::convert::TryFrom; use std::convert::TryFrom;
use futures::future;
use sqlx::{Pool, Sqlite};
use crate::db::models::{Periods, Schedule}; use crate::db::models::{Periods, Schedule};
use crate::db::schedules::*; use crate::db::schedules::*;
@ -23,31 +23,14 @@ pub struct RequestSchedule {
#[get("/api/v1/schedules")] #[get("/api/v1/schedules")]
pub async fn index(pool: web::Data<Pool<Sqlite>>) -> impl Responder { pub async fn index(pool: web::Data<Pool<Sqlite>>) -> impl Responder {
let schedules = get_schedules(&pool).await; let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
if let Err(err) = schedules { return HttpResponse::from(DatabaseError::from(err));
return HttpResponse::from(err);
} }
let schedules = schedules.unwrap(); let mut pool_conn = pool_conn.unwrap();
let mut return_schedules: Vec<ReturnSchedule> = schedules.iter().map(ReturnSchedule::from).collect(); let schedules = get_schedules(&mut pool_conn).await;
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&pool);
}
HttpResponse::Ok().json(return_schedules)
}
#[get("/api/v1/schedules/tag/{tag}")]
pub async fn tagged(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let (tag,) = path.into_inner();
let tag_db = get_tag(&pool, &tag).await;
if let Err(err) = tag_db {
return HttpResponse::from(err);
}
let tag_db = tag_db.unwrap();
let schedules = get_schedules_by_tag(&pool, &tag_db).await;
if let Err(err) = schedules { if let Err(err) = schedules {
return HttpResponse::from(err); return HttpResponse::from(err);
} }
@ -56,25 +39,61 @@ pub async fn tagged(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -
let mut return_schedules: Vec<ReturnSchedule> = let mut return_schedules: Vec<ReturnSchedule> =
schedules.iter().map(ReturnSchedule::from).collect(); schedules.iter().map(ReturnSchedule::from).collect();
for schedule in return_schedules.iter_mut() { for schedule in return_schedules.iter_mut() {
schedule.load_tags(&pool); schedule.load_tags(&mut pool_conn);
}
HttpResponse::Ok().json(return_schedules)
}
#[get("/api/v1/schedules/tag/{tag}")]
pub async fn tagged(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
return HttpResponse::from(DatabaseError::from(err));
}
let mut pool_conn = pool_conn.unwrap();
let (tag,) = path.into_inner();
let tag_db = get_tag(&mut pool_conn, &tag).await;
if let Err(err) = tag_db {
return HttpResponse::from(err);
}
let tag_db = tag_db.unwrap();
let schedules = get_schedules_by_tag(&mut pool_conn, &tag_db).await;
if let Err(err) = schedules {
return HttpResponse::from(err);
}
let schedules = schedules.unwrap();
let mut return_schedules: Vec<ReturnSchedule> =
schedules.iter().map(ReturnSchedule::from).collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&mut pool_conn);
} }
HttpResponse::Ok().json(return_schedules) HttpResponse::Ok().json(return_schedules)
} }
#[get("/api/v1/schedules/{schedule_id}")] #[get("/api/v1/schedules/{schedule_id}")]
pub async fn show(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder { pub async fn show(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
return HttpResponse::from(DatabaseError::from(err));
}
let mut pool_conn = pool_conn.unwrap();
let (schedule_uid,) = path.into_inner(); let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid)); let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
match emgauwa_uid { match emgauwa_uid {
Ok(uid) => { Ok(uid) => {
let schedule = get_schedule_by_uid(&pool, &uid).await; let schedule = get_schedule_by_uid(&mut pool_conn, &uid).await;
match schedule { match schedule {
Ok(ok) => { Ok(ok) => {
let mut return_schedule = ReturnSchedule::from(ok); let mut return_schedule = ReturnSchedule::from(ok);
return_schedule.load_tags(&pool); return_schedule.load_tags(&mut pool_conn);
HttpResponse::Ok().json(return_schedule) HttpResponse::Ok().json(return_schedule)
}, }
Err(err) => HttpResponse::from(err), Err(err) => HttpResponse::from(err),
} }
} }
@ -83,40 +102,63 @@ pub async fn show(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) ->
} }
#[post("/api/v1/schedules")] #[post("/api/v1/schedules")]
pub async fn add(pool: web::Data<Pool<Sqlite>>, data: web::Json<RequestSchedule>) -> impl Responder { pub async fn add(
let new_schedule = create_schedule(&pool, &data.name, &data.periods).await; pool: web::Data<Pool<Sqlite>>,
data: web::Json<RequestSchedule>,
) -> impl Responder {
let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
return HttpResponse::from(DatabaseError::from(err));
}
let mut pool_conn = pool_conn.unwrap();
let new_schedule = create_schedule(&mut pool_conn, &data.name, &data.periods).await;
if let Err(err) = new_schedule { if let Err(err) = new_schedule {
return HttpResponse::from(err); return HttpResponse::from(err);
} }
let new_schedule = new_schedule.unwrap(); let new_schedule = new_schedule.unwrap();
let result = set_schedule_tags(&pool, &new_schedule, data.tags.as_slice()).await; let result = set_schedule_tags(&mut pool_conn, &new_schedule, data.tags.as_slice()).await;
if let Err(err) = result { if let Err(err) = result {
return HttpResponse::from(err); return HttpResponse::from(err);
} }
let mut return_schedule = ReturnSchedule::from(new_schedule); let mut return_schedule = ReturnSchedule::from(new_schedule);
return_schedule.load_tags(&pool); return_schedule.load_tags(&mut pool_conn);
HttpResponse::Created().json(return_schedule) HttpResponse::Created().json(return_schedule)
} }
async fn add_list_single(pool: &Pool<Sqlite>, request_schedule: &RequestSchedule) -> Result<Schedule, DatabaseError> { async fn add_list_single(
let new_schedule = create_schedule(pool, &request_schedule.name, &request_schedule.periods).await?; conn: &mut PoolConnection<Sqlite>,
request_schedule: &RequestSchedule,
) -> Result<Schedule, DatabaseError> {
let new_schedule =
create_schedule(conn, &request_schedule.name, &request_schedule.periods).await?;
set_schedule_tags(pool, &new_schedule, request_schedule.tags.as_slice()).await?; set_schedule_tags(conn, &new_schedule, request_schedule.tags.as_slice()).await?;
Ok(new_schedule) Ok(new_schedule)
} }
#[post("/api/v1/schedules/list")] #[post("/api/v1/schedules/list")]
pub async fn add_list(pool: web::Data<Pool<Sqlite>>, data: web::Json<Vec<RequestSchedule>>) -> impl Responder { pub async fn add_list(
let result: Vec<Result<Schedule, DatabaseError>> = future::join_all( pool: web::Data<Pool<Sqlite>>,
data data: web::Json<Vec<RequestSchedule>>,
) -> impl Responder {
let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
return HttpResponse::from(DatabaseError::from(err));
}
let mut pool_conn = pool_conn.unwrap();
let result: Vec<Result<Schedule, DatabaseError>> = data
.as_slice() .as_slice()
.iter() .iter()
.map(|request_schedule| add_list_single(&pool, request_schedule)) .map(|request_schedule| {
).await; futures::executor::block_on(add_list_single(&mut pool_conn, request_schedule))
})
.collect();
match vec_has_error(&result) { match vec_has_error(&result) {
true => HttpResponse::from( true => HttpResponse::from(
@ -133,7 +175,7 @@ pub async fn add_list(pool: web::Data<Pool<Sqlite>>, data: web::Json<Vec<Request
.collect(); .collect();
for schedule in return_schedules.iter_mut() { for schedule in return_schedules.iter_mut() {
schedule.load_tags(&pool); schedule.load_tags(&mut pool_conn);
} }
HttpResponse::Created().json(return_schedules) HttpResponse::Created().json(return_schedules)
} }
@ -146,6 +188,12 @@ pub async fn update(
path: web::Path<(String,)>, path: web::Path<(String,)>,
data: web::Json<RequestSchedule>, data: web::Json<RequestSchedule>,
) -> impl Responder { ) -> impl Responder {
let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
return HttpResponse::from(DatabaseError::from(err));
}
let mut pool_conn = pool_conn.unwrap();
let (schedule_uid,) = path.into_inner(); let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid)); let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
if let Err(err) = emgauwa_uid { if let Err(err) = emgauwa_uid {
@ -153,30 +201,42 @@ pub async fn update(
} }
let emgauwa_uid = emgauwa_uid.unwrap(); let emgauwa_uid = emgauwa_uid.unwrap();
let schedule = get_schedule_by_uid(&pool, &emgauwa_uid, ).await; let schedule = get_schedule_by_uid(&mut pool_conn, &emgauwa_uid).await;
if let Err(err) = schedule { if let Err(err) = schedule {
return HttpResponse::from(err); return HttpResponse::from(err);
} }
let schedule = schedule.unwrap(); let schedule = schedule.unwrap();
let schedule = update_schedule(&pool, &schedule, data.name.as_str(), data.periods.borrow()).await; let schedule = update_schedule(
&mut pool_conn,
&schedule,
data.name.as_str(),
data.periods.borrow(),
)
.await;
if let Err(err) = schedule { if let Err(err) = schedule {
return HttpResponse::from(err); return HttpResponse::from(err);
} }
let schedule = schedule.unwrap(); let schedule = schedule.unwrap();
let result = set_schedule_tags(&pool, &schedule, data.tags.as_slice()).await; let result = set_schedule_tags(&mut pool_conn, &schedule, data.tags.as_slice()).await;
if let Err(err) = result { if let Err(err) = result {
return HttpResponse::from(err); return HttpResponse::from(err);
} }
let mut return_schedule = ReturnSchedule::from(schedule); let mut return_schedule = ReturnSchedule::from(schedule);
return_schedule.load_tags(&pool); return_schedule.load_tags(&mut pool_conn);
HttpResponse::Ok().json(return_schedule) HttpResponse::Ok().json(return_schedule)
} }
#[delete("/api/v1/schedules/{schedule_id}")] #[delete("/api/v1/schedules/{schedule_id}")]
pub async fn delete(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder { pub async fn delete(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let pool_conn = pool.acquire().await;
if let Err(err) = pool_conn {
return HttpResponse::from(DatabaseError::from(err));
}
let mut pool_conn = pool_conn.unwrap();
let (schedule_uid,) = path.into_inner(); let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid)); let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
@ -184,7 +244,7 @@ pub async fn delete(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -
Ok(uid) => match uid { Ok(uid) => match uid {
EmgauwaUid::Off => HttpResponse::from(HandlerError::ProtectedSchedule), EmgauwaUid::Off => HttpResponse::from(HandlerError::ProtectedSchedule),
EmgauwaUid::On => HttpResponse::from(HandlerError::ProtectedSchedule), EmgauwaUid::On => HttpResponse::from(HandlerError::ProtectedSchedule),
EmgauwaUid::Any(_) => match delete_schedule_by_uid(&pool, uid).await { EmgauwaUid::Any(_) => match delete_schedule_by_uid(&mut pool_conn, uid).await {
Ok(_) => HttpResponse::Ok().json("schedule got deleted"), Ok(_) => HttpResponse::Ok().json("schedule got deleted"),
Err(err) => HttpResponse::from(err), Err(err) => HttpResponse::from(err),
}, },

View file

@ -1,5 +1,7 @@
use futures::executor; use futures::executor;
use serde::Serialize; use serde::Serialize;
use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use crate::db::models::Schedule; use crate::db::models::Schedule;
use crate::db::schedules::get_schedule_tags; use crate::db::schedules::get_schedule_tags;
@ -12,14 +14,17 @@ pub struct ReturnSchedule {
} }
impl ReturnSchedule { impl ReturnSchedule {
pub fn load_tags(&mut self, pool: &sqlx::Pool<sqlx::Sqlite>) { pub fn load_tags(&mut self, conn: &mut PoolConnection<Sqlite>) {
self.tags = executor::block_on(get_schedule_tags(pool, &self.schedule)).unwrap(); self.tags = executor::block_on(get_schedule_tags(conn, &self.schedule)).unwrap();
} }
} }
impl From<Schedule> for ReturnSchedule { impl From<Schedule> for ReturnSchedule {
fn from(schedule: Schedule) -> Self { fn from(schedule: Schedule) -> Self {
ReturnSchedule { schedule, tags: vec![]} ReturnSchedule {
schedule,
tags: vec![],
}
} }
} }

View file

@ -4,11 +4,11 @@ use std::str::FromStr;
use crate::types::EmgauwaUid; use crate::types::EmgauwaUid;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use sqlx::{Decode, Encode, Sqlite, Type};
use sqlx::database::HasArguments; use sqlx::database::HasArguments;
use sqlx::encode::IsNull; use sqlx::encode::IsNull;
use sqlx::error::BoxDynError; use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef}; use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
use sqlx::{Decode, Encode, Sqlite, Type};
use uuid::Uuid; use uuid::Uuid;
impl EmgauwaUid { impl EmgauwaUid {