Session rollback fails to undo an attribute change.

Issue #3072 closed
ehynes created an issue

Calling session.rollback() while following along with the ORM tutorial failed to revert the user name from 'Edwardo' back to 'ed'.

Comments (2)

  1. Mike Bayer repo owner

    The User object here is not present in the database after the rollback, and whatever data is inside of it is gone. There's no way to get the "ed" back. when the rollback happens, technically it might be more "correct" to just erase everything inside the User object that's created, since the INSERT, if any, was cancelled (in this case there's not even an INSERT unless you said session.flush()). But that's a little heavy handed, so whatever state was present on the non-inserted row just stays there:

    session = Session()
    
    session.add(ed_user)
    
    ed_user.name = 'Edwardo'
    session.rollback()
    
    assert ed_user not in session
    

    to see the rollback, you need to roll back to a row that is persistent:

    session.add(ed_user)
    session.commit()  # ed_user's row is now permanently in the DB
    
    ed_user.name = 'Edwardo' # new transaction.
    session.rollback()  # roll it back.
    
    assert ed_user in session  # ed_user still in session, still managed
    assert ed_user.name == 'ed', ed_user.name  # old value is there
    
  2. Log in to comment