lua-users home
lua-l archive

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


Hi,

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? I've been thinking about
having a gateway function that catches errors and yields and unwinds
the transaction stack properly (though coroutine yields are ... pretty
evil since I don't know if it'll be resumed).
I could of course simply put "carefully" begins, commits and rollbacks
where I believe it would be required, but I doubt I can manage to do
that properly.

Cheers,
Eike