Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When session.flush() failed on SQLAlchemy, should I call rollback?

I know rollback called when session.commit() failed such as try-except block.
But when session.flush() failed, should I execute rollback()?

try:
    session.flush()
except IntegrityError:
    session.rollback()
like image 289
Jony cruse Avatar asked Aug 31 '15 06:08

Jony cruse


People also ask

How do I rollback SQLAlchemy?

Using SAVEPOINT commit() method on this object is called, “RELEASE SAVEPOINT” is emitted to the database, and if instead the . rollback() method is called, “ROLLBACK TO SAVEPOINT” is emitted. The enclosing database transaction remains in progress.

What does Session rollback () do?

Rolling Back. Session. rollback() rolls back the current transaction, if any.

What does flush do SQLAlchemy?

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

What does Session refresh do SQLAlchemy?

The Session. expire() and Session. refresh() methods are used in those cases when one wants to force an object to re-load its data from the database, in those cases when it is known that the current state of data is possibly stale.


2 Answers

The accepted answer is not entirely correct. The documentation about Session.flush() is a bit misleading about this.

Upon failure, the transaction (i.e. the database transaction) will be rolled back (by the database). Its python counterpart, the Session object itself will then be in an "inactive" state and, according to the documentation 1 2

must be explicitly rolled back by the calling application, in the same way that it would otherwise need to be explicitly committed if a failure had not occurred.

It does further acknowledge that

this is a common error when using the ORM

like image 150
Michael Ekoka Avatar answered Oct 01 '22 23:10

Michael Ekoka


Failed flush is always rolled back, you do not need to do it yourself:

http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.flush

Database operations will be issued in the current transactional context and do not affect the state of the transaction, unless an error occurs, in which case the entire transaction is rolled back. You may flush() as often as you like within a transaction to move changes from Python to the database’s transaction buffer.

like image 34
Mikko Ohtamaa Avatar answered Oct 01 '22 22:10

Mikko Ohtamaa