• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Force database transaction rollback

#1
Hi all,

I am adding this here to see if I am missing something, and if not if it could be added to the todo list to make codeigniter better ;o)

I am using transaction inside a try catch and in the catch I want to force a rollback of the database even if all the queries were successfully. In my case this is because I only want to commit the database if an email is successfully sent but I'm sure there are many other cases where this would be useful.

Obviously I know I can use the manual transaction stuff like _being _rollback etc but this wont give the extra functionality eg nested transactions that trans_start and trans_complete give.

My simple solution at the mo is to add a parameter to the trans_complete function in DB_driver.php that you can pass a boolean of TRUE to if you want to force a rollback. Then by changing the line:

PHP Code:
if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE

to

PHP Code:
if ($force_rollback OR $this->_trans_status === FALSE OR $this->_trans_failure === TRUE

it gives me the desired effect.

So am I missing something? or would this be a usefully little update...

Many thanks
Ben
Reply

#2
Wouldn't it be simpler to add a trans_force_rollback() or trans_fail() method to your DB driver which simply sets $this->_trans_status to false?

This would also lend itself to better exception handling under PHP 5.5+ by using a finally block to run trans_complete() with the trans_force_rollback() call in the catch block.

Personally, though, I tend to shy away from making a database transaction dependent on outside forces. A database transaction is intended to ensure a series of database actions are completed as a group (usually in part to ensure some integrity of the data), so the failure of one database action forces the rollback of previous actions in the transaction. Whether an email was sent is something I would normally indicate with a value in the database so I could simply attempt to re-send the email at another time (and/or not allow some other action to occur until the email is sent), as there are too many unrelated factors which can cause the email to fail.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.