On Mon, Aug 3, 2015 at 2:56 PM, K. Frank <kfrank2...@gmail.com> wrote:

> Hello List!
>
> I am looking at the Wt::Dbo tutorial:
>
>    http://www.webtoolkit.eu/wt/doc/tutorial/dbo.html
>
> and, specifically, the example code:
>
>     ...
>     /*
>      * A unit of work happens always within a transaction.
>      */
>     dbo::Transaction transaction(session);
>
>     User *user = new User();
>     user->name = "Joe";
>     user->password = "Secret";
>     user->role = User::Visitor;
>     user->karma = 13;
>
>     dbo::ptr<User> userPtr = session.add(user);
>    }
>
> I would like to clarify a few points:
>
> First, as I understand it, the constructor of Wt::Dbo::Transaction
> (called when the local variable "transaction" is declared) causes
> the "begin transaction" SQL statement to be called.  Is this correct?
>

yup. To see evidence of this (and much more), use
 Wt::Dbo::backend::Sqlite3::setProperty("show-queries", "true");


>
> Then, when the destructor is called (when "transaction" goes out
> of scope at the closing brace in the example), the transaction is
> committed, i.e., the "commit transaction" SQL statement is called.
> Is this also correct?
>

As long as no exception is being thrown, yes.


>
> I'm a little confused about what happens if an exception is thrown.
> Presumably an SQL "rollback transaction" will be executed.  But
> how?  Destructors will be called for local variable within the try block.
> So, tweaking the example code a little:
>
>    try {
>       dbo::Transaction transaction(session);
>
>       User *user = new User();
>       user->name = "Joe";
>       user->password = "Secret";
>       user->role = User::Visitor;
>       user->karma = 13;
>
>       dbo::ptr<User> userPtr = session.add(user);
>    }
>    catch (...) {
>       // ...
>    }
>
> If an exception is thrown in the try block, the destructor for
> "transaction"
> will be called.  How will this destructor know to call "rollback
> transaction",
> rather than "commit transaction"?  One possibility is that if the call to
> "session.add" fails and throws an exception, it could first set some
> "dirty transaction" flag that gets inspection by Wt::Dbo::Transaction's
> destructor.  But what if it's not a Wt::Dbo exception?  Suppose I add
> the line "if (42)  throw 17;" to the try block.  How would the destructor
> then know to roll back the SQL transaction?
>
> (Or is this some kind of c++ thing where the destructor "knows" that
> it's being called in an exception-triggered stack unwind?)
>

It's some kind of C++ thing:
http://en.cppreference.com/w/cpp/error/uncaught_exception

Happy coding!

In Christ,
Aaron Laws
------------------------------------------------------------------------------
_______________________________________________
witty-interest mailing list
witty-interest@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/witty-interest

Reply via email to