On Jul 24, 2014, at 3:25 AM, George Sakkis <george.sak...@gmail.com> wrote:

> I'm a bit confused about the difference between (a) an instance "belonging 
> to" a session as determined by object_session(obj) and (b) "being in" the 
> session as determined by obj in session. To illustrate:
> 
>     from sqlalchemy import Column, Integer, String, create_engine
>     from sqlalchemy.ext.declarative import declarative_base
>     from sqlalchemy.orm import sessionmaker
>     
>     Base = declarative_base()
>     
>     class User(Base):
>         __tablename__ = "users"
>         id = Column(Integer, primary_key=True)
>         name = Column(String)
>     
>     
>     if __name__ == "__main__":
>         engine = create_engine("sqlite:///:memory:", echo=False)
>         Base.metadata.create_all(engine)
>         Session = sessionmaker(bind=engine)
>         session = Session()
>     
>         ed = User(name="ed")
>     
>         def log(msg):
>             print "{}: {}".format(msg, (Session.object_session(ed) is not 
> None,
>                                         ed in session))
>     
>         log("After instantiation")
>     
>         session.add(ed)
>         log("After add")
>     
>         session.flush()
>         log("After flush")
>     
>         session.delete(ed)
>         log("After delete")
>     
>         session.flush()
>         log("After flush")
>     
>         session.expunge(ed)
>         log("After expunge")
> 
> 
> The output is:
> 
> After instantiation: (False, False)
> After add: (True, True)
> After flush: (True, True)
> After delete: (True, True)
> After flush: (True, False)
> After expunge: (True, False)
> 
> So up to the last flush() these two coincide but after flush() deletes the 
> instance, it still "belongs to" the session while not being in it.

expunge() is a bug:

https://bitbucket.org/zzzeek/sqlalchemy/issue/3139/expunge-after-delete-fails

it's supposed to raise (hence can't fix this til 1.0).

so ignore expunge.  if you were to emit session.rollback(), you'd find the 
DELETE is rolled back and you'd again get True, True.   The Session still knows 
about this object within the transaction's "ready to roll back" state.   The 
object isn't permanently not part of the Session until the commit():

        
    session.commit()
    log("commit")


output:

commit: (False, False)



-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to