Atomic transactions and logging - php

Let's say I have a function that modifies a database. This could be anywhere from one query to multiple queries in a transaction. In any of these modifications we want to make sure all queries are successful. Thankfully for transactions, if one of these fails I have a way of making sure none of the changes are made permanent.
Now let's say I also have a log that needs to be written to to make note of the change (s). How could I make sure that both the modifications are made and the log written?
I could always do a try/catch on either but say for instance my queries are successful but my log is unsuccessful. How could I then go back and undo all of the modifications to the database?
Would something like this be effective and/or advisable?
try {
$db->connect();
$db->mysqli->begin_transaction();
// series of queries
...
// log to file
$db->mysqli->commit();
} catch (exception $e) {
$db->mysqli->rollback();
$db->mysqli->close();
}
Wanted to make note of some behaviors I observed while testing this. If you place the commit() before the log, the database changes will not roll back even if an exception is caught while logging.

The data will be stored in the database once you call commit() or trigger an implicit commit. For example, this will not make any changes to the database because there is no commit:
$mysqli->begin_transaction();
$mysqli->query('INSERT INTO test1(val) VALUES(2)');
// end of script's execution
In your little example, the transaction will be rolled back as long as your logging functionality stops the execution or throws an exception.
$db->connect();
try {
$db->mysqli->begin_transaction();
// series of queries
...
// log to file
throw new \Exception(); // <-- This will prevent commit from executing.
$db->mysqli->commit();
} catch (\Exception $e) {
// An exception? That's ok, we'll try something different instead.
$db->mysqli->rollback();
}
You need to call rollback only if you want to recover from the exception and clear the unsaved buffer. The only time you should ever catch exceptions is if you want to somehow recover from it and do a different thing. Otherwise, your code could be simplified by removing try-catch and rollback altogether.
However, it is a good idea to catch exceptions in transactions and roll it back explicitly as soon as possible, even when you do not want to recover. It can prevent an issue if you catch the exception somewhere else in your code and you try to execute other DB actions. The unsaved data is still in the buffer until you close the session or roll back! This is why you would often see code like this:
$db->connect();
try {
$db->mysqli->begin_transaction();
throw new \Exception(); // <-- Something throws an exception
$db->mysqli->commit();
} catch (\Exception $e) {
// rollback unsaved data, but rethrow the exception as we do not know how to recover from it here
$db->mysqli->rollback();
throw $e;
}

Related

What is the difference between DB::beginTransaction() and DB::transaction()?

I'm using Laravel 5.2.
I would like to know what are the differences between :
DB::beginTransaction() and DB::transaction()
DB::commitTransction() and DB::commit()
DB::rollbackTransction() and DB::rollback()
Any helps would be appreciated.
DB::beginTransaction() will only begin a transaction, while for DB::transaction() you must pass a Closure function that will be executed inside a transaction.
So this:
DB::transaction(function() {
// Do something and save to the db...
});
is the same as this:
// Open a try/catch block
try {
// Begin a transaction
DB::beginTransaction();
// Do something and save to the db...
// Commit the transaction
DB::commit();
} catch (\Exception $e) {
// An error occured; cancel the transaction...
DB::rollback();
// and throw the error again.
throw $e;
}
As you can see, DB::transaction() is a "helper" function to avoid writing code to catch errors, begin a transaction, commit the transaction, and optionally rollback (cancel the transaction) if an error occured.
If you have a more complex logic, or need an specific behaviour, you will manually build your transaction; if your logic is rather simple, DB::transaction() is the way to go.
As for DB::commitTransaction() and DB::rollbackTransaction(), I can't find information.
It's a good practice to check the source code of the things you use, because you will learn how they are written, as well as how to write. Here's the file with the source for these methods.
From Laravel 6 to use Transactions must be use the following helper functions.
use Illuminate\Support\Facades\DB;
try {
// For Begin a transaction
DB::beginTransaction();
// Do something
// Commit the transaction
DB:: commit();
} catch (\Throwable $e) {
// An error occured
DB::rollback();
// and throw the error again.
throw $e;
}
if you use the DB::commitTransaction(); function, get error undefined function.

Calling SQL rollback on php exception

Consider the following scenario:
I open a new connection to MySQL, using mysqli extension
I start a transaction
I do some queries on the MySQL database and to some php computation
Either MySQL or php may throw some exceptions
I commit the transaction
(pseudo) code:
$sql = new mysqli();
...
{ //some scope
$sql->query("START TRANSACTION");
...
if (something)
throw Exception("Something went wrong");
...
$sql->query("COMMIT"); // or $sql->commit()
} //leave scope either normally or through exception
...
$sql->query( ... ); // other stuff not in transaction
If all the above is in some big try catch block (or perhaps even the exception is uncaught) the transaction will remain unfinished. If I then try to do some more work on the database, those actions will belong to the transaction.
My question is: is there some possible mechanism that would permit me to automatically send $sql->rollback() when I leave the transaction-creating scope in an abnormal way?
Some notes:
mysqli::autocommit is not the same as a transaction. It is just a setting for autocommit you turn on or off. Equivalent to MySQL SET autocommit.
mysqli::begin_transaction is not documented and I don't know what is its precise behavior. Will it call rollback when the mysqli object dies for example?
The Command mysqli::begin_transaction is the same (object oriented way) as your $sql->query("START TRANSACTION");;
There is no way, to auto rollback on exception.
You can only comit, if everything has success. Then it will be a "auto rollback" if not. But this way, you will have trouble very soon, if you have more then one commit.
So your current code is allready very good. I would do it the full OOP way:
$sql->begin_transaction();
try {
$sql->query('DO SOMETHING');
if(!true) {
throw new \Exception("Something went wrong");
}
$sql->commit();
}
catch (\Exception exception) {
$sql->rollback();
}
You also can write your own Exception:
class SqlAutoRollbackException extends \Exception {
function __construct($msg, Sql $sql) {
$sql->rollback();
parent::__construct($msg);
}
}
But you still need to catch it.
You cannot automatically rollback on exception, but with a little code you can do what you want. Even if you already are in a try-catch block you can nest them for your transaction section, such as this:
try {
$sql->query("START TRANSACTION");
...
if (something)
throw new PossiblyCustomException("Something went wrong");
...
$sql->query("COMMIT");
} catch (Exception $e) { //catch all exceptions
$sql->query("ROLLBACK");
throw $e; //rethrow the very same exception object
}
Even if you use the most generic catch Exception, the actual type of the exception is known. When you rethrow, it can still be caught by PossiblyCustomException later. Thus, all the handling you already have remains unaffected by this new try-catch block.
So you want to either commit the transaction or rollback the transaction if there was a problem, and there are many ways that a problem could occur - either through a mysql error or php throwing an exception. So why not set up a flag at the start of the transaction, set that flag when the transaction ready to be committed, and check the state of the flag when the process is done to see if a rollback is needed?
If you are afraid of globally scoped variables you could use an overly complicated Singleton class or some kind of static variable for this, but here is the basic idea:
function main() {
global $commit_flag = false;
start_transaction();
doEverything();
if ($commit_flag) {
commit_transaction();
} else {
rollback_transaction();
}
}
function doEverything() {
global $commit_flag;
try {
/* do some stuff that may cause errors */
$commit_flag = true;
} catch { ... }
}
You can handle mysql exceptions using DECLARE ... HANDLER Syntax, but I don't find it proper to try to handle them through PHP !
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
START TRANSACTION;
INSERT INTO Users ( user_id ) VALUES('1');
INSERT INTO Users ( user_id ) VALUES('2');
COMMIT;
END;
More information can be found here :
http://dev.mysql.com/doc/refman/5.5/en/declare-handler.html

Pdo Error Catching Try/Catch

After looking into using try catch blocks for my Pdo statements is it really a benefit? Does this just slow your code down?
I believe that there should be a try catch around the connection command in case the database connection fails. But does there really need to be try catch around each pre prepared statement? These should never change and never really error out.
Any thoughts?
I'm using Php and MySql.
There is no benefit to this:
try {
// exec statement
// exec statement
}
catch (Exception $e) {
// do nothing
}
If you aren't going to do anything with the error and provide a reasonable solution, then you may as well let the exception bubble up to the application's main "something went wrong" error page.
But you may want to do this:
// begin transaction
try {
// exec statement
// exec statement
// commit transaction
}
catch (Exception $e) {
// rollback transaction
// handle error or rethrow $e;
}
And prepared statements can throw exceptions. Perhaps a unique key is violated, or a foreign key constraint is, etc.
But the main point is, you don't use exceptions to hide or silence errors. You use them to catch an error, process it intelligently, and continue on accordingly.

In MySQL is it best practice to wrap LOCK TABLES calls in a try catch?

When executing a "LOCK TABLES" is it wise to wrap the call in a try/catch to make sure the table gets unlocked in case of an exception?
In general it's a good idea to use try { } catch for operations that require undoing a previous operation in case of any errors; it's not limited to just database statements.
That said, when using databases, it's advisable to use a more granular locking mechanism such as the one that comes with transactional databases such as InnoDB. You would still use try { } catch, but in this manner:
// start a new transaction
$db->beginTransaction();
try {
// do stuff
// make the changes permament
$db->commit();
} catch (Exception $e) {
// roll back any changes you've made
$db->rollback();
throw $e;
}
The exact behaviour of conflict resolution is defined by the transaction isolation level, which can be changed to suit your needs.

PHP and MySQL ACID Program design

a while ago I completely recoded my application so that MySQL would perform in an ACID way.
At the very top level of all functions I do something like this:
try{
$db->begin();
dosomething($_SESSION['userid']);
$db->commit();
}catch(advException $e){
$eCode = $e->getCode();
$eMessage = $e->getMessage();
# Success
if ($eCode == 0){
$db->commit();
}else{
$db->rollback();
}
}
Within the function 'dosomething' I have the Exceptions thrown to users like:
throw new Exception('There was a problem.',1);
or
throw new Exception('You have successfully done that!', 0);
So that I can control the flow of the program. If theres a problem then roll back everything that happened and if everything was good then commit it. It's all worked quite great but there's just one flaw that I've come across so far.
I added Exception logging so I can see when there are issues that users face. But the problem is, if the table that logs the errors is InnoDB then it's also included in the transaction and will rollback if theres a problem so no errors are stored.
To get around this I basically just made the Error logging table MyISAM so when a rollback is done, the changes are still there.
Now I'm thinking of other bits I'd like to keep out of the transaction, like sending a mail within my application to the admin to help alert of problems.
Is there any sort of way for me to not include a database insert within the parent transaction? Have I taken a bad route in terms of Application/DB design and is there any other way I could have handled this?
Thanks, Dominic
It is not good idea to throw an Exception on success.
You have to do DB insert after previous rollback was called.
catch (Exception $e) {
$db->rollback();
Log::insert('Error: ' . $e->getMessage());
}
Try to use Logger to control your program. It is more flexible way.
Use return codes for successful operation, and Exceptions to specify exceptional situations (such as severe errors, etc.). As for your specific issue, I'd recommend having a separate database for logging if you choose to use the rollback strategy.

Categories