lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Tue, Jan 4, 2011 at 2:21 PM, Eike Decker <> wrote:
> Can anyone give me a pointer how to handle db transaction(s/ objects)
> "gracefully"?
> Let's say I have a database connection. The "classic" way would be
> ---
> db:query "begin"
> ...
> db:query "commit"
> ---
> However, the commit or rollback might be forgotten, or more likely,
> omitted in case of coroutine yields (without resume) or on errors -
> that merrily jump across the function calls.
> A __gc function could be used to rollback on collection, but this
> measure is not instant and therefore only a measure of last resort
> (when Lua exits for example). Besides that, the order of __gc calls is
> not guaranteed to be defined (right?).
> In C++, one can handle this case by having an object on the stack that
> has a destructor that gets called if the object is unwound from the
> stack. This technique doesn't work in Lua however, due to the nature
> of garbage collection.
> Does anyone know a nice solution to this?

Wrap your query and commit in a single function, pass it to a
protected call and execute a rollback if the call fails:

-- query() and handle() are user functions
result, error = pcall(query())
query_result = result or handle(error)

If you're trying to do something like reuse a connection or work
around blocking I/O then look into data access patterns.