Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a series of non database methods mimic transactions.

I have several method calls I need to perform that need to be "transactional" but I am unsure how to implement this aside from try/catch/finally.

Background

  • Application is console based.
  • Application will have multiple threads
  • A database is queried for connection information, connection is made to a webservice to login, a session ID is generated and a database is updated.
  • An operation invokes a logout, which needs to clean up the database, clear the session ID and log out of the webservice

What I'm trying to figure out

I want to make sure that when a logout is requested I want to ensure that the entire process is either all successful, or not at all. For instance I don't want the database to be cleaned up, the session ID cleaned and the logout operation fail (hence the login is still valid).

Ideally the solution would "rollback" on a failure, thereby ensuring the previous state is maintained.

Is there is a slick way to accomplish this, or am I stuck with a series of nested try/catch/finally blocks to do this?

like image 732
Robert H Avatar asked Nov 02 '22 22:11

Robert H


1 Answers

If you want to implement some rollback method, you must store undo data for all the things you'll need to rollback in case of a failure.

  • for the DB you already have a rollback method.
  • for each file you are modifying/deleting in the operation that may need to be rolled-back, you have to keep a backup copy, to allow you to revert to the previous state.
  • any in-memory variables that may have to be rolled-back should have backup copies.

This will allow you at any point in your code to rollback to a previous state when an error occurs.

like image 184
Eran Avatar answered Nov 09 '22 11:11

Eran