Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get SQLAlchemy nested rollback error?

I got an error as follows in my code of python (which collects twitter statuses and store in database).

sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back by a nested rollback() call.  To begin a new transaction, issue Session.rollback() first. 

I want to know what is the problem, why does it occur, and how can I solve it.

I have no idea about nested rollback. Is there any simple example which occurs nested rollback?

like image 356
fbessho Avatar asked Jan 15 '12 14:01

fbessho


People also ask

What is Autocommit Sqlalchemy?

The “autocommit” feature is only in effect when no Transaction has otherwise been declared. This means the feature is not generally used with the ORM, as the Session object by default always maintains an ongoing Transaction .

What is Sqlalchemy flush?

flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.

How do I create a transaction in Sqlalchemy?

connection() method at the start of a transaction: from sqlalchemy. orm import Session # assume session just constructed sess = Session(bind=engine) # call connection() with options before any other operations proceed. # this will procure a new connection from the bound engine and begin a real # database transaction.


1 Answers

The problem was solved. The point, in this case, is that rollback is not executed until we call rollback explicitly, so when we include commit(), we should write it in a try statement, and write rollback() in the exception statement (in most case) as written in https://docs.sqlalchemy.org/en/13/faq/sessions.html#this-session-s-transaction-has-been-rolled-back-due-to-a-previous-exception-during-flush-or-similar

And, here is the correct code example. I quoted this from the link above.

try:     <use session>     session.commit() except:     session.rollback()     raise finally:     session.close()  # optional, depends on use case 
like image 186
fbessho Avatar answered Oct 02 '22 16:10

fbessho