Improve database errors (NotFound -> Option)

This commit is contained in:
Tobias Reisinger 2023-11-27 13:33:04 +01:00
parent be7f31906c
commit 8dab4b9a50
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
9 changed files with 96 additions and 78 deletions
emgauwa-lib/src/db

View file

@ -34,25 +34,22 @@ async fn init_schedule(
periods: DbPeriods,
) -> Result<(), DatabaseError> {
trace!("Initializing schedule {:?}", name);
match DbSchedule::get_by_uid(&mut pool.acquire().await.unwrap(), uid).await {
Ok(_) => Ok(()),
Err(err) => match err {
DatabaseError::NotFound => {
trace!("Schedule {:?} not found, inserting", name);
sqlx::query_as!(
DbSchedule,
"INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
uid,
name,
periods,
)
.fetch_optional(pool)
.await?
.ok_or(DatabaseError::InsertGetError)
.map(|_| ())
}
_ => Err(err),
},
match DbSchedule::get_by_uid(&mut pool.acquire().await.unwrap(), uid).await? {
Some(_) => Ok(()),
None => {
trace!("Schedule {:?} not found, inserting", name);
sqlx::query_as!(
DbSchedule,
"INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
uid,
name,
periods,
)
.fetch_optional(pool)
.await?
.ok_or(DatabaseError::InsertGetError)
.map(|_| ())
}
}
}