Deprecated ORM Event Interfaces

This section describes the class-based ORM event interface which firstexisted in SQLAlchemy 0.1, which progressed with more kinds of events upuntil SQLAlchemy 0.5. The non-ORM analogue is described at Deprecated Event Interfaces.

Deprecated since version 0.7: As of SQLAlchemy 0.7, the new event system described inEvents replaces the extension/proxy/listener system, providinga consistent interface to all events without the need for subclassing.

Mapper Events

  • class sqlalchemy.orm.interfaces.MapperExtension
  • Base implementation for Mapper event hooks.

Deprecated since version 0.7: MapperExtension is deprecated and will be removed in a futurerelease. Please refer to event.listen() in conjunction withthe MapperEvents listener interface.

New extension classes subclass MapperExtension and are specifiedusing the extension mapper() argument, which is a singleMapperExtension or a list of such:

  1. from sqlalchemy.orm.interfaces import MapperExtension
  2.  
  3. class MyExtension(MapperExtension):
  4. def before_insert(self, mapper, connection, instance):
  5. print "instance %s before insert !" % instance
  6.  
  7. m = mapper(User, users_table, extension=MyExtension())

A single mapper can maintain a chain of MapperExtensionobjects. When a particular mapping event occurs, thecorresponding method on each MapperExtension is invokedserially, and each method has the ability to halt the chainfrom proceeding further:

  1. m = mapper(User, users_table, extension=[ext1, ext2, ext3])

Each MapperExtension method returns the symbolEXT_CONTINUE by default. This symbol generally means “moveto the next MapperExtension for processing”. For methodsthat return objects like translated rows or new objectinstances, EXT_CONTINUE means the result of the methodshould be ignored. In some cases it’s required for adefault mapper activity to be performed, such as adding anew instance to a result list.

The symbol EXT_STOP has significance within a chainof MapperExtension objects that the chain will be stoppedwhen this symbol is returned. Like EXT_CONTINUE, it alsohas additional significance in some cases that a defaultmapper activity will not be performed.

  • afterdelete(_mapper, connection, instance)
  • Receive an object instance after that instance is deleted.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • afterinsert(_mapper, connection, instance)
  • Receive an object instance after that instance is inserted.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • afterupdate(_mapper, connection, instance)
  • Receive an object instance after that instance is updated.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • beforedelete(_mapper, connection, instance)
  • Receive an object instance before that instance is deleted.

Note that no changes to the overall flush plan can be madehere; and manipulation of the Session will not have thedesired effect. To manipulate the Session within anextension, use SessionExtension.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • beforeinsert(_mapper, connection, instance)
  • Receive an object instance before that instance is insertedinto its table.

This is a good place to set up primary key values and suchthat aren’t handled otherwise.

Column-based attributes can be modified within this methodwhich will result in the new value being inserted. Howeverno changes to the overall flush plan can be made, andmanipulation of the Session will not have the desired effect.To manipulate the Session within an extension, useSessionExtension.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • beforeupdate(_mapper, connection, instance)
  • Receive an object instance before that instance is updated.

Note that this method is called for all instances that are marked as“dirty”, even those which have no net changes to their column-basedattributes. An object is marked as dirty when any of its column-basedattributes have a “set attribute” operation called or when any of itscollections are modified. If, at update time, no column-basedattributes have any net changes, no UPDATE statement will be issued.This means that an instance being sent to beforeupdate is _not aguarantee that an UPDATE statement will be issued (although you canaffect the outcome here).

To detect if the column-based attributes on the object have netchanges, and will therefore generate an UPDATE statement, useobject_session(instance).is_modified(instance,include_collections=False).

Column-based attributes can be modified within this methodwhich will result in the new value being updated. Howeverno changes to the overall flush plan can be made, andmanipulation of the Session will not have the desired effect.To manipulate the Session within an extension, useSessionExtension.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • initfailed(_mapper, class__, _oldinit, instance, args, kwargs)
  • Receive an instance when its constructor has been called,and raised an exception.

This method is only called during a userland construction ofan object. It is not called when an object is loaded from thedatabase.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • initinstance(_mapper, class__, _oldinit, instance, args, kwargs)
  • Receive an instance when its constructor is called.

This method is only called during a userland construction ofan object. It is not called when an object is loaded from thedatabase.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • instrumentclass(_mapper, class_)
  • Receive a class when the mapper is first constructed, and hasapplied instrumentation to the mapped class.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

  • reconstructinstance(_mapper, instance)
  • Receive an object instance after it has been created vianew, and after initial attribute population hasoccurred.

This typically occurs when the instance is created based onincoming result rows, and is only called once for thatinstance’s lifetime.

Note that during a result-row load, this method is called uponthe first row received for this instance. Note that someattributes and collections may or may not be loaded or eveninitialized, depending on what’s present in the result rows.

The return value is only significant within the MapperExtensionchain; the parent mapper’s behavior isn’t modified by this method.

Session Events

  • class sqlalchemy.orm.interfaces.SessionExtension
  • Base implementation for Session event hooks.

Deprecated since version 0.7: SessionExtension is deprecated and will be removed in a futurerelease. Please refer to event.listen() in conjunction withthe SessionEvents listener interface.

Subclasses may be installed into a Session (orsessionmaker) using the extension keywordargument:

  1. from sqlalchemy.orm.interfaces import SessionExtension
  2.  
  3. class MySessionExtension(SessionExtension):
  4. def before_commit(self, session):
  5. print "before commit!"
  6.  
  7. Session = sessionmaker(extension=MySessionExtension())

The same SessionExtension instance can be usedwith any number of sessions.

  • afterattach(_session, instance)
  • Execute after an instance is attached to a session.

This is called after an add, delete or merge.

  • afterbegin(_session, transaction, connection)
  • Execute after a transaction is begun on a connection

transaction is the SessionTransaction. This method is calledafter an engine level transaction is begun on a connection.

  • afterbulk_delete(_session, query, query_context, result)
  • Execute after a bulk delete operation to the session.

This is called after a session.query(…).delete()

query is the query object that this delete operation wascalled on. query_context was the query context object.result is the result object returned from the bulk operation.

  • afterbulk_update(_session, query, query_context, result)
  • Execute after a bulk update operation to the session.

This is called after a session.query(…).update()

query is the query object that this update operation wascalled on. query_context was the query context object.result is the result object returned from the bulk operation.

  • aftercommit(_session)
  • Execute after a commit has occurred.

Note that this may not be per-flush if a longer runningtransaction is ongoing.

  • afterflush(_session, flush_context)
  • Execute after flush has completed, but before commit has beencalled.

Note that the session’s state is still in pre-flush, i.e. ‘new’,‘dirty’, and ‘deleted’ lists still show pre-flush state as wellas the history settings on instance attributes.

  • afterflush_postexec(_session, flush_context)
  • Execute after flush has completed, and after the post-execstate occurs.

This will be when the ‘new’, ‘dirty’, and ‘deleted’ lists are intheir final state. An actual commit() may or may not haveoccurred, depending on whether or not the flush started its owntransaction or participated in a larger transaction.

  • afterrollback(_session)
  • Execute after a rollback has occurred.

Note that this may not be per-flush if a longer runningtransaction is ongoing.

  • beforecommit(_session)
  • Execute right before commit is called.

Note that this may not be per-flush if a longer runningtransaction is ongoing.

  • beforeflush(_session, flush_context, instances)
  • Execute before flush process has started.

instances is an optional list of objects which were passed tothe flush() method.

Attribute Events

  • class sqlalchemy.orm.interfaces.AttributeExtension
  • Base implementation for AttributeImpl event hooks, eventsthat fire upon attribute mutations in user code.

Deprecated since version 0.7: AttributeExtension is deprecated and will be removed in afuture release. Please refer to event.listen() in conjunctionwith the AttributeEvents listener interface.

AttributeExtension is used to listen for set,remove, and append events on individual mapped attributes.It is established on an individual mapped attribute usingthe extension argument, available oncolumn_property(), relationship(), andothers:

  1. from sqlalchemy.orm.interfaces import AttributeExtension
  2. from sqlalchemy.orm import mapper, relationship, column_property
  3.  
  4. class MyAttrExt(AttributeExtension):
  5. def append(self, state, value, initiator):
  6. print "append event !"
  7. return value
  8.  
  9. def set(self, state, value, oldvalue, initiator):
  10. print "set event !"
  11. return value
  12.  
  13. mapper(SomeClass, sometable, properties={
  14. 'foo':column_property(sometable.c.foo, extension=MyAttrExt()),
  15. 'bar':relationship(Bar, extension=MyAttrExt())
  16. })

Note that the AttributeExtension methodsappend() andset() need to return thevalue parameter. The returned value is used as theeffective value, and allows the extension to change what isultimately persisted.

AttributeExtension is assembled within the descriptors associatedwith a mapped class.

  • activehistory = True_
  • indicates that the set() method would like to receive the ‘old’ value,even if it means firing lazy callables.

Note that active_history can also be set directly viacolumn_property() and relationship().

  • append(state, value, initiator)
  • Receive a collection append event.

The returned value will be used as the actual value to beappended.

  • remove(state, value, initiator)
  • Receive a remove event.

No return value is defined.

  • set(state, value, oldvalue, initiator)
  • Receive a set event.

The returned value will be used as the actual value to beset.