From ff6dcf6dfe84df8b502b8ef2f8ac2dde7116ab9a Mon Sep 17 00:00:00 2001 From: StNicolay Date: Wed, 19 Jul 2023 14:56:07 +0300 Subject: [PATCH] Added a transaction for deleting all --- entity/src/account.rs | 2 +- entity/src/master_pass.rs | 2 +- src/commands/delete_all.rs | 27 +++++++++++++++++++-------- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/entity/src/account.rs b/entity/src/account.rs index d702986..f8e1ab2 100644 --- a/entity/src/account.rs +++ b/entity/src/account.rs @@ -79,7 +79,7 @@ impl Entity { /// Deletes all the user's accounts from DB #[inline] - pub async fn delete_all(user_id: u64, db: &DatabaseConnection) -> crate::Result<()> { + pub async fn delete_all(user_id: u64, db: &impl ConnectionTrait) -> crate::Result<()> { Self::delete_many() .filter(Column::UserId.eq(user_id)) .exec(db) diff --git a/entity/src/master_pass.rs b/entity/src/master_pass.rs index af20b61..0ac1e61 100644 --- a/entity/src/master_pass.rs +++ b/entity/src/master_pass.rs @@ -33,7 +33,7 @@ impl Entity { } /// Removes a master password of the user from the database - pub async fn remove(user_id: u64, db: &DatabaseConnection) -> Result<(), DbErr> { + pub async fn remove(user_id: u64, db: &impl ConnectionTrait) -> Result<(), DbErr> { Self::delete_by_id(user_id).exec(db).await?; Ok(()) } diff --git a/src/commands/delete_all.rs b/src/commands/delete_all.rs index bf4c5e0..59a90e7 100644 --- a/src/commands/delete_all.rs +++ b/src/commands/delete_all.rs @@ -1,5 +1,7 @@ use crate::prelude::*; -use tokio::join; +use log::error; +use sea_orm::TransactionTrait; +use tokio::try_join; /// Gets the master password, deletes the accounts and the master password from DB. /// Although it doesn't use the master password, we get it to be sure that it's the user who used that command @@ -12,14 +14,23 @@ async fn get_master_pass( ) -> crate::Result<()> { dialogue.exit().await?; let user_id = msg.from().ok_or(NoUserInfo)?.id.0; - match join!( - Account::delete_all(user_id, &db), - MasterPass::remove(user_id, &db), - ) { - (Ok(_), Ok(_)) => (), - (Err(err), _) | (Ok(_), Err(err)) => return Err(err.into()), + let txn = db.begin().await?; + let result = try_join!( + Account::delete_all(user_id, &txn), + MasterPass::remove(user_id, &txn), + ); + let text = match result { + Ok(_) => { + txn.commit().await?; + "Everything was deleted" + } + Err(err) => { + error!("{}", crate::Error::from(err)); + txn.rollback().await?; + "Something went wrong. Try again later" + } }; - bot.send_message(msg.chat.id, "Everything was deleted") + bot.send_message(msg.chat.id, text) .reply_markup(deletion_markup()) .await?; Ok(())