use crate::config::SharedConfig;
use open_timeline_core::{Name, OpenTimelineId};
use open_timeline_crud::{Create, CrudError, DeleteById, FetchByName, Update};
use open_timeline_gui_core::CreateOrEdit;
use std::fmt::Debug;
use tokio::sync::mpsc::Sender;
#[derive(Debug, Clone)]
pub enum CrudOperationRequested {
CreateOrUpdate,
Delete,
}
pub trait ToOpenTimelineType<T> {
fn to_opentimeline_type(&self) -> T;
}
pub async fn save_crud<T>(
shared_config: SharedConfig,
edit_or_create: &CreateOrEdit,
mut value: T,
tx: Sender<Result<T, CrudError>>,
) where
T: Create + Update,
{
let result = async {
let mut transaction = shared_config.read().await.db_pool.begin().await?;
match edit_or_create {
CreateOrEdit::Create => value.create(&mut transaction).await?,
CreateOrEdit::Edit => value.update(&mut transaction).await?,
};
transaction.commit().await.map_err(|_| CrudError::DbError)?;
Ok(value)
}
.await;
let _ = tx.send(result).await;
}
pub async fn _fetch_crud<T>(
shared_config: SharedConfig,
name: Name,
tx: Sender<Result<(), CrudError>>,
) where
T: FetchByName,
{
let result = async {
let mut transaction = shared_config.read().await.db_pool.begin().await?;
T::fetch_by_name(&mut transaction, &name).await?;
Ok(())
}
.await;
let _ = tx.send(result).await;
}
pub async fn delete_from_id_crud<T>(
shared_config: SharedConfig,
id: OpenTimelineId,
tx: Sender<Result<(), CrudError>>,
) where
T: DeleteById,
{
let result = async {
let mut transaction = shared_config.read().await.db_pool.begin().await?;
T::delete_by_id(&mut transaction, &id).await?;
transaction.commit().await.map_err(|_| CrudError::DbError)?;
Ok(())
}
.await;
let _ = tx.send(result).await;
}