Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Begin your transaction.

  2. Write a scope(success) guard to commit the transaction immediately after starting it (if committing isn't implicit).

  3. Write a scope(failure) guard to roll back the transaction immediately after starting it. You may use multiple blocks to rollback multiple steps.

  4. 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.

  5. Write the following code for your transaction:

    {
      // performing a SQL transaction
      database.query("START TRANSACTION");
      scope(success) database...