<s> """<STR_LIT>""" <EOL> from sqlalchemy . orm import * <EOL> from sqlalchemy import * <EOL> from sqlalchemy . orm . interfaces import SessionExtension <EOL> from sqlalchemy . ext . declarative import declarative_base <EOL> from sqlalchemy . orm import attributes <EOL> class Versioned ( object ) : <EOL> def new_version ( self , session ) : <EOL> make_transient ( self ) <EOL> self . id = None <EOL> class VersionExtension ( SessionExtension ) : <EOL> def before_flush ( self , session , flush_context , instances ) : <EOL> for instance in session . dirty : <EOL> if not isinstance ( instance , Versioned ) : <EOL> continue <EOL> if not session . is_modified ( instance , passive = True ) : <EOL> continue <EOL> if not attributes . instance_state ( instance ) . has_identity : <EOL> continue <EOL> instance . new_version ( session ) <EOL> session . add ( instance ) <EOL> Base = declarative_base ( ) <EOL> engine = create_engine ( '<STR_LIT>' , echo = True ) <EOL> Session = sessionmaker ( engine , extension = [ VersionExtension ( ) ] ) <EOL> class Example ( Versioned , Base ) : <EOL> __tablename__ = '<STR_LIT>' <EOL> id = Column ( Integer , primary_key = True ) <EOL> data = Column ( String ) <EOL> Base . metadata . create_all ( engine ) <EOL> session = Session ( ) <EOL> e1 = Example ( data = '<STR_LIT>' ) <EOL> session . add ( e1 ) <EOL> session . commit ( ) <EOL> e1 . data = '<STR_LIT>' <EOL> session . commit ( ) <EOL> assert session . query ( Example . id , Example . data ) . order_by ( Example . id ) . all ( ) == [ ( <NUM_LIT:1> , '<STR_LIT>' ) , ( <NUM_LIT:2> , '<STR_LIT>' ) ] <EOL> class Parent ( Base ) : <EOL> __tablename__ = '<STR_LIT>' <EOL> id = Column ( Integer , primary_key = True ) <EOL> child_id = Column ( Integer , ForeignKey ( '<STR_LIT>' ) ) <EOL> child = relationship ( "<STR_LIT>" , backref = backref ( '<STR_LIT>' , uselist = False ) ) <EOL> class Child ( Versioned , Base ) : <EOL> __tablename__ = '<STR_LIT>' <EOL> id = Column ( Integer , primary_key = True ) <EOL> data = Column ( String ) <EOL> def new_version ( self , session ) : <EOL> session . expire ( self . parent , [ '<STR_LIT>' ] ) <EOL> Versioned . new_version ( self , session ) <EOL> self . parent . child = self <EOL> Base . metadata . create_all ( engine ) <EOL> session = Session ( ) <EOL> p1 = Parent ( child = Child ( data = '<STR_LIT>' ) ) <EOL> session . add ( p1 ) <EOL> session . commit ( ) <EOL> p1 . child . data = '<STR_LIT>' <EOL> session . commit ( ) <EOL> assert p1 . child_id == <NUM_LIT:2> <EOL> assert session . query ( Child . id , Child . data ) . order_by ( Child . id ) . all ( ) == [ ( <NUM_LIT:1> , '<STR_LIT>' ) , ( <NUM_LIT:2> , '<STR_LIT>' ) ] </s>
