Using scope guards to manage transactions
D doesn't require you to make wrapper types or write try/catch statements all the time. You can also use scope guards. They can be triggered by three conditions: exit
, success
, or failure
. Here, we'll perform a multistep transaction with scope guards to ensure exception safety.
How to do it…
In order to use scope guards to manage transactions, perform the following steps:
Begin your transaction.
Write a
scope(success)
guard to commit the transaction immediately after starting it (if committing isn't implicit).Write a
scope(failure)
guard to roll back the transaction immediately after starting it. You may use multiple blocks to rollback multiple steps.Write a
scope(exit)
guard to free any resources. Write the free code immediately after the acquisition code. You may use multiple blocks to free multiple resources.Write the following code for your transaction:
{ // performing a SQL transaction database.query("START TRANSACTION"); scope(success) database...