pravin4659
pravin4659

Reputation: 181

How to use nested transaction with scoped session in SQLAlchemy?

I have written code bellow for handling nested transaction throughout my application. But when it rollback once after that all the transaction get rollback till I restart application.

# method_a starts a transaction and calls method_b
def method_a():
    session.begin(subtransactions=True)
    try:
        method_b()
        session.commit()  # transaction is committed here
    except:
        session.rollback() # rolls back the transaction


# method_b also starts a transaction, but when
# called from method_a participates in the ongoing
# transaction.
def method_b():
    session.begin(subtransactions=True)
    try:
        session.add(SomeObject('bat', 'lala'))
        session.commit()  # transaction is not committed yet
    except:
        session.rollback() # rolls back the transaction, in this case
                       # the one that was initiated in method_a().


# create a Session and call method_a
session = Session(autocommit=True)
global session
method_a(session)

Upvotes: 8

Views: 16994

Answers (1)

zzzeek
zzzeek

Reputation: 75117

unless SAVEPOINT is being used, which is not the case here, session.rollback() rolls back the entire transaction, regardless of nesting. The purpose of nesting with "subtransactions" is so that several blocks of code can each specify that they "begin()" and "commit()" a transaction, independently of whether or not one of those methods calls the other. It is only the outermost begin()/commit() pair that has any effect, so the code here is equivalent to there being no begin()/commit() call in method_b() at all.

The "subtransactions" pattern exists mostly for the purposes of framework integrations and is not intended for general use.

Upvotes: 7

Related Questions