use entity::alerts; use migration::{Migrator, MigratorTrait}; use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set}; use thiserror::Error; use tracing::debug; use crate::json::alert::Alert; #[derive(Error, Debug)] #[error("rdbms error")] pub enum RdbmsError { /// Database Error #[error("db error")] DbError(#[from] sea_orm::DbErr), } pub struct Db { connection: DatabaseConnection, } impl Db { pub async fn is_alert_updated(&self, alert: &Alert) -> Result { let db_alert = entity::alerts::Entity::find_by_id(&alert.identifier) .one(&self.connection) .await?; Ok(match db_alert { Some(db_alert) => db_alert.publish_date < alert.publish_date, None => true, }) } pub async fn save_alert(&self, alert: &Alert) -> Result<(), RdbmsError> { let db_alert = entity::alerts::Entity::find_by_id(&alert.identifier) .one(&self.connection) .await?; let alert = alerts::ActiveModel { id: Set(alert.identifier.to_owned()), publish_date: Set(alert.publish_date), }; match db_alert { Some(_) => alert.save(&self.connection).await?, None => alert.insert(&self.connection).await?.into(), }; Ok(()) } } pub async fn connect(connection_string: &str) -> Result { debug!("connecting to {connection_string}..."); let connection = migration::sea_orm::Database::connect(connection_string).await?; Migrator::up(&connection, None).await?; let connection = sea_orm::Database::connect(connection_string).await?; Ok(Db { connection }) }