Default scope of variables

Chris Angelico rosuav at gmail.com
Tue Jul 9 09:45:56 CEST 2013


On Tue, Jul 9, 2013 at 5:35 PM, Frank Millman <frank at chagford.com> wrote:
> I have been following this sub-thread with interest, as it resonates with
> what I am doing in my project.

Just FYI, none of my own code will help you as it's all using libpqxx,
but the docs for the library itself are around if you want them (it's
one of the standard ways for C++ programs to use PostgreSQL).

> I came up with the following context manager -
>
> class DbSession:
>     def __exit__(self, type, exc, tb):
>             if self.transaction_active:
>                 self.conn.commit()
>                 self.transaction_active = False

Hmm. So you automatically commit. I'd actually be inclined to _not_ do
this; make it really explicit in your code that you now will commit
this transaction (which might throw an exception if you have open
subtransactions). The way the code with libpqxx works is that any
transaction (including a subtransaction) must be explicitly committed,
or it will be rolled back. So there's one possible code path that
results in persistent changes to the database, and anything else
won't:

* If the object expires without being committed, it's rolled back.
* If an exception is thrown and unwinds the stack, roll back.
* If a Unix signal is sent that terminates the program, roll back.
* If the process gets killed -9, definitely roll back.
* If the computer the program's running on spontaneously combusts, roll back.
* If the hard drive is physically ripped from the server during
processing, roll back.

(Note though that most of these guarantees are from PostgreSQL, not
from libpqxx. I'm talking about the whole ecosystem here, not
something one single library can handle.)

I have absolute 100% confidence that nothing can possibly affect the
database unless I explicitly commit it (aside from a few
non-transaction actions like advancing a sequence pointer, which
specifically don't matter (rolled back transactions can result in gaps
in a sequence of record IDs, nothing more)). It's an extremely
comfortable work environment - I can write whatever code I like, and
if I'm not sure if it'll work or not, I just comment out the commit
line and run. *Nothing* can get past that and quietly commit it behind
my back.

ChrisA



More information about the Python-list mailing list