2012-11-11 17 views
2

我已經編寫了代碼來處理整個我的應用程序中的嵌套事務。但是當它回滾一次之後,所有事務都會回滾,直到我重新啓動應用程序。如何在SQLAlchemy中使用具有作用域會話的嵌套事務?

# 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

您使用的是哪個引擎? –

+0

將'except:'替換爲'SomeSpecificExceptionClass:'除外。 'except:'捕獲所有*錯誤,而您可能只想捕獲數據庫引發的某些特定錯誤。 – Bakuriu

+0

我正在使用mysql InoDB存儲引擎 – pravin4659

回答

3

除非正在使用SAVEPOINT,但在此情況並非如此,session.rollback()會回滾整個事務,無論嵌套如何。與「子事務」嵌套的目的是使得幾個代碼塊可以分別指定它們「開始()」和「提交()」事務,而不管這些方法中的一個是否調用另一個。它只有最外層的 begin()/ commit()對有任何作用,因此這裏的代碼相當於在method_b()中完成begin()/ commit()調用時的no

「子事務」模式主要出於框架集成的目的而存在,不適用於一般用途。

+1

可能有用的提到,這隻適用於'autocommit = True' http://docs.sqlalchemy.org/en/rel_1_0/orm/session_transaction.html#using-subtransactions-with-自動提交 – ezdazuzena