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()
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.
Rolling Back. Session. rollback() rolls back the current transaction, if any.
flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With