Session.clear() doesn't work after IntegrityError

Issue #716 resolved
Former user created an issue

As a followup to #704, Session.clear() fails after IntegrityError where Session.expunge(obj) works. See attached example.

Comments (1)

  1. Mike Bayer repo owner

    theres two ways to prevent whats happening from happening.

    one is to turn off "cascade" from Host to User:

    orm.mapper(Host, host_table, properties={
        'users': orm.relation(User, backref='host', cascade="none")
    })
    

    the other, to explicitly remove user2 from host.users:

    try:
        user2 = User('ryan', host)
        session.save(user2)
        session.flush()
    except SQLError:
        session.clear()  # this doesn't work
        host.users.remove(user2)
    

    When you say session.expunge(user2), user2 is removed. then when you say User('joe', host), user3 is added to the session, the 'save-update' cascade fires off, sees that host is already in the session, and stops.

    in contrast, when you say session.clear(), both user2 and host are removed. then upon saving user3, the 'save-update' cascade hits host, keeps on cascading, hits user2, and re-adds it to the session.

    Therefore either disabling this cascade from Host to User, or ensuring that user2 is removed from all cascading collections, prevents the object from being re-saved to the session.

  2. Log in to comment