Transactions

Transactions guarantee that either all operations within the transaction are executed successfully, or none are executed at all. They are essential for maintaining data consistency during more complex operations.

The simplest way to use transactions looks like this:

$database->beginTransaction();
try {
	$database->query('DELETE FROM articles WHERE id = ?', $id);
	$database->query('INSERT INTO audit_log', [
		'article_id' => $id,
		'action' => 'delete'
	]);
	$database->commit();
} catch (\Exception $e) {
	$database->rollBack();
	throw $e;
}

A much cleaner and more elegant way to achieve the same result is by using the transaction() method. This method accepts a callback as a parameter, which it executes within the transaction. If the callback runs without throwing an exception, the transaction is automatically committed. If an exception is thrown, the transaction is rolled back, and the exception is propagated further.

$database->transaction(function ($database) use ($id) {
	$database->query('DELETE FROM articles WHERE id = ?', $id);
	$database->query('INSERT INTO audit_log', [
		'article_id' => $id,
		'action' => 'delete'
	]);
});

The transaction() method can also return values:

$count = $database->transaction(function ($database) {
	$result = $database->query('UPDATE users SET active = ?', true);
	return $result->getRowCount(); // returns the number of rows updated
});
version: 4.0 3.x