Added a transaction for deleting all

This commit is contained in:
StNicolay 2023-07-19 14:56:07 +03:00
parent 255a794b0f
commit ff6dcf6dfe
Signed by: StNicolay
GPG Key ID: 9693D04DCD962B0D
3 changed files with 21 additions and 10 deletions

View File

@ -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)

View File

@ -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(())
}

View File

@ -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(())