Context

I would like to make use of nested transactions using SQLAlchemy (in 
postgres), but I want to write an independent function that doesn't care if 
the session already has a transaction or not -- it can start a nested 
transaction or outer transaction appropriately.


Question

What is the most elegant syntax to begin a transaction, which will be 
either an outer or nested transaction, as appropriate?

So far the best I have seen is: session.begin(nested=session.is_active)

Is there something better than this?


Discussion

I am using postgres, which does not natively support nested transactions, 
so nested transactions are implemented using the SAVEPOINT command.

Specifically, what the above code does (against postgres, at least) is: * 
If there is no transaction in progress, start a (non-nested) transaction 
(BEGIN) * If there is already a transaction in progress, begin a nested 
transaction (SAVEPOINT)

Is there something better than this? Ideally I'd like to just call 
session.begin() and have it internally work out if it needs to be an outer 
transaction (BEGIN) or a nested transaction (SAVEPOINT) without me having 
to be explicit about it.


Motivation

I would like to write a function f(session) which takes a SQLAlchemy 
session and makes some changes within a transaction. Also, I want the 
ability to rollback the changes that f() has made (and *only* the changes 
that f() has made).

If the calling code has begun a transaction, and made changes, then I don't 
want a rollback within f() to discard changes that were made by the calling 
code.


Thanks in advance,

Dani

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to