Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/sqlalchemy/orm/events.py : 56%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# orm/events.py
2# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
3# <see AUTHORS file>
4#
5# This module is part of SQLAlchemy and is released under
6# the MIT License: http://www.opensource.org/licenses/mit-license.php
8"""ORM event interfaces.
10"""
11import weakref
13from . import instrumentation
14from . import interfaces
15from . import mapperlib
16from .attributes import QueryableAttribute
17from .base import _mapper_or_none
18from .query import Query
19from .scoping import scoped_session
20from .session import Session
21from .session import sessionmaker
22from .. import event
23from .. import exc
24from .. import util
25from ..util.compat import inspect_getfullargspec
28class InstrumentationEvents(event.Events):
29 """Events related to class instrumentation events.
31 The listeners here support being established against
32 any new style class, that is any object that is a subclass
33 of 'type'. Events will then be fired off for events
34 against that class. If the "propagate=True" flag is passed
35 to event.listen(), the event will fire off for subclasses
36 of that class as well.
38 The Python ``type`` builtin is also accepted as a target,
39 which when used has the effect of events being emitted
40 for all classes.
42 Note the "propagate" flag here is defaulted to ``True``,
43 unlike the other class level events where it defaults
44 to ``False``. This means that new subclasses will also
45 be the subject of these events, when a listener
46 is established on a superclass.
48 """
50 _target_class_doc = "SomeBaseClass"
51 _dispatch_target = instrumentation.InstrumentationFactory
53 @classmethod
54 def _accept_with(cls, target):
55 if isinstance(target, type):
56 return _InstrumentationEventsHold(target)
57 else:
58 return None
60 @classmethod
61 def _listen(cls, event_key, propagate=True, **kw):
62 target, identifier, fn = (
63 event_key.dispatch_target,
64 event_key.identifier,
65 event_key._listen_fn,
66 )
68 def listen(target_cls, *arg):
69 listen_cls = target()
70 if propagate and issubclass(target_cls, listen_cls):
71 return fn(target_cls, *arg)
72 elif not propagate and target_cls is listen_cls:
73 return fn(target_cls, *arg)
75 def remove(ref):
76 key = event.registry._EventKey(
77 None,
78 identifier,
79 listen,
80 instrumentation._instrumentation_factory,
81 )
82 getattr(
83 instrumentation._instrumentation_factory.dispatch, identifier
84 ).remove(key)
86 target = weakref.ref(target.class_, remove)
88 event_key.with_dispatch_target(
89 instrumentation._instrumentation_factory
90 ).with_wrapper(listen).base_listen(**kw)
92 @classmethod
93 def _clear(cls):
94 super(InstrumentationEvents, cls)._clear()
95 instrumentation._instrumentation_factory.dispatch._clear()
97 def class_instrument(self, cls):
98 """Called after the given class is instrumented.
100 To get at the :class:`.ClassManager`, use
101 :func:`.manager_of_class`.
103 """
105 def class_uninstrument(self, cls):
106 """Called before the given class is uninstrumented.
108 To get at the :class:`.ClassManager`, use
109 :func:`.manager_of_class`.
111 """
113 def attribute_instrument(self, cls, key, inst):
114 """Called when an attribute is instrumented."""
117class _InstrumentationEventsHold(object):
118 """temporary marker object used to transfer from _accept_with() to
119 _listen() on the InstrumentationEvents class.
121 """
123 def __init__(self, class_):
124 self.class_ = class_
126 dispatch = event.dispatcher(InstrumentationEvents)
129class InstanceEvents(event.Events):
130 """Define events specific to object lifecycle.
132 e.g.::
134 from sqlalchemy import event
136 def my_load_listener(target, context):
137 print("on load!")
139 event.listen(SomeClass, 'load', my_load_listener)
141 Available targets include:
143 * mapped classes
144 * unmapped superclasses of mapped or to-be-mapped classes
145 (using the ``propagate=True`` flag)
146 * :class:`_orm.Mapper` objects
147 * the :class:`_orm.Mapper` class itself and the :func:`.mapper`
148 function indicate listening for all mappers.
150 Instance events are closely related to mapper events, but
151 are more specific to the instance and its instrumentation,
152 rather than its system of persistence.
154 When using :class:`.InstanceEvents`, several modifiers are
155 available to the :func:`.event.listen` function.
157 :param propagate=False: When True, the event listener should
158 be applied to all inheriting classes as well as the
159 class which is the target of this listener.
160 :param raw=False: When True, the "target" argument passed
161 to applicable event listener functions will be the
162 instance's :class:`.InstanceState` management
163 object, rather than the mapped instance itself.
164 :param restore_load_context=False: Applies to the
165 :meth:`.InstanceEvents.load` and :meth:`.InstanceEvents.refresh`
166 events. Restores the loader context of the object when the event
167 hook is complete, so that ongoing eager load operations continue
168 to target the object appropriately. A warning is emitted if the
169 object is moved to a new loader context from within one of these
170 events if this flag is not set.
172 .. versionadded:: 1.3.14
175 """
177 _target_class_doc = "SomeClass"
179 _dispatch_target = instrumentation.ClassManager
181 @classmethod
182 def _new_classmanager_instance(cls, class_, classmanager):
183 _InstanceEventsHold.populate(class_, classmanager)
185 @classmethod
186 @util.dependencies("sqlalchemy.orm")
187 def _accept_with(cls, orm, target):
188 if isinstance(target, instrumentation.ClassManager):
189 return target
190 elif isinstance(target, mapperlib.Mapper):
191 return target.class_manager
192 elif target is orm.mapper:
193 return instrumentation.ClassManager
194 elif isinstance(target, type):
195 if issubclass(target, mapperlib.Mapper):
196 return instrumentation.ClassManager
197 else:
198 manager = instrumentation.manager_of_class(target)
199 if manager:
200 return manager
201 else:
202 return _InstanceEventsHold(target)
203 return None
205 @classmethod
206 def _listen(
207 cls,
208 event_key,
209 raw=False,
210 propagate=False,
211 restore_load_context=False,
212 **kw
213 ):
214 target, fn = (event_key.dispatch_target, event_key._listen_fn)
216 if not raw or restore_load_context:
218 def wrap(state, *arg, **kw):
219 if not raw:
220 target = state.obj()
221 else:
222 target = state
223 if restore_load_context:
224 runid = state.runid
225 try:
226 return fn(target, *arg, **kw)
227 finally:
228 if restore_load_context:
229 state.runid = runid
231 event_key = event_key.with_wrapper(wrap)
233 event_key.base_listen(propagate=propagate, **kw)
235 if propagate:
236 for mgr in target.subclass_managers(True):
237 event_key.with_dispatch_target(mgr).base_listen(propagate=True)
239 @classmethod
240 def _clear(cls):
241 super(InstanceEvents, cls)._clear()
242 _InstanceEventsHold._clear()
244 def first_init(self, manager, cls):
245 """Called when the first instance of a particular mapping is called.
247 This event is called when the ``__init__`` method of a class
248 is called the first time for that particular class. The event
249 invokes before ``__init__`` actually proceeds as well as before
250 the :meth:`.InstanceEvents.init` event is invoked.
252 """
254 def init(self, target, args, kwargs):
255 """Receive an instance when its constructor is called.
257 This method is only called during a userland construction of
258 an object, in conjunction with the object's constructor, e.g.
259 its ``__init__`` method. It is not called when an object is
260 loaded from the database; see the :meth:`.InstanceEvents.load`
261 event in order to intercept a database load.
263 The event is called before the actual ``__init__`` constructor
264 of the object is called. The ``kwargs`` dictionary may be
265 modified in-place in order to affect what is passed to
266 ``__init__``.
268 :param target: the mapped instance. If
269 the event is configured with ``raw=True``, this will
270 instead be the :class:`.InstanceState` state-management
271 object associated with the instance.
272 :param args: positional arguments passed to the ``__init__`` method.
273 This is passed as a tuple and is currently immutable.
274 :param kwargs: keyword arguments passed to the ``__init__`` method.
275 This structure *can* be altered in place.
277 .. seealso::
279 :meth:`.InstanceEvents.init_failure`
281 :meth:`.InstanceEvents.load`
283 """
285 def init_failure(self, target, args, kwargs):
286 """Receive an instance when its constructor has been called,
287 and raised an exception.
289 This method is only called during a userland construction of
290 an object, in conjunction with the object's constructor, e.g.
291 its ``__init__`` method. It is not called when an object is loaded
292 from the database.
294 The event is invoked after an exception raised by the ``__init__``
295 method is caught. After the event
296 is invoked, the original exception is re-raised outwards, so that
297 the construction of the object still raises an exception. The
298 actual exception and stack trace raised should be present in
299 ``sys.exc_info()``.
301 :param target: the mapped instance. If
302 the event is configured with ``raw=True``, this will
303 instead be the :class:`.InstanceState` state-management
304 object associated with the instance.
305 :param args: positional arguments that were passed to the ``__init__``
306 method.
307 :param kwargs: keyword arguments that were passed to the ``__init__``
308 method.
310 .. seealso::
312 :meth:`.InstanceEvents.init`
314 :meth:`.InstanceEvents.load`
316 """
318 def load(self, target, context):
319 """Receive an object instance after it has been created via
320 ``__new__``, and after initial attribute population has
321 occurred.
323 This typically occurs when the instance is created based on
324 incoming result rows, and is only called once for that
325 instance's lifetime.
327 .. warning::
329 During a result-row load, this event is invoked when the
330 first row received for this instance is processed. When using
331 eager loading with collection-oriented attributes, the additional
332 rows that are to be loaded / processed in order to load subsequent
333 collection items have not occurred yet. This has the effect
334 both that collections will not be fully loaded, as well as that
335 if an operation occurs within this event handler that emits
336 another database load operation for the object, the "loading
337 context" for the object can change and interfere with the
338 existing eager loaders still in progress.
340 Examples of what can cause the "loading context" to change within
341 the event handler include, but are not necessarily limited to:
343 * accessing deferred attributes that weren't part of the row,
344 will trigger an "undefer" operation and refresh the object
346 * accessing attributes on a joined-inheritance subclass that
347 weren't part of the row, will trigger a refresh operation.
349 As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The
350 :paramref:`.InstanceEvents.restore_load_context` option may be
351 used on the event to prevent this warning; this will ensure that
352 the existing loading context is maintained for the object after the
353 event is called::
355 @event.listens_for(
356 SomeClass, "load", restore_load_context=True)
357 def on_load(instance, context):
358 instance.some_unloaded_attribute
360 .. versionchanged:: 1.3.14 Added
361 :paramref:`.InstanceEvents.restore_load_context`
362 and :paramref:`.SessionEvents.restore_load_context` flags which
363 apply to "on load" events, which will ensure that the loading
364 context for an object is restored when the event hook is
365 complete; a warning is emitted if the load context of the object
366 changes without this flag being set.
369 The :meth:`.InstanceEvents.load` event is also available in a
370 class-method decorator format called :func:`_orm.reconstructor`.
372 :param target: the mapped instance. If
373 the event is configured with ``raw=True``, this will
374 instead be the :class:`.InstanceState` state-management
375 object associated with the instance.
376 :param context: the :class:`.QueryContext` corresponding to the
377 current :class:`_query.Query` in progress. This argument may be
378 ``None`` if the load does not correspond to a :class:`_query.Query`,
379 such as during :meth:`.Session.merge`.
381 .. seealso::
383 :meth:`.InstanceEvents.init`
385 :meth:`.InstanceEvents.refresh`
387 :meth:`.SessionEvents.loaded_as_persistent`
389 :ref:`mapping_constructors`
391 """
393 def refresh(self, target, context, attrs):
394 """Receive an object instance after one or more attributes have
395 been refreshed from a query.
397 Contrast this to the :meth:`.InstanceEvents.load` method, which
398 is invoked when the object is first loaded from a query.
400 .. note:: This event is invoked within the loader process before
401 eager loaders may have been completed, and the object's state may
402 not be complete. Additionally, invoking row-level refresh
403 operations on the object will place the object into a new loader
404 context, interfering with the existing load context. See the note
405 on :meth:`.InstanceEvents.load` for background on making use of the
406 :paramref:`.InstanceEvents.restore_load_context` parameter, in
407 order to resolve this scenario.
409 :param target: the mapped instance. If
410 the event is configured with ``raw=True``, this will
411 instead be the :class:`.InstanceState` state-management
412 object associated with the instance.
413 :param context: the :class:`.QueryContext` corresponding to the
414 current :class:`_query.Query` in progress.
415 :param attrs: sequence of attribute names which
416 were populated, or None if all column-mapped, non-deferred
417 attributes were populated.
419 .. seealso::
421 :meth:`.InstanceEvents.load`
423 """
425 def refresh_flush(self, target, flush_context, attrs):
426 """Receive an object instance after one or more attributes that
427 contain a column-level default or onupdate handler have been refreshed
428 during persistence of the object's state.
430 This event is the same as :meth:`.InstanceEvents.refresh` except
431 it is invoked within the unit of work flush process, and includes
432 only non-primary-key columns that have column level default or
433 onupdate handlers, including Python callables as well as server side
434 defaults and triggers which may be fetched via the RETURNING clause.
436 .. note::
438 While the :meth:`.InstanceEvents.refresh_flush` event is triggered
439 for an object that was INSERTed as well as for an object that was
440 UPDATEd, the event is geared primarily towards the UPDATE process;
441 it is mostly an internal artifact that INSERT actions can also
442 trigger this event, and note that **primary key columns for an
443 INSERTed row are explicitly omitted** from this event. In order to
444 intercept the newly INSERTed state of an object, the
445 :meth:`.SessionEvents.pending_to_persistent` and
446 :meth:`.MapperEvents.after_insert` are better choices.
448 .. versionadded:: 1.0.5
450 :param target: the mapped instance. If
451 the event is configured with ``raw=True``, this will
452 instead be the :class:`.InstanceState` state-management
453 object associated with the instance.
454 :param flush_context: Internal :class:`.UOWTransaction` object
455 which handles the details of the flush.
456 :param attrs: sequence of attribute names which
457 were populated.
459 .. seealso::
461 :ref:`orm_server_defaults`
463 :ref:`metadata_defaults_toplevel`
465 """
467 def expire(self, target, attrs):
468 """Receive an object instance after its attributes or some subset
469 have been expired.
471 'keys' is a list of attribute names. If None, the entire
472 state was expired.
474 :param target: the mapped instance. If
475 the event is configured with ``raw=True``, this will
476 instead be the :class:`.InstanceState` state-management
477 object associated with the instance.
478 :param attrs: sequence of attribute
479 names which were expired, or None if all attributes were
480 expired.
482 """
484 def pickle(self, target, state_dict):
485 """Receive an object instance when its associated state is
486 being pickled.
488 :param target: the mapped instance. If
489 the event is configured with ``raw=True``, this will
490 instead be the :class:`.InstanceState` state-management
491 object associated with the instance.
492 :param state_dict: the dictionary returned by
493 :class:`.InstanceState.__getstate__`, containing the state
494 to be pickled.
496 """
498 def unpickle(self, target, state_dict):
499 """Receive an object instance after its associated state has
500 been unpickled.
502 :param target: the mapped instance. If
503 the event is configured with ``raw=True``, this will
504 instead be the :class:`.InstanceState` state-management
505 object associated with the instance.
506 :param state_dict: the dictionary sent to
507 :class:`.InstanceState.__setstate__`, containing the state
508 dictionary which was pickled.
510 """
513class _EventsHold(event.RefCollection):
514 """Hold onto listeners against unmapped, uninstrumented classes.
516 Establish _listen() for that class' mapper/instrumentation when
517 those objects are created for that class.
519 """
521 def __init__(self, class_):
522 self.class_ = class_
524 @classmethod
525 def _clear(cls):
526 cls.all_holds.clear()
528 class HoldEvents(object):
529 _dispatch_target = None
531 @classmethod
532 def _listen(
533 cls, event_key, raw=False, propagate=False, retval=False, **kw
534 ):
535 target = event_key.dispatch_target
537 if target.class_ in target.all_holds:
538 collection = target.all_holds[target.class_]
539 else:
540 collection = target.all_holds[target.class_] = {}
542 event.registry._stored_in_collection(event_key, target)
543 collection[event_key._key] = (event_key, raw, propagate, retval)
545 if propagate:
546 stack = list(target.class_.__subclasses__())
547 while stack:
548 subclass = stack.pop(0)
549 stack.extend(subclass.__subclasses__())
550 subject = target.resolve(subclass)
551 if subject is not None:
552 # we are already going through __subclasses__()
553 # so leave generic propagate flag False
554 event_key.with_dispatch_target(subject).listen(
555 raw=raw, propagate=False, retval=retval, **kw
556 )
558 def remove(self, event_key):
559 target = event_key.dispatch_target
561 if isinstance(target, _EventsHold):
562 collection = target.all_holds[target.class_]
563 del collection[event_key._key]
565 @classmethod
566 def populate(cls, class_, subject):
567 for subclass in class_.__mro__:
568 if subclass in cls.all_holds:
569 collection = cls.all_holds[subclass]
570 for event_key, raw, propagate, retval in collection.values():
571 if propagate or subclass is class_:
572 # since we can't be sure in what order different
573 # classes in a hierarchy are triggered with
574 # populate(), we rely upon _EventsHold for all event
575 # assignment, instead of using the generic propagate
576 # flag.
577 event_key.with_dispatch_target(subject).listen(
578 raw=raw, propagate=False, retval=retval
579 )
582class _InstanceEventsHold(_EventsHold):
583 all_holds = weakref.WeakKeyDictionary()
585 def resolve(self, class_):
586 return instrumentation.manager_of_class(class_)
588 class HoldInstanceEvents(_EventsHold.HoldEvents, InstanceEvents):
589 pass
591 dispatch = event.dispatcher(HoldInstanceEvents)
594class MapperEvents(event.Events):
595 """Define events specific to mappings.
597 e.g.::
599 from sqlalchemy import event
601 def my_before_insert_listener(mapper, connection, target):
602 # execute a stored procedure upon INSERT,
603 # apply the value to the row to be inserted
604 target.calculated_value = connection.scalar(
605 "select my_special_function(%d)"
606 % target.special_number)
608 # associate the listener function with SomeClass,
609 # to execute during the "before_insert" hook
610 event.listen(
611 SomeClass, 'before_insert', my_before_insert_listener)
613 Available targets include:
615 * mapped classes
616 * unmapped superclasses of mapped or to-be-mapped classes
617 (using the ``propagate=True`` flag)
618 * :class:`_orm.Mapper` objects
619 * the :class:`_orm.Mapper` class itself and the :func:`.mapper`
620 function indicate listening for all mappers.
622 Mapper events provide hooks into critical sections of the
623 mapper, including those related to object instrumentation,
624 object loading, and object persistence. In particular, the
625 persistence methods :meth:`~.MapperEvents.before_insert`,
626 and :meth:`~.MapperEvents.before_update` are popular
627 places to augment the state being persisted - however, these
628 methods operate with several significant restrictions. The
629 user is encouraged to evaluate the
630 :meth:`.SessionEvents.before_flush` and
631 :meth:`.SessionEvents.after_flush` methods as more
632 flexible and user-friendly hooks in which to apply
633 additional database state during a flush.
635 When using :class:`.MapperEvents`, several modifiers are
636 available to the :func:`.event.listen` function.
638 :param propagate=False: When True, the event listener should
639 be applied to all inheriting mappers and/or the mappers of
640 inheriting classes, as well as any
641 mapper which is the target of this listener.
642 :param raw=False: When True, the "target" argument passed
643 to applicable event listener functions will be the
644 instance's :class:`.InstanceState` management
645 object, rather than the mapped instance itself.
646 :param retval=False: when True, the user-defined event function
647 must have a return value, the purpose of which is either to
648 control subsequent event propagation, or to otherwise alter
649 the operation in progress by the mapper. Possible return
650 values are:
652 * ``sqlalchemy.orm.interfaces.EXT_CONTINUE`` - continue event
653 processing normally.
654 * ``sqlalchemy.orm.interfaces.EXT_STOP`` - cancel all subsequent
655 event handlers in the chain.
656 * other values - the return value specified by specific listeners.
658 """
660 _target_class_doc = "SomeClass"
661 _dispatch_target = mapperlib.Mapper
663 @classmethod
664 def _new_mapper_instance(cls, class_, mapper):
665 _MapperEventsHold.populate(class_, mapper)
667 @classmethod
668 @util.dependencies("sqlalchemy.orm")
669 def _accept_with(cls, orm, target):
670 if target is orm.mapper:
671 return mapperlib.Mapper
672 elif isinstance(target, type):
673 if issubclass(target, mapperlib.Mapper):
674 return target
675 else:
676 mapper = _mapper_or_none(target)
677 if mapper is not None:
678 return mapper
679 else:
680 return _MapperEventsHold(target)
681 else:
682 return target
684 @classmethod
685 def _listen(
686 cls, event_key, raw=False, retval=False, propagate=False, **kw
687 ):
688 target, identifier, fn = (
689 event_key.dispatch_target,
690 event_key.identifier,
691 event_key._listen_fn,
692 )
694 if (
695 identifier in ("before_configured", "after_configured")
696 and target is not mapperlib.Mapper
697 ):
698 util.warn(
699 "'before_configured' and 'after_configured' ORM events "
700 "only invoke with the mapper() function or Mapper class "
701 "as the target."
702 )
704 if not raw or not retval:
705 if not raw:
706 meth = getattr(cls, identifier)
707 try:
708 target_index = (
709 inspect_getfullargspec(meth)[0].index("target") - 1
710 )
711 except ValueError:
712 target_index = None
714 def wrap(*arg, **kw):
715 if not raw and target_index is not None:
716 arg = list(arg)
717 arg[target_index] = arg[target_index].obj()
718 if not retval:
719 fn(*arg, **kw)
720 return interfaces.EXT_CONTINUE
721 else:
722 return fn(*arg, **kw)
724 event_key = event_key.with_wrapper(wrap)
726 if propagate:
727 for mapper in target.self_and_descendants:
728 event_key.with_dispatch_target(mapper).base_listen(
729 propagate=True, **kw
730 )
731 else:
732 event_key.base_listen(**kw)
734 @classmethod
735 def _clear(cls):
736 super(MapperEvents, cls)._clear()
737 _MapperEventsHold._clear()
739 def instrument_class(self, mapper, class_):
740 r"""Receive a class when the mapper is first constructed,
741 before instrumentation is applied to the mapped class.
743 This event is the earliest phase of mapper construction.
744 Most attributes of the mapper are not yet initialized.
746 This listener can either be applied to the :class:`_orm.Mapper`
747 class overall, or to any un-mapped class which serves as a base
748 for classes that will be mapped (using the ``propagate=True`` flag)::
750 Base = declarative_base()
752 @event.listens_for(Base, "instrument_class", propagate=True)
753 def on_new_class(mapper, cls_):
754 " ... "
756 :param mapper: the :class:`_orm.Mapper` which is the target
757 of this event.
758 :param class\_: the mapped class.
760 """
762 def before_mapper_configured(self, mapper, class_):
763 """Called right before a specific mapper is to be configured.
765 This event is intended to allow a specific mapper to be skipped during
766 the configure step, by returning the :attr:`.orm.interfaces.EXT_SKIP`
767 symbol which indicates to the :func:`.configure_mappers` call that this
768 particular mapper (or hierarchy of mappers, if ``propagate=True`` is
769 used) should be skipped in the current configuration run. When one or
770 more mappers are skipped, the he "new mappers" flag will remain set,
771 meaning the :func:`.configure_mappers` function will continue to be
772 called when mappers are used, to continue to try to configure all
773 available mappers.
775 In comparison to the other configure-level events,
776 :meth:`.MapperEvents.before_configured`,
777 :meth:`.MapperEvents.after_configured`, and
778 :meth:`.MapperEvents.mapper_configured`, the
779 :meth;`.MapperEvents.before_mapper_configured` event provides for a
780 meaningful return value when it is registered with the ``retval=True``
781 parameter.
783 .. versionadded:: 1.3
785 e.g.::
787 from sqlalchemy.orm import EXT_SKIP
789 Base = declarative_base()
791 DontConfigureBase = declarative_base()
793 @event.listens_for(
794 DontConfigureBase,
795 "before_mapper_configured", retval=True, propagate=True)
796 def dont_configure(mapper, cls):
797 return EXT_SKIP
800 .. seealso::
802 :meth:`.MapperEvents.before_configured`
804 :meth:`.MapperEvents.after_configured`
806 :meth:`.MapperEvents.mapper_configured`
808 """
810 def mapper_configured(self, mapper, class_):
811 r"""Called when a specific mapper has completed its own configuration
812 within the scope of the :func:`.configure_mappers` call.
814 The :meth:`.MapperEvents.mapper_configured` event is invoked
815 for each mapper that is encountered when the
816 :func:`_orm.configure_mappers` function proceeds through the current
817 list of not-yet-configured mappers.
818 :func:`_orm.configure_mappers` is typically invoked
819 automatically as mappings are first used, as well as each time
820 new mappers have been made available and new mapper use is
821 detected.
823 When the event is called, the mapper should be in its final
824 state, but **not including backrefs** that may be invoked from
825 other mappers; they might still be pending within the
826 configuration operation. Bidirectional relationships that
827 are instead configured via the
828 :paramref:`.orm.relationship.back_populates` argument
829 *will* be fully available, since this style of relationship does not
830 rely upon other possibly-not-configured mappers to know that they
831 exist.
833 For an event that is guaranteed to have **all** mappers ready
834 to go including backrefs that are defined only on other
835 mappings, use the :meth:`.MapperEvents.after_configured`
836 event; this event invokes only after all known mappings have been
837 fully configured.
839 The :meth:`.MapperEvents.mapper_configured` event, unlike
840 :meth:`.MapperEvents.before_configured` or
841 :meth:`.MapperEvents.after_configured`,
842 is called for each mapper/class individually, and the mapper is
843 passed to the event itself. It also is called exactly once for
844 a particular mapper. The event is therefore useful for
845 configurational steps that benefit from being invoked just once
846 on a specific mapper basis, which don't require that "backref"
847 configurations are necessarily ready yet.
849 :param mapper: the :class:`_orm.Mapper` which is the target
850 of this event.
851 :param class\_: the mapped class.
853 .. seealso::
855 :meth:`.MapperEvents.before_configured`
857 :meth:`.MapperEvents.after_configured`
859 :meth:`.MapperEvents.before_mapper_configured`
861 """
862 # TODO: need coverage for this event
864 def before_configured(self):
865 """Called before a series of mappers have been configured.
867 The :meth:`.MapperEvents.before_configured` event is invoked
868 each time the :func:`_orm.configure_mappers` function is
869 invoked, before the function has done any of its work.
870 :func:`_orm.configure_mappers` is typically invoked
871 automatically as mappings are first used, as well as each time
872 new mappers have been made available and new mapper use is
873 detected.
875 This event can **only** be applied to the :class:`_orm.Mapper` class
876 or :func:`.mapper` function, and not to individual mappings or
877 mapped classes. It is only invoked for all mappings as a whole::
879 from sqlalchemy.orm import mapper
881 @event.listens_for(mapper, "before_configured")
882 def go():
883 # ...
885 Contrast this event to :meth:`.MapperEvents.after_configured`,
886 which is invoked after the series of mappers has been configured,
887 as well as :meth:`.MapperEvents.before_mapper_configured`
888 and :meth:`.MapperEvents.mapper_configured`, which are both invoked
889 on a per-mapper basis.
891 Theoretically this event is called once per
892 application, but is actually called any time new mappers
893 are to be affected by a :func:`_orm.configure_mappers`
894 call. If new mappings are constructed after existing ones have
895 already been used, this event will likely be called again. To ensure
896 that a particular event is only called once and no further, the
897 ``once=True`` argument (new in 0.9.4) can be applied::
899 from sqlalchemy.orm import mapper
901 @event.listens_for(mapper, "before_configured", once=True)
902 def go():
903 # ...
906 .. versionadded:: 0.9.3
909 .. seealso::
911 :meth:`.MapperEvents.before_mapper_configured`
913 :meth:`.MapperEvents.mapper_configured`
915 :meth:`.MapperEvents.after_configured`
917 """
919 def after_configured(self):
920 """Called after a series of mappers have been configured.
922 The :meth:`.MapperEvents.after_configured` event is invoked
923 each time the :func:`_orm.configure_mappers` function is
924 invoked, after the function has completed its work.
925 :func:`_orm.configure_mappers` is typically invoked
926 automatically as mappings are first used, as well as each time
927 new mappers have been made available and new mapper use is
928 detected.
930 Contrast this event to the :meth:`.MapperEvents.mapper_configured`
931 event, which is called on a per-mapper basis while the configuration
932 operation proceeds; unlike that event, when this event is invoked,
933 all cross-configurations (e.g. backrefs) will also have been made
934 available for any mappers that were pending.
935 Also contrast to :meth:`.MapperEvents.before_configured`,
936 which is invoked before the series of mappers has been configured.
938 This event can **only** be applied to the :class:`_orm.Mapper` class
939 or :func:`.mapper` function, and not to individual mappings or
940 mapped classes. It is only invoked for all mappings as a whole::
942 from sqlalchemy.orm import mapper
944 @event.listens_for(mapper, "after_configured")
945 def go():
946 # ...
948 Theoretically this event is called once per
949 application, but is actually called any time new mappers
950 have been affected by a :func:`_orm.configure_mappers`
951 call. If new mappings are constructed after existing ones have
952 already been used, this event will likely be called again. To ensure
953 that a particular event is only called once and no further, the
954 ``once=True`` argument (new in 0.9.4) can be applied::
956 from sqlalchemy.orm import mapper
958 @event.listens_for(mapper, "after_configured", once=True)
959 def go():
960 # ...
962 .. seealso::
964 :meth:`.MapperEvents.before_mapper_configured`
966 :meth:`.MapperEvents.mapper_configured`
968 :meth:`.MapperEvents.before_configured`
970 """
972 def before_insert(self, mapper, connection, target):
973 """Receive an object instance before an INSERT statement
974 is emitted corresponding to that instance.
976 This event is used to modify local, non-object related
977 attributes on the instance before an INSERT occurs, as well
978 as to emit additional SQL statements on the given
979 connection.
981 The event is often called for a batch of objects of the
982 same class before their INSERT statements are emitted at
983 once in a later step. In the extremely rare case that
984 this is not desirable, the :func:`.mapper` can be
985 configured with ``batch=False``, which will cause
986 batches of instances to be broken up into individual
987 (and more poorly performing) event->persist->event
988 steps.
990 .. warning::
992 Mapper-level flush events only allow **very limited operations**,
993 on attributes local to the row being operated upon only,
994 as well as allowing any SQL to be emitted on the given
995 :class:`_engine.Connection`. **Please read fully** the notes
996 at :ref:`session_persistence_mapper` for guidelines on using
997 these methods; generally, the :meth:`.SessionEvents.before_flush`
998 method should be preferred for general on-flush changes.
1000 :param mapper: the :class:`_orm.Mapper` which is the target
1001 of this event.
1002 :param connection: the :class:`_engine.Connection` being used to
1003 emit INSERT statements for this instance. This
1004 provides a handle into the current transaction on the
1005 target database specific to this instance.
1006 :param target: the mapped instance being persisted. If
1007 the event is configured with ``raw=True``, this will
1008 instead be the :class:`.InstanceState` state-management
1009 object associated with the instance.
1010 :return: No return value is supported by this event.
1012 .. seealso::
1014 :ref:`session_persistence_events`
1016 """
1018 def after_insert(self, mapper, connection, target):
1019 """Receive an object instance after an INSERT statement
1020 is emitted corresponding to that instance.
1022 This event is used to modify in-Python-only
1023 state on the instance after an INSERT occurs, as well
1024 as to emit additional SQL statements on the given
1025 connection.
1027 The event is often called for a batch of objects of the
1028 same class after their INSERT statements have been
1029 emitted at once in a previous step. In the extremely
1030 rare case that this is not desirable, the
1031 :func:`.mapper` can be configured with ``batch=False``,
1032 which will cause batches of instances to be broken up
1033 into individual (and more poorly performing)
1034 event->persist->event steps.
1036 .. warning::
1038 Mapper-level flush events only allow **very limited operations**,
1039 on attributes local to the row being operated upon only,
1040 as well as allowing any SQL to be emitted on the given
1041 :class:`_engine.Connection`. **Please read fully** the notes
1042 at :ref:`session_persistence_mapper` for guidelines on using
1043 these methods; generally, the :meth:`.SessionEvents.before_flush`
1044 method should be preferred for general on-flush changes.
1046 :param mapper: the :class:`_orm.Mapper` which is the target
1047 of this event.
1048 :param connection: the :class:`_engine.Connection` being used to
1049 emit INSERT statements for this instance. This
1050 provides a handle into the current transaction on the
1051 target database specific to this instance.
1052 :param target: the mapped instance being persisted. If
1053 the event is configured with ``raw=True``, this will
1054 instead be the :class:`.InstanceState` state-management
1055 object associated with the instance.
1056 :return: No return value is supported by this event.
1058 .. seealso::
1060 :ref:`session_persistence_events`
1062 """
1064 def before_update(self, mapper, connection, target):
1065 """Receive an object instance before an UPDATE statement
1066 is emitted corresponding to that instance.
1068 This event is used to modify local, non-object related
1069 attributes on the instance before an UPDATE occurs, as well
1070 as to emit additional SQL statements on the given
1071 connection.
1073 This method is called for all instances that are
1074 marked as "dirty", *even those which have no net changes
1075 to their column-based attributes*. An object is marked
1076 as dirty when any of its column-based attributes have a
1077 "set attribute" operation called or when any of its
1078 collections are modified. If, at update time, no
1079 column-based attributes have any net changes, no UPDATE
1080 statement will be issued. This means that an instance
1081 being sent to :meth:`~.MapperEvents.before_update` is
1082 *not* a guarantee that an UPDATE statement will be
1083 issued, although you can affect the outcome here by
1084 modifying attributes so that a net change in value does
1085 exist.
1087 To detect if the column-based attributes on the object have net
1088 changes, and will therefore generate an UPDATE statement, use
1089 ``object_session(instance).is_modified(instance,
1090 include_collections=False)``.
1092 The event is often called for a batch of objects of the
1093 same class before their UPDATE statements are emitted at
1094 once in a later step. In the extremely rare case that
1095 this is not desirable, the :func:`.mapper` can be
1096 configured with ``batch=False``, which will cause
1097 batches of instances to be broken up into individual
1098 (and more poorly performing) event->persist->event
1099 steps.
1101 .. warning::
1103 Mapper-level flush events only allow **very limited operations**,
1104 on attributes local to the row being operated upon only,
1105 as well as allowing any SQL to be emitted on the given
1106 :class:`_engine.Connection`. **Please read fully** the notes
1107 at :ref:`session_persistence_mapper` for guidelines on using
1108 these methods; generally, the :meth:`.SessionEvents.before_flush`
1109 method should be preferred for general on-flush changes.
1111 :param mapper: the :class:`_orm.Mapper` which is the target
1112 of this event.
1113 :param connection: the :class:`_engine.Connection` being used to
1114 emit UPDATE statements for this instance. This
1115 provides a handle into the current transaction on the
1116 target database specific to this instance.
1117 :param target: the mapped instance being persisted. If
1118 the event is configured with ``raw=True``, this will
1119 instead be the :class:`.InstanceState` state-management
1120 object associated with the instance.
1121 :return: No return value is supported by this event.
1123 .. seealso::
1125 :ref:`session_persistence_events`
1127 """
1129 def after_update(self, mapper, connection, target):
1130 """Receive an object instance after an UPDATE statement
1131 is emitted corresponding to that instance.
1133 This event is used to modify in-Python-only
1134 state on the instance after an UPDATE occurs, as well
1135 as to emit additional SQL statements on the given
1136 connection.
1138 This method is called for all instances that are
1139 marked as "dirty", *even those which have no net changes
1140 to their column-based attributes*, and for which
1141 no UPDATE statement has proceeded. An object is marked
1142 as dirty when any of its column-based attributes have a
1143 "set attribute" operation called or when any of its
1144 collections are modified. If, at update time, no
1145 column-based attributes have any net changes, no UPDATE
1146 statement will be issued. This means that an instance
1147 being sent to :meth:`~.MapperEvents.after_update` is
1148 *not* a guarantee that an UPDATE statement has been
1149 issued.
1151 To detect if the column-based attributes on the object have net
1152 changes, and therefore resulted in an UPDATE statement, use
1153 ``object_session(instance).is_modified(instance,
1154 include_collections=False)``.
1156 The event is often called for a batch of objects of the
1157 same class after their UPDATE statements have been emitted at
1158 once in a previous step. In the extremely rare case that
1159 this is not desirable, the :func:`.mapper` can be
1160 configured with ``batch=False``, which will cause
1161 batches of instances to be broken up into individual
1162 (and more poorly performing) event->persist->event
1163 steps.
1165 .. warning::
1167 Mapper-level flush events only allow **very limited operations**,
1168 on attributes local to the row being operated upon only,
1169 as well as allowing any SQL to be emitted on the given
1170 :class:`_engine.Connection`. **Please read fully** the notes
1171 at :ref:`session_persistence_mapper` for guidelines on using
1172 these methods; generally, the :meth:`.SessionEvents.before_flush`
1173 method should be preferred for general on-flush changes.
1175 :param mapper: the :class:`_orm.Mapper` which is the target
1176 of this event.
1177 :param connection: the :class:`_engine.Connection` being used to
1178 emit UPDATE statements for this instance. This
1179 provides a handle into the current transaction on the
1180 target database specific to this instance.
1181 :param target: the mapped instance being persisted. If
1182 the event is configured with ``raw=True``, this will
1183 instead be the :class:`.InstanceState` state-management
1184 object associated with the instance.
1185 :return: No return value is supported by this event.
1187 .. seealso::
1189 :ref:`session_persistence_events`
1191 """
1193 def before_delete(self, mapper, connection, target):
1194 """Receive an object instance before a DELETE statement
1195 is emitted corresponding to that instance.
1197 This event is used to emit additional SQL statements on
1198 the given connection as well as to perform application
1199 specific bookkeeping related to a deletion event.
1201 The event is often called for a batch of objects of the
1202 same class before their DELETE statements are emitted at
1203 once in a later step.
1205 .. warning::
1207 Mapper-level flush events only allow **very limited operations**,
1208 on attributes local to the row being operated upon only,
1209 as well as allowing any SQL to be emitted on the given
1210 :class:`_engine.Connection`. **Please read fully** the notes
1211 at :ref:`session_persistence_mapper` for guidelines on using
1212 these methods; generally, the :meth:`.SessionEvents.before_flush`
1213 method should be preferred for general on-flush changes.
1215 :param mapper: the :class:`_orm.Mapper` which is the target
1216 of this event.
1217 :param connection: the :class:`_engine.Connection` being used to
1218 emit DELETE statements for this instance. This
1219 provides a handle into the current transaction on the
1220 target database specific to this instance.
1221 :param target: the mapped instance being deleted. If
1222 the event is configured with ``raw=True``, this will
1223 instead be the :class:`.InstanceState` state-management
1224 object associated with the instance.
1225 :return: No return value is supported by this event.
1227 .. seealso::
1229 :ref:`session_persistence_events`
1231 """
1233 def after_delete(self, mapper, connection, target):
1234 """Receive an object instance after a DELETE statement
1235 has been emitted corresponding to that instance.
1237 This event is used to emit additional SQL statements on
1238 the given connection as well as to perform application
1239 specific bookkeeping related to a deletion event.
1241 The event is often called for a batch of objects of the
1242 same class after their DELETE statements have been emitted at
1243 once in a previous step.
1245 .. warning::
1247 Mapper-level flush events only allow **very limited operations**,
1248 on attributes local to the row being operated upon only,
1249 as well as allowing any SQL to be emitted on the given
1250 :class:`_engine.Connection`. **Please read fully** the notes
1251 at :ref:`session_persistence_mapper` for guidelines on using
1252 these methods; generally, the :meth:`.SessionEvents.before_flush`
1253 method should be preferred for general on-flush changes.
1255 :param mapper: the :class:`_orm.Mapper` which is the target
1256 of this event.
1257 :param connection: the :class:`_engine.Connection` being used to
1258 emit DELETE statements for this instance. This
1259 provides a handle into the current transaction on the
1260 target database specific to this instance.
1261 :param target: the mapped instance being deleted. If
1262 the event is configured with ``raw=True``, this will
1263 instead be the :class:`.InstanceState` state-management
1264 object associated with the instance.
1265 :return: No return value is supported by this event.
1267 .. seealso::
1269 :ref:`session_persistence_events`
1271 """
1274class _MapperEventsHold(_EventsHold):
1275 all_holds = weakref.WeakKeyDictionary()
1277 def resolve(self, class_):
1278 return _mapper_or_none(class_)
1280 class HoldMapperEvents(_EventsHold.HoldEvents, MapperEvents):
1281 pass
1283 dispatch = event.dispatcher(HoldMapperEvents)
1286_sessionevents_lifecycle_event_names = set()
1289class SessionEvents(event.Events):
1290 """Define events specific to :class:`.Session` lifecycle.
1292 e.g.::
1294 from sqlalchemy import event
1295 from sqlalchemy.orm import sessionmaker
1297 def my_before_commit(session):
1298 print("before commit!")
1300 Session = sessionmaker()
1302 event.listen(Session, "before_commit", my_before_commit)
1304 The :func:`~.event.listen` function will accept
1305 :class:`.Session` objects as well as the return result
1306 of :class:`~.sessionmaker()` and :class:`~.scoped_session()`.
1308 Additionally, it accepts the :class:`.Session` class which
1309 will apply listeners to all :class:`.Session` instances
1310 globally.
1312 :param raw=False: When True, the "target" argument passed
1313 to applicable event listener functions that work on individual
1314 objects will be the instance's :class:`.InstanceState` management
1315 object, rather than the mapped instance itself.
1317 .. versionadded:: 1.3.14
1319 :param restore_load_context=False: Applies to the
1320 :meth:`.SessionEvents.loaded_as_persistent` event. Restores the loader
1321 context of the object when the event hook is complete, so that ongoing
1322 eager load operations continue to target the object appropriately. A
1323 warning is emitted if the object is moved to a new loader context from
1324 within this event if this flag is not set.
1326 .. versionadded:: 1.3.14
1328 """
1330 _target_class_doc = "SomeSessionOrFactory"
1332 _dispatch_target = Session
1334 def _lifecycle_event(fn):
1335 _sessionevents_lifecycle_event_names.add(fn.__name__)
1336 return fn
1338 @classmethod
1339 def _accept_with(cls, target):
1340 if isinstance(target, scoped_session):
1342 target = target.session_factory
1343 if not isinstance(target, sessionmaker) and (
1344 not isinstance(target, type) or not issubclass(target, Session)
1345 ):
1346 raise exc.ArgumentError(
1347 "Session event listen on a scoped_session "
1348 "requires that its creation callable "
1349 "is associated with the Session class."
1350 )
1352 if isinstance(target, sessionmaker):
1353 return target.class_
1354 elif isinstance(target, type):
1355 if issubclass(target, scoped_session):
1356 return Session
1357 elif issubclass(target, Session):
1358 return target
1359 elif isinstance(target, Session):
1360 return target
1361 else:
1362 return None
1364 @classmethod
1365 def _listen(cls, event_key, raw=False, restore_load_context=False, **kw):
1366 is_instance_event = (
1367 event_key.identifier in _sessionevents_lifecycle_event_names
1368 )
1370 if is_instance_event:
1371 if not raw or restore_load_context:
1373 fn = event_key._listen_fn
1375 def wrap(session, state, *arg, **kw):
1376 if not raw:
1377 target = state.obj()
1378 if target is None:
1379 # existing behavior is that if the object is
1380 # garbage collected, no event is emitted
1381 return
1382 else:
1383 target = state
1384 if restore_load_context:
1385 runid = state.runid
1386 try:
1387 return fn(session, target, *arg, **kw)
1388 finally:
1389 if restore_load_context:
1390 state.runid = runid
1392 event_key = event_key.with_wrapper(wrap)
1394 event_key.base_listen(**kw)
1396 def after_transaction_create(self, session, transaction):
1397 """Execute when a new :class:`.SessionTransaction` is created.
1399 This event differs from :meth:`~.SessionEvents.after_begin`
1400 in that it occurs for each :class:`.SessionTransaction`
1401 overall, as opposed to when transactions are begun
1402 on individual database connections. It is also invoked
1403 for nested transactions and subtransactions, and is always
1404 matched by a corresponding
1405 :meth:`~.SessionEvents.after_transaction_end` event
1406 (assuming normal operation of the :class:`.Session`).
1408 :param session: the target :class:`.Session`.
1409 :param transaction: the target :class:`.SessionTransaction`.
1411 To detect if this is the outermost
1412 :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
1413 SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
1414 is ``None``::
1416 @event.listens_for(session, "after_transaction_create")
1417 def after_transaction_create(session, transaction):
1418 if transaction.parent is None:
1419 # work with top-level transaction
1421 To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
1422 :attr:`.SessionTransaction.nested` attribute::
1424 @event.listens_for(session, "after_transaction_create")
1425 def after_transaction_create(session, transaction):
1426 if transaction.nested:
1427 # work with SAVEPOINT transaction
1430 .. seealso::
1432 :class:`.SessionTransaction`
1434 :meth:`~.SessionEvents.after_transaction_end`
1436 """
1438 def after_transaction_end(self, session, transaction):
1439 """Execute when the span of a :class:`.SessionTransaction` ends.
1441 This event differs from :meth:`~.SessionEvents.after_commit`
1442 in that it corresponds to all :class:`.SessionTransaction`
1443 objects in use, including those for nested transactions
1444 and subtransactions, and is always matched by a corresponding
1445 :meth:`~.SessionEvents.after_transaction_create` event.
1447 :param session: the target :class:`.Session`.
1448 :param transaction: the target :class:`.SessionTransaction`.
1450 To detect if this is the outermost
1451 :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
1452 SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
1453 is ``None``::
1455 @event.listens_for(session, "after_transaction_create")
1456 def after_transaction_end(session, transaction):
1457 if transaction.parent is None:
1458 # work with top-level transaction
1460 To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
1461 :attr:`.SessionTransaction.nested` attribute::
1463 @event.listens_for(session, "after_transaction_create")
1464 def after_transaction_end(session, transaction):
1465 if transaction.nested:
1466 # work with SAVEPOINT transaction
1469 .. seealso::
1471 :class:`.SessionTransaction`
1473 :meth:`~.SessionEvents.after_transaction_create`
1475 """
1477 def before_commit(self, session):
1478 """Execute before commit is called.
1480 .. note::
1482 The :meth:`~.SessionEvents.before_commit` hook is *not* per-flush,
1483 that is, the :class:`.Session` can emit SQL to the database
1484 many times within the scope of a transaction.
1485 For interception of these events, use the
1486 :meth:`~.SessionEvents.before_flush`,
1487 :meth:`~.SessionEvents.after_flush`, or
1488 :meth:`~.SessionEvents.after_flush_postexec`
1489 events.
1491 :param session: The target :class:`.Session`.
1493 .. seealso::
1495 :meth:`~.SessionEvents.after_commit`
1497 :meth:`~.SessionEvents.after_begin`
1499 :meth:`~.SessionEvents.after_transaction_create`
1501 :meth:`~.SessionEvents.after_transaction_end`
1503 """
1505 def after_commit(self, session):
1506 """Execute after a commit has occurred.
1508 .. note::
1510 The :meth:`~.SessionEvents.after_commit` hook is *not* per-flush,
1511 that is, the :class:`.Session` can emit SQL to the database
1512 many times within the scope of a transaction.
1513 For interception of these events, use the
1514 :meth:`~.SessionEvents.before_flush`,
1515 :meth:`~.SessionEvents.after_flush`, or
1516 :meth:`~.SessionEvents.after_flush_postexec`
1517 events.
1519 .. note::
1521 The :class:`.Session` is not in an active transaction
1522 when the :meth:`~.SessionEvents.after_commit` event is invoked,
1523 and therefore can not emit SQL. To emit SQL corresponding to
1524 every transaction, use the :meth:`~.SessionEvents.before_commit`
1525 event.
1527 :param session: The target :class:`.Session`.
1529 .. seealso::
1531 :meth:`~.SessionEvents.before_commit`
1533 :meth:`~.SessionEvents.after_begin`
1535 :meth:`~.SessionEvents.after_transaction_create`
1537 :meth:`~.SessionEvents.after_transaction_end`
1539 """
1541 def after_rollback(self, session):
1542 """Execute after a real DBAPI rollback has occurred.
1544 Note that this event only fires when the *actual* rollback against
1545 the database occurs - it does *not* fire each time the
1546 :meth:`.Session.rollback` method is called, if the underlying
1547 DBAPI transaction has already been rolled back. In many
1548 cases, the :class:`.Session` will not be in
1549 an "active" state during this event, as the current
1550 transaction is not valid. To acquire a :class:`.Session`
1551 which is active after the outermost rollback has proceeded,
1552 use the :meth:`.SessionEvents.after_soft_rollback` event, checking the
1553 :attr:`.Session.is_active` flag.
1555 :param session: The target :class:`.Session`.
1557 """
1559 def after_soft_rollback(self, session, previous_transaction):
1560 """Execute after any rollback has occurred, including "soft"
1561 rollbacks that don't actually emit at the DBAPI level.
1563 This corresponds to both nested and outer rollbacks, i.e.
1564 the innermost rollback that calls the DBAPI's
1565 rollback() method, as well as the enclosing rollback
1566 calls that only pop themselves from the transaction stack.
1568 The given :class:`.Session` can be used to invoke SQL and
1569 :meth:`.Session.query` operations after an outermost rollback
1570 by first checking the :attr:`.Session.is_active` flag::
1572 @event.listens_for(Session, "after_soft_rollback")
1573 def do_something(session, previous_transaction):
1574 if session.is_active:
1575 session.execute("select * from some_table")
1577 :param session: The target :class:`.Session`.
1578 :param previous_transaction: The :class:`.SessionTransaction`
1579 transactional marker object which was just closed. The current
1580 :class:`.SessionTransaction` for the given :class:`.Session` is
1581 available via the :attr:`.Session.transaction` attribute.
1583 """
1585 def before_flush(self, session, flush_context, instances):
1586 """Execute before flush process has started.
1588 :param session: The target :class:`.Session`.
1589 :param flush_context: Internal :class:`.UOWTransaction` object
1590 which handles the details of the flush.
1591 :param instances: Usually ``None``, this is the collection of
1592 objects which can be passed to the :meth:`.Session.flush` method
1593 (note this usage is deprecated).
1595 .. seealso::
1597 :meth:`~.SessionEvents.after_flush`
1599 :meth:`~.SessionEvents.after_flush_postexec`
1601 :ref:`session_persistence_events`
1603 """
1605 def after_flush(self, session, flush_context):
1606 """Execute after flush has completed, but before commit has been
1607 called.
1609 Note that the session's state is still in pre-flush, i.e. 'new',
1610 'dirty', and 'deleted' lists still show pre-flush state as well
1611 as the history settings on instance attributes.
1613 .. warning:: This event runs after the :class:`.Session` has emitted
1614 SQL to modify the database, but **before** it has altered its
1615 internal state to reflect those changes, including that newly
1616 inserted objects are placed into the identity map. ORM operations
1617 emitted within this event such as loads of related items
1618 may produce new identity map entries that will immediately
1619 be replaced, sometimes causing confusing results. SQLAlchemy will
1620 emit a warning for this condition as of version 1.3.9.
1622 :param session: The target :class:`.Session`.
1623 :param flush_context: Internal :class:`.UOWTransaction` object
1624 which handles the details of the flush.
1626 .. seealso::
1628 :meth:`~.SessionEvents.before_flush`
1630 :meth:`~.SessionEvents.after_flush_postexec`
1632 :ref:`session_persistence_events`
1634 """
1636 def after_flush_postexec(self, session, flush_context):
1637 """Execute after flush has completed, and after the post-exec
1638 state occurs.
1640 This will be when the 'new', 'dirty', and 'deleted' lists are in
1641 their final state. An actual commit() may or may not have
1642 occurred, depending on whether or not the flush started its own
1643 transaction or participated in a larger transaction.
1645 :param session: The target :class:`.Session`.
1646 :param flush_context: Internal :class:`.UOWTransaction` object
1647 which handles the details of the flush.
1650 .. seealso::
1652 :meth:`~.SessionEvents.before_flush`
1654 :meth:`~.SessionEvents.after_flush`
1656 :ref:`session_persistence_events`
1658 """
1660 def after_begin(self, session, transaction, connection):
1661 """Execute after a transaction is begun on a connection
1663 :param session: The target :class:`.Session`.
1664 :param transaction: The :class:`.SessionTransaction`.
1665 :param connection: The :class:`_engine.Connection` object
1666 which will be used for SQL statements.
1668 .. seealso::
1670 :meth:`~.SessionEvents.before_commit`
1672 :meth:`~.SessionEvents.after_commit`
1674 :meth:`~.SessionEvents.after_transaction_create`
1676 :meth:`~.SessionEvents.after_transaction_end`
1678 """
1680 @_lifecycle_event
1681 def before_attach(self, session, instance):
1682 """Execute before an instance is attached to a session.
1684 This is called before an add, delete or merge causes
1685 the object to be part of the session.
1687 .. seealso::
1689 :meth:`~.SessionEvents.after_attach`
1691 :ref:`session_lifecycle_events`
1693 """
1695 @_lifecycle_event
1696 def after_attach(self, session, instance):
1697 """Execute after an instance is attached to a session.
1699 This is called after an add, delete or merge.
1701 .. note::
1703 As of 0.8, this event fires off *after* the item
1704 has been fully associated with the session, which is
1705 different than previous releases. For event
1706 handlers that require the object not yet
1707 be part of session state (such as handlers which
1708 may autoflush while the target object is not
1709 yet complete) consider the
1710 new :meth:`.before_attach` event.
1712 .. seealso::
1714 :meth:`~.SessionEvents.before_attach`
1716 :ref:`session_lifecycle_events`
1718 """
1720 @event._legacy_signature(
1721 "0.9",
1722 ["session", "query", "query_context", "result"],
1723 lambda update_context: (
1724 update_context.session,
1725 update_context.query,
1726 update_context.context,
1727 update_context.result,
1728 ),
1729 )
1730 def after_bulk_update(self, update_context):
1731 """Execute after a bulk update operation to the session.
1733 This is called as a result of the :meth:`_query.Query.update` method.
1735 :param update_context: an "update context" object which contains
1736 details about the update, including these attributes:
1738 * ``session`` - the :class:`.Session` involved
1739 * ``query`` -the :class:`_query.Query`
1740 object that this update operation
1741 was called upon.
1742 * ``values`` The "values" dictionary that was passed to
1743 :meth:`_query.Query.update`.
1744 * ``context`` The :class:`.QueryContext` object, corresponding
1745 to the invocation of an ORM query.
1746 * ``result`` the :class:`_engine.ResultProxy`
1747 returned as a result of the
1748 bulk UPDATE operation.
1750 .. seealso::
1752 :meth:`.QueryEvents.before_compile_update`
1754 :meth:`.SessionEvents.after_bulk_delete`
1756 """
1758 @event._legacy_signature(
1759 "0.9",
1760 ["session", "query", "query_context", "result"],
1761 lambda delete_context: (
1762 delete_context.session,
1763 delete_context.query,
1764 delete_context.context,
1765 delete_context.result,
1766 ),
1767 )
1768 def after_bulk_delete(self, delete_context):
1769 """Execute after a bulk delete operation to the session.
1771 This is called as a result of the :meth:`_query.Query.delete` method.
1773 :param delete_context: a "delete context" object which contains
1774 details about the update, including these attributes:
1776 * ``session`` - the :class:`.Session` involved
1777 * ``query`` -the :class:`_query.Query`
1778 object that this update operation
1779 was called upon.
1780 * ``context`` The :class:`.QueryContext` object, corresponding
1781 to the invocation of an ORM query.
1782 * ``result`` the :class:`_engine.ResultProxy`
1783 returned as a result of the
1784 bulk DELETE operation.
1786 .. seealso::
1788 :meth:`.QueryEvents.before_compile_delete`
1790 :meth:`.SessionEvents.after_bulk_update`
1792 """
1794 @_lifecycle_event
1795 def transient_to_pending(self, session, instance):
1796 """Intercept the "transient to pending" transition for a specific object.
1798 This event is a specialization of the
1799 :meth:`.SessionEvents.after_attach` event which is only invoked
1800 for this specific transition. It is invoked typically during the
1801 :meth:`.Session.add` call.
1803 :param session: target :class:`.Session`
1805 :param instance: the ORM-mapped instance being operated upon.
1807 .. versionadded:: 1.1
1809 .. seealso::
1811 :ref:`session_lifecycle_events`
1813 """
1815 @_lifecycle_event
1816 def pending_to_transient(self, session, instance):
1817 """Intercept the "pending to transient" transition for a specific object.
1819 This less common transition occurs when an pending object that has
1820 not been flushed is evicted from the session; this can occur
1821 when the :meth:`.Session.rollback` method rolls back the transaction,
1822 or when the :meth:`.Session.expunge` method is used.
1824 :param session: target :class:`.Session`
1826 :param instance: the ORM-mapped instance being operated upon.
1828 .. versionadded:: 1.1
1830 .. seealso::
1832 :ref:`session_lifecycle_events`
1834 """
1836 @_lifecycle_event
1837 def persistent_to_transient(self, session, instance):
1838 """Intercept the "persistent to transient" transition for a specific object.
1840 This less common transition occurs when an pending object that has
1841 has been flushed is evicted from the session; this can occur
1842 when the :meth:`.Session.rollback` method rolls back the transaction.
1844 :param session: target :class:`.Session`
1846 :param instance: the ORM-mapped instance being operated upon.
1848 .. versionadded:: 1.1
1850 .. seealso::
1852 :ref:`session_lifecycle_events`
1854 """
1856 @_lifecycle_event
1857 def pending_to_persistent(self, session, instance):
1858 """Intercept the "pending to persistent"" transition for a specific object.
1860 This event is invoked within the flush process, and is
1861 similar to scanning the :attr:`.Session.new` collection within
1862 the :meth:`.SessionEvents.after_flush` event. However, in this
1863 case the object has already been moved to the persistent state
1864 when the event is called.
1866 :param session: target :class:`.Session`
1868 :param instance: the ORM-mapped instance being operated upon.
1870 .. versionadded:: 1.1
1872 .. seealso::
1874 :ref:`session_lifecycle_events`
1876 """
1878 @_lifecycle_event
1879 def detached_to_persistent(self, session, instance):
1880 """Intercept the "detached to persistent" transition for a specific object.
1882 This event is a specialization of the
1883 :meth:`.SessionEvents.after_attach` event which is only invoked
1884 for this specific transition. It is invoked typically during the
1885 :meth:`.Session.add` call, as well as during the
1886 :meth:`.Session.delete` call if the object was not previously
1887 associated with the
1888 :class:`.Session` (note that an object marked as "deleted" remains
1889 in the "persistent" state until the flush proceeds).
1891 .. note::
1893 If the object becomes persistent as part of a call to
1894 :meth:`.Session.delete`, the object is **not** yet marked as
1895 deleted when this event is called. To detect deleted objects,
1896 check the ``deleted`` flag sent to the
1897 :meth:`.SessionEvents.persistent_to_detached` to event after the
1898 flush proceeds, or check the :attr:`.Session.deleted` collection
1899 within the :meth:`.SessionEvents.before_flush` event if deleted
1900 objects need to be intercepted before the flush.
1902 :param session: target :class:`.Session`
1904 :param instance: the ORM-mapped instance being operated upon.
1906 .. versionadded:: 1.1
1908 .. seealso::
1910 :ref:`session_lifecycle_events`
1912 """
1914 @_lifecycle_event
1915 def loaded_as_persistent(self, session, instance):
1916 """Intercept the "loaded as persistent" transition for a specific object.
1918 This event is invoked within the ORM loading process, and is invoked
1919 very similarly to the :meth:`.InstanceEvents.load` event. However,
1920 the event here is linkable to a :class:`.Session` class or instance,
1921 rather than to a mapper or class hierarchy, and integrates
1922 with the other session lifecycle events smoothly. The object
1923 is guaranteed to be present in the session's identity map when
1924 this event is called.
1926 .. note:: This event is invoked within the loader process before
1927 eager loaders may have been completed, and the object's state may
1928 not be complete. Additionally, invoking row-level refresh
1929 operations on the object will place the object into a new loader
1930 context, interfering with the existing load context. See the note
1931 on :meth:`.InstanceEvents.load` for background on making use of the
1932 :paramref:`.SessionEvents.restore_load_context` parameter, which
1933 works in the same manner as that of
1934 :paramref:`.InstanceEvents.restore_load_context`, in order to
1935 resolve this scenario.
1937 :param session: target :class:`.Session`
1939 :param instance: the ORM-mapped instance being operated upon.
1941 .. versionadded:: 1.1
1943 .. seealso::
1945 :ref:`session_lifecycle_events`
1947 """
1949 @_lifecycle_event
1950 def persistent_to_deleted(self, session, instance):
1951 """Intercept the "persistent to deleted" transition for a specific object.
1953 This event is invoked when a persistent object's identity
1954 is deleted from the database within a flush, however the object
1955 still remains associated with the :class:`.Session` until the
1956 transaction completes.
1958 If the transaction is rolled back, the object moves again
1959 to the persistent state, and the
1960 :meth:`.SessionEvents.deleted_to_persistent` event is called.
1961 If the transaction is committed, the object becomes detached,
1962 which will emit the :meth:`.SessionEvents.deleted_to_detached`
1963 event.
1965 Note that while the :meth:`.Session.delete` method is the primary
1966 public interface to mark an object as deleted, many objects
1967 get deleted due to cascade rules, which are not always determined
1968 until flush time. Therefore, there's no way to catch
1969 every object that will be deleted until the flush has proceeded.
1970 the :meth:`.SessionEvents.persistent_to_deleted` event is therefore
1971 invoked at the end of a flush.
1973 .. versionadded:: 1.1
1975 .. seealso::
1977 :ref:`session_lifecycle_events`
1979 """
1981 @_lifecycle_event
1982 def deleted_to_persistent(self, session, instance):
1983 """Intercept the "deleted to persistent" transition for a specific object.
1985 This transition occurs only when an object that's been deleted
1986 successfully in a flush is restored due to a call to
1987 :meth:`.Session.rollback`. The event is not called under
1988 any other circumstances.
1990 .. versionadded:: 1.1
1992 .. seealso::
1994 :ref:`session_lifecycle_events`
1996 """
1998 @_lifecycle_event
1999 def deleted_to_detached(self, session, instance):
2000 """Intercept the "deleted to detached" transition for a specific object.
2002 This event is invoked when a deleted object is evicted
2003 from the session. The typical case when this occurs is when
2004 the transaction for a :class:`.Session` in which the object
2005 was deleted is committed; the object moves from the deleted
2006 state to the detached state.
2008 It is also invoked for objects that were deleted in a flush
2009 when the :meth:`.Session.expunge_all` or :meth:`.Session.close`
2010 events are called, as well as if the object is individually
2011 expunged from its deleted state via :meth:`.Session.expunge`.
2013 .. versionadded:: 1.1
2015 .. seealso::
2017 :ref:`session_lifecycle_events`
2019 """
2021 @_lifecycle_event
2022 def persistent_to_detached(self, session, instance):
2023 """Intercept the "persistent to detached" transition for a specific object.
2025 This event is invoked when a persistent object is evicted
2026 from the session. There are many conditions that cause this
2027 to happen, including:
2029 * using a method such as :meth:`.Session.expunge`
2030 or :meth:`.Session.close`
2032 * Calling the :meth:`.Session.rollback` method, when the object
2033 was part of an INSERT statement for that session's transaction
2036 :param session: target :class:`.Session`
2038 :param instance: the ORM-mapped instance being operated upon.
2040 :param deleted: boolean. If True, indicates this object moved
2041 to the detached state because it was marked as deleted and flushed.
2044 .. versionadded:: 1.1
2046 .. seealso::
2048 :ref:`session_lifecycle_events`
2050 """
2053class AttributeEvents(event.Events):
2054 r"""Define events for object attributes.
2056 These are typically defined on the class-bound descriptor for the
2057 target class.
2059 e.g.::
2061 from sqlalchemy import event
2063 @event.listens_for(MyClass.collection, 'append', propagate=True)
2064 def my_append_listener(target, value, initiator):
2065 print("received append event for target: %s" % target)
2068 Listeners have the option to return a possibly modified version of the
2069 value, when the :paramref:`.AttributeEvents.retval` flag is passed to
2070 :func:`.event.listen` or :func:`.event.listens_for`::
2072 def validate_phone(target, value, oldvalue, initiator):
2073 "Strip non-numeric characters from a phone number"
2075 return re.sub(r'\D', '', value)
2077 # setup listener on UserContact.phone attribute, instructing
2078 # it to use the return value
2079 listen(UserContact.phone, 'set', validate_phone, retval=True)
2081 A validation function like the above can also raise an exception
2082 such as :exc:`ValueError` to halt the operation.
2084 The :paramref:`.AttributeEvents.propagate` flag is also important when
2085 applying listeners to mapped classes that also have mapped subclasses,
2086 as when using mapper inheritance patterns::
2089 @event.listens_for(MySuperClass.attr, 'set', propagate=True)
2090 def receive_set(target, value, initiator):
2091 print("value set: %s" % target)
2093 The full list of modifiers available to the :func:`.event.listen`
2094 and :func:`.event.listens_for` functions are below.
2096 :param active_history=False: When True, indicates that the
2097 "set" event would like to receive the "old" value being
2098 replaced unconditionally, even if this requires firing off
2099 database loads. Note that ``active_history`` can also be
2100 set directly via :func:`.column_property` and
2101 :func:`_orm.relationship`.
2103 :param propagate=False: When True, the listener function will
2104 be established not just for the class attribute given, but
2105 for attributes of the same name on all current subclasses
2106 of that class, as well as all future subclasses of that
2107 class, using an additional listener that listens for
2108 instrumentation events.
2109 :param raw=False: When True, the "target" argument to the
2110 event will be the :class:`.InstanceState` management
2111 object, rather than the mapped instance itself.
2112 :param retval=False: when True, the user-defined event
2113 listening must return the "value" argument from the
2114 function. This gives the listening function the opportunity
2115 to change the value that is ultimately used for a "set"
2116 or "append" event.
2118 """
2120 _target_class_doc = "SomeClass.some_attribute"
2121 _dispatch_target = QueryableAttribute
2123 @staticmethod
2124 def _set_dispatch(cls, dispatch_cls):
2125 dispatch = event.Events._set_dispatch(cls, dispatch_cls)
2126 dispatch_cls._active_history = False
2127 return dispatch
2129 @classmethod
2130 def _accept_with(cls, target):
2131 # TODO: coverage
2132 if isinstance(target, interfaces.MapperProperty):
2133 return getattr(target.parent.class_, target.key)
2134 else:
2135 return target
2137 @classmethod
2138 def _listen(
2139 cls,
2140 event_key,
2141 active_history=False,
2142 raw=False,
2143 retval=False,
2144 propagate=False,
2145 ):
2147 target, fn = event_key.dispatch_target, event_key._listen_fn
2149 if active_history:
2150 target.dispatch._active_history = True
2152 if not raw or not retval:
2154 def wrap(target, *arg):
2155 if not raw:
2156 target = target.obj()
2157 if not retval:
2158 if arg:
2159 value = arg[0]
2160 else:
2161 value = None
2162 fn(target, *arg)
2163 return value
2164 else:
2165 return fn(target, *arg)
2167 event_key = event_key.with_wrapper(wrap)
2169 event_key.base_listen(propagate=propagate)
2171 if propagate:
2172 manager = instrumentation.manager_of_class(target.class_)
2174 for mgr in manager.subclass_managers(True):
2175 event_key.with_dispatch_target(mgr[target.key]).base_listen(
2176 propagate=True
2177 )
2178 if active_history:
2179 mgr[target.key].dispatch._active_history = True
2181 def append(self, target, value, initiator):
2182 """Receive a collection append event.
2184 The append event is invoked for each element as it is appended
2185 to the collection. This occurs for single-item appends as well
2186 as for a "bulk replace" operation.
2188 :param target: the object instance receiving the event.
2189 If the listener is registered with ``raw=True``, this will
2190 be the :class:`.InstanceState` object.
2191 :param value: the value being appended. If this listener
2192 is registered with ``retval=True``, the listener
2193 function must return this value, or a new value which
2194 replaces it.
2195 :param initiator: An instance of :class:`.attributes.Event`
2196 representing the initiation of the event. May be modified
2197 from its original value by backref handlers in order to control
2198 chained event propagation, as well as be inspected for information
2199 about the source of the event.
2200 :return: if the event was registered with ``retval=True``,
2201 the given value, or a new effective value, should be returned.
2203 .. seealso::
2205 :class:`.AttributeEvents` - background on listener options such
2206 as propagation to subclasses.
2208 :meth:`.AttributeEvents.bulk_replace`
2210 """
2212 def bulk_replace(self, target, values, initiator):
2213 """Receive a collection 'bulk replace' event.
2215 This event is invoked for a sequence of values as they are incoming
2216 to a bulk collection set operation, which can be
2217 modified in place before the values are treated as ORM objects.
2218 This is an "early hook" that runs before the bulk replace routine
2219 attempts to reconcile which objects are already present in the
2220 collection and which are being removed by the net replace operation.
2222 It is typical that this method be combined with use of the
2223 :meth:`.AttributeEvents.append` event. When using both of these
2224 events, note that a bulk replace operation will invoke
2225 the :meth:`.AttributeEvents.append` event for all new items,
2226 even after :meth:`.AttributeEvents.bulk_replace` has been invoked
2227 for the collection as a whole. In order to determine if an
2228 :meth:`.AttributeEvents.append` event is part of a bulk replace,
2229 use the symbol :attr:`~.attributes.OP_BULK_REPLACE` to test the
2230 incoming initiator::
2232 from sqlalchemy.orm.attributes import OP_BULK_REPLACE
2234 @event.listens_for(SomeObject.collection, "bulk_replace")
2235 def process_collection(target, values, initiator):
2236 values[:] = [_make_value(value) for value in values]
2238 @event.listens_for(SomeObject.collection, "append", retval=True)
2239 def process_collection(target, value, initiator):
2240 # make sure bulk_replace didn't already do it
2241 if initiator is None or initiator.op is not OP_BULK_REPLACE:
2242 return _make_value(value)
2243 else:
2244 return value
2246 .. versionadded:: 1.2
2248 :param target: the object instance receiving the event.
2249 If the listener is registered with ``raw=True``, this will
2250 be the :class:`.InstanceState` object.
2251 :param value: a sequence (e.g. a list) of the values being set. The
2252 handler can modify this list in place.
2253 :param initiator: An instance of :class:`.attributes.Event`
2254 representing the initiation of the event.
2256 .. seealso::
2258 :class:`.AttributeEvents` - background on listener options such
2259 as propagation to subclasses.
2262 """
2264 def remove(self, target, value, initiator):
2265 """Receive a collection remove event.
2267 :param target: the object instance receiving the event.
2268 If the listener is registered with ``raw=True``, this will
2269 be the :class:`.InstanceState` object.
2270 :param value: the value being removed.
2271 :param initiator: An instance of :class:`.attributes.Event`
2272 representing the initiation of the event. May be modified
2273 from its original value by backref handlers in order to control
2274 chained event propagation.
2276 .. versionchanged:: 0.9.0 the ``initiator`` argument is now
2277 passed as a :class:`.attributes.Event` object, and may be
2278 modified by backref handlers within a chain of backref-linked
2279 events.
2281 :return: No return value is defined for this event.
2284 .. seealso::
2286 :class:`.AttributeEvents` - background on listener options such
2287 as propagation to subclasses.
2289 """
2291 def set(self, target, value, oldvalue, initiator):
2292 """Receive a scalar set event.
2294 :param target: the object instance receiving the event.
2295 If the listener is registered with ``raw=True``, this will
2296 be the :class:`.InstanceState` object.
2297 :param value: the value being set. If this listener
2298 is registered with ``retval=True``, the listener
2299 function must return this value, or a new value which
2300 replaces it.
2301 :param oldvalue: the previous value being replaced. This
2302 may also be the symbol ``NEVER_SET`` or ``NO_VALUE``.
2303 If the listener is registered with ``active_history=True``,
2304 the previous value of the attribute will be loaded from
2305 the database if the existing value is currently unloaded
2306 or expired.
2307 :param initiator: An instance of :class:`.attributes.Event`
2308 representing the initiation of the event. May be modified
2309 from its original value by backref handlers in order to control
2310 chained event propagation.
2312 .. versionchanged:: 0.9.0 the ``initiator`` argument is now
2313 passed as a :class:`.attributes.Event` object, and may be
2314 modified by backref handlers within a chain of backref-linked
2315 events.
2317 :return: if the event was registered with ``retval=True``,
2318 the given value, or a new effective value, should be returned.
2320 .. seealso::
2322 :class:`.AttributeEvents` - background on listener options such
2323 as propagation to subclasses.
2325 """
2327 def init_scalar(self, target, value, dict_):
2328 r"""Receive a scalar "init" event.
2330 This event is invoked when an uninitialized, unpersisted scalar
2331 attribute is accessed, e.g. read::
2334 x = my_object.some_attribute
2336 The ORM's default behavior when this occurs for an un-initialized
2337 attribute is to return the value ``None``; note this differs from
2338 Python's usual behavior of raising ``AttributeError``. The
2339 event here can be used to customize what value is actually returned,
2340 with the assumption that the event listener would be mirroring
2341 a default generator that is configured on the Core
2342 :class:`_schema.Column`
2343 object as well.
2345 Since a default generator on a :class:`_schema.Column`
2346 might also produce
2347 a changing value such as a timestamp, the
2348 :meth:`.AttributeEvents.init_scalar`
2349 event handler can also be used to **set** the newly returned value, so
2350 that a Core-level default generation function effectively fires off
2351 only once, but at the moment the attribute is accessed on the
2352 non-persisted object. Normally, no change to the object's state
2353 is made when an uninitialized attribute is accessed (much older
2354 SQLAlchemy versions did in fact change the object's state).
2356 If a default generator on a column returned a particular constant,
2357 a handler might be used as follows::
2359 SOME_CONSTANT = 3.1415926
2361 class MyClass(Base):
2362 # ...
2364 some_attribute = Column(Numeric, default=SOME_CONSTANT)
2366 @event.listens_for(
2367 MyClass.some_attribute, "init_scalar",
2368 retval=True, propagate=True)
2369 def _init_some_attribute(target, dict_, value):
2370 dict_['some_attribute'] = SOME_CONSTANT
2371 return SOME_CONSTANT
2373 Above, we initialize the attribute ``MyClass.some_attribute`` to the
2374 value of ``SOME_CONSTANT``. The above code includes the following
2375 features:
2377 * By setting the value ``SOME_CONSTANT`` in the given ``dict_``,
2378 we indicate that this value is to be persisted to the database.
2379 This supersedes the use of ``SOME_CONSTANT`` in the default generator
2380 for the :class:`_schema.Column`. The ``active_column_defaults.py``
2381 example given at :ref:`examples_instrumentation` illustrates using
2382 the same approach for a changing default, e.g. a timestamp
2383 generator. In this particular example, it is not strictly
2384 necessary to do this since ``SOME_CONSTANT`` would be part of the
2385 INSERT statement in either case.
2387 * By establishing the ``retval=True`` flag, the value we return
2388 from the function will be returned by the attribute getter.
2389 Without this flag, the event is assumed to be a passive observer
2390 and the return value of our function is ignored.
2392 * The ``propagate=True`` flag is significant if the mapped class
2393 includes inheriting subclasses, which would also make use of this
2394 event listener. Without this flag, an inheriting subclass will
2395 not use our event handler.
2397 In the above example, the attribute set event
2398 :meth:`.AttributeEvents.set` as well as the related validation feature
2399 provided by :obj:`_orm.validates` is **not** invoked when we apply our
2400 value to the given ``dict_``. To have these events to invoke in
2401 response to our newly generated value, apply the value to the given
2402 object as a normal attribute set operation::
2404 SOME_CONSTANT = 3.1415926
2406 @event.listens_for(
2407 MyClass.some_attribute, "init_scalar",
2408 retval=True, propagate=True)
2409 def _init_some_attribute(target, dict_, value):
2410 # will also fire off attribute set events
2411 target.some_attribute = SOME_CONSTANT
2412 return SOME_CONSTANT
2414 When multiple listeners are set up, the generation of the value
2415 is "chained" from one listener to the next by passing the value
2416 returned by the previous listener that specifies ``retval=True``
2417 as the ``value`` argument of the next listener.
2419 .. versionadded:: 1.1
2421 :param target: the object instance receiving the event.
2422 If the listener is registered with ``raw=True``, this will
2423 be the :class:`.InstanceState` object.
2424 :param value: the value that is to be returned before this event
2425 listener were invoked. This value begins as the value ``None``,
2426 however will be the return value of the previous event handler
2427 function if multiple listeners are present.
2428 :param dict\_: the attribute dictionary of this mapped object.
2429 This is normally the ``__dict__`` of the object, but in all cases
2430 represents the destination that the attribute system uses to get
2431 at the actual value of this attribute. Placing the value in this
2432 dictionary has the effect that the value will be used in the
2433 INSERT statement generated by the unit of work.
2436 .. seealso::
2438 :class:`.AttributeEvents` - background on listener options such
2439 as propagation to subclasses.
2441 :ref:`examples_instrumentation` - see the
2442 ``active_column_defaults.py`` example.
2444 """
2446 def init_collection(self, target, collection, collection_adapter):
2447 """Receive a 'collection init' event.
2449 This event is triggered for a collection-based attribute, when
2450 the initial "empty collection" is first generated for a blank
2451 attribute, as well as for when the collection is replaced with
2452 a new one, such as via a set event.
2454 E.g., given that ``User.addresses`` is a relationship-based
2455 collection, the event is triggered here::
2457 u1 = User()
2458 u1.addresses.append(a1) # <- new collection
2460 and also during replace operations::
2462 u1.addresses = [a2, a3] # <- new collection
2464 :param target: the object instance receiving the event.
2465 If the listener is registered with ``raw=True``, this will
2466 be the :class:`.InstanceState` object.
2467 :param collection: the new collection. This will always be generated
2468 from what was specified as
2469 :paramref:`_orm.relationship.collection_class`, and will always
2470 be empty.
2471 :param collection_adapter: the :class:`.CollectionAdapter` that will
2472 mediate internal access to the collection.
2474 .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection`
2475 and :meth:`.AttributeEvents.dispose_collection` events supersede
2476 the :class:`.orm.collection.linker` hook.
2478 .. seealso::
2480 :class:`.AttributeEvents` - background on listener options such
2481 as propagation to subclasses.
2483 """
2485 def dispose_collection(self, target, collection, collection_adapter):
2486 """Receive a 'collection dispose' event.
2488 This event is triggered for a collection-based attribute when
2489 a collection is replaced, that is::
2491 u1.addresses.append(a1)
2493 u1.addresses = [a2, a3] # <- old collection is disposed
2495 The old collection received will contain its previous contents.
2497 .. versionchanged:: 1.2 The collection passed to
2498 :meth:`.AttributeEvents.dispose_collection` will now have its
2499 contents before the dispose intact; previously, the collection
2500 would be empty.
2502 .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection`
2503 and :meth:`.AttributeEvents.dispose_collection` events supersede
2504 the :class:`.collection.linker` hook.
2506 .. seealso::
2508 :class:`.AttributeEvents` - background on listener options such
2509 as propagation to subclasses.
2511 """
2513 def modified(self, target, initiator):
2514 """Receive a 'modified' event.
2516 This event is triggered when the :func:`.attributes.flag_modified`
2517 function is used to trigger a modify event on an attribute without
2518 any specific value being set.
2520 .. versionadded:: 1.2
2522 :param target: the object instance receiving the event.
2523 If the listener is registered with ``raw=True``, this will
2524 be the :class:`.InstanceState` object.
2526 :param initiator: An instance of :class:`.attributes.Event`
2527 representing the initiation of the event.
2529 .. seealso::
2531 :class:`.AttributeEvents` - background on listener options such
2532 as propagation to subclasses.
2534 """
2537class QueryEvents(event.Events):
2538 """Represent events within the construction of a :class:`_query.Query`
2539 object.
2541 The events here are intended to be used with an as-yet-unreleased
2542 inspection system for :class:`_query.Query`. Some very basic operations
2543 are possible now, however the inspection system is intended to allow
2544 complex query manipulations to be automated.
2546 .. versionadded:: 1.0.0
2548 """
2550 _target_class_doc = "SomeQuery"
2551 _dispatch_target = Query
2553 def before_compile(self, query):
2554 """Receive the :class:`_query.Query`
2555 object before it is composed into a
2556 core :class:`_expression.Select` object.
2558 This event is intended to allow changes to the query given::
2560 @event.listens_for(Query, "before_compile", retval=True)
2561 def no_deleted(query):
2562 for desc in query.column_descriptions:
2563 if desc['type'] is User:
2564 entity = desc['entity']
2565 query = query.filter(entity.deleted == False)
2566 return query
2568 The event should normally be listened with the ``retval=True``
2569 parameter set, so that the modified query may be returned.
2571 The :meth:`.QueryEvents.before_compile` event by default
2572 will disallow "baked" queries from caching a query, if the event
2573 hook returns a new :class:`_query.Query` object.
2574 This affects both direct
2575 use of the baked query extension as well as its operation within
2576 lazy loaders and eager loaders for relationships. In order to
2577 re-establish the query being cached, apply the event adding the
2578 ``bake_ok`` flag::
2580 @event.listens_for(
2581 Query, "before_compile", retval=True, bake_ok=True)
2582 def my_event(query):
2583 for desc in query.column_descriptions:
2584 if desc['type'] is User:
2585 entity = desc['entity']
2586 query = query.filter(entity.deleted == False)
2587 return query
2589 When ``bake_ok`` is set to True, the event hook will only be invoked
2590 once, and not called for subsequent invocations of a particular query
2591 that is being cached.
2593 .. versionadded:: 1.3.11 - added the "bake_ok" flag to the
2594 :meth:`.QueryEvents.before_compile` event and disallowed caching via
2595 the "baked" extension from occurring for event handlers that
2596 return a new :class:`_query.Query` object if this flag is not set.
2598 .. seealso::
2600 :meth:`.QueryEvents.before_compile_update`
2602 :meth:`.QueryEvents.before_compile_delete`
2604 :ref:`baked_with_before_compile`
2606 """
2608 def before_compile_update(self, query, update_context):
2609 """Allow modifications to the :class:`_query.Query` object within
2610 :meth:`_query.Query.update`.
2612 Like the :meth:`.QueryEvents.before_compile` event, if the event
2613 is to be used to alter the :class:`_query.Query` object, it should
2614 be configured with ``retval=True``, and the modified
2615 :class:`_query.Query` object returned, as in ::
2617 @event.listens_for(Query, "before_compile_update", retval=True)
2618 def no_deleted(query, update_context):
2619 for desc in query.column_descriptions:
2620 if desc['type'] is User:
2621 entity = desc['entity']
2622 query = query.filter(entity.deleted == False)
2624 update_context.values['timestamp'] = datetime.utcnow()
2625 return query
2627 The ``.values`` dictionary of the "update context" object can also
2628 be modified in place as illustrated above.
2630 :param query: a :class:`_query.Query` instance; this is also
2631 the ``.query`` attribute of the given "update context"
2632 object.
2634 :param update_context: an "update context" object which is
2635 the same kind of object as described in
2636 :paramref:`.QueryEvents.after_bulk_update.update_context`.
2637 The object has a ``.values`` attribute in an UPDATE context which is
2638 the dictionary of parameters passed to :meth:`_query.Query.update`.
2639 This
2640 dictionary can be modified to alter the VALUES clause of the
2641 resulting UPDATE statement.
2643 .. versionadded:: 1.2.17
2645 .. seealso::
2647 :meth:`.QueryEvents.before_compile`
2649 :meth:`.QueryEvents.before_compile_delete`
2652 """
2654 def before_compile_delete(self, query, delete_context):
2655 """Allow modifications to the :class:`_query.Query` object within
2656 :meth:`_query.Query.delete`.
2658 Like the :meth:`.QueryEvents.before_compile` event, this event
2659 should be configured with ``retval=True``, and the modified
2660 :class:`_query.Query` object returned, as in ::
2662 @event.listens_for(Query, "before_compile_delete", retval=True)
2663 def no_deleted(query, delete_context):
2664 for desc in query.column_descriptions:
2665 if desc['type'] is User:
2666 entity = desc['entity']
2667 query = query.filter(entity.deleted == False)
2668 return query
2670 :param query: a :class:`_query.Query` instance; this is also
2671 the ``.query`` attribute of the given "delete context"
2672 object.
2674 :param delete_context: a "delete context" object which is
2675 the same kind of object as described in
2676 :paramref:`.QueryEvents.after_bulk_delete.delete_context`.
2678 .. versionadded:: 1.2.17
2680 .. seealso::
2682 :meth:`.QueryEvents.before_compile`
2684 :meth:`.QueryEvents.before_compile_update`
2687 """
2689 @classmethod
2690 def _listen(cls, event_key, retval=False, bake_ok=False, **kw):
2691 fn = event_key._listen_fn
2693 if not retval:
2695 def wrap(*arg, **kw):
2696 if not retval:
2697 query = arg[0]
2698 fn(*arg, **kw)
2699 return query
2700 else:
2701 return fn(*arg, **kw)
2703 event_key = event_key.with_wrapper(wrap)
2704 else:
2705 # don't assume we can apply an attribute to the callable
2706 def wrap(*arg, **kw):
2707 return fn(*arg, **kw)
2709 event_key = event_key.with_wrapper(wrap)
2711 wrap._bake_ok = bake_ok
2713 event_key.base_listen(**kw)