我已经在我的应用程序中编写了用于处理嵌套事务的代码。但是当它回滚一次之后,所有事务都会回滚直到我重新启动应用程序。
# 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)
答案 0 :(得分:3)
除非使用SAVEPOINT,否则session.rollback()会回滚整个事务,无论是否嵌套。嵌套“子事务”的目的是使得几个代码块可以分别指定它们“begin()”和“commit()”事务,而不管这些方法中的一个是否调用另一个。只有最外层 begin()/ commit()对有任何影响,所以这里的代码等同于 no begin()/ commit()调用在method_b()中。
“子交易”模式主要用于框架集成,不适用于一般用途。