Transactions

The Drupal database API also provides a way to represent and handle database transactions (for the database types which support them). Transactions are ways in which database operations can be wrapped and grouped together in view of committing them, all or none. For example, if you have multiple records that are related, it's possible you will want only some of them written if one fails its INSERT operation for some reason. This could leave you with a corrupt or incomplete data that could throw your application into a spin.

Performing multiple database-changing operations after a transaction has been opened only finalizes (commits) those changes to the database when that transaction closes. If something goes wrong, it can also be rolled back, which will prevent the data from being committed.

In Drupal 8, a transaction is represented by a Transaction object (a specific subclass for each database type). As soon as the object is destroyed (is no longer in scope), the operations get committed to the database. However, if we get an indication that something went wrong in our operations (usually via catching an exception), we can roll back the transaction, which will stop those operations from being committed. Moreover, transactions can be nested, so Drupal keeps track of transactions that have been opened within the scope of other transactions.

Let's see an example of how to use transactions:

$transaction = $database->startTransaction();
try {
$database->update('players')
->fields(['data' => serialize(['sport' => 'tennis', 'feature' => 'This guy can play tennis'])])
->condition('name', 'Novak D.')
->execute();
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('my_type', $e);
}

The first thing we did was start a transaction using our connection service. Then, we wrapped our operation in a try/catch block to catch any exceptions that might be thrown in performing them. If one does get thrown, we roll back the transaction, because we don’t want to commit anything to the database, as we don't know what failed and what shape our data is in. Finally, we used the watchdog_exception() helper to log the exception to the database log. Do note that logging this before the rollback would prevent the exception from being written to the database as well.

If there is no exception, the operation gets committed as soon as the $transaction variable gets removed and is no longer in scope (usually at the end of the function). It is also interesting to note that if within this transaction we call another function in which we perform database operations, those operations will be part of this same transaction by default. So, they also get rolled back, if we roll back or get committed if we don't. This is why the database watchdog log will not be saved if called before the rollback.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset