On 6/12/22 4:11 PM, kdevel wrote:
On Tuesday, 7 June 2022 at 18:37:13 UTC, Steven Schveighoffer wrote:
[...]
My very common use of `scope(failure)` for my DB code:

```d
conn.exec("START TRANSACTION");
scope(success) conn.exec("COMMIT");
scope(failure) conn.exec("ROLLBACK");
```

Are there multiple (successful) returns in your code or why are you executing the COMMIT under a scope exit clause?

No, usually just one (the implicit final return).

If there is only one successful return wouldn't it enhance code readability when an explicit COMMIT precedes the return?

It just introduces another place where I can mess up the transaction. I can write these 3 lines, and be done, never having to worry about the transaction code again.

This is one of the major features of scope guards.

Is the ROLLBACK really necessary?

Yes. If you don't execute the rollback and start executing more DB calls, they all get included in the transaction (and might be expected to be).

Isn't the transaction not committed (i.e. rolled back) when the db handle is closed?

Possibly, but I don't close the handle. It goes back to a pool to get reused.

Why not have a Transaction class (struct)?

A transaction class/struct cannot hook normal return and throwing differently (the destructor has no way of knowing whether an exception is in flight).

-Steve

Reply via email to