events.py 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893
  1. # orm/events.py
  2. # Copyright (C) 2005-2024 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: https://www.opensource.org/licenses/mit-license.php
  7. """ORM event interfaces.
  8. """
  9. import weakref
  10. from . import instrumentation
  11. from . import interfaces
  12. from . import mapperlib
  13. from .attributes import QueryableAttribute
  14. from .base import _mapper_or_none
  15. from .query import Query
  16. from .scoping import scoped_session
  17. from .session import Session
  18. from .session import sessionmaker
  19. from .. import event
  20. from .. import exc
  21. from .. import util
  22. from ..util.compat import inspect_getfullargspec
  23. class InstrumentationEvents(event.Events):
  24. """Events related to class instrumentation events.
  25. The listeners here support being established against
  26. any new style class, that is any object that is a subclass
  27. of 'type'. Events will then be fired off for events
  28. against that class. If the "propagate=True" flag is passed
  29. to event.listen(), the event will fire off for subclasses
  30. of that class as well.
  31. The Python ``type`` builtin is also accepted as a target,
  32. which when used has the effect of events being emitted
  33. for all classes.
  34. Note the "propagate" flag here is defaulted to ``True``,
  35. unlike the other class level events where it defaults
  36. to ``False``. This means that new subclasses will also
  37. be the subject of these events, when a listener
  38. is established on a superclass.
  39. """
  40. _target_class_doc = "SomeBaseClass"
  41. _dispatch_target = instrumentation.InstrumentationFactory
  42. @classmethod
  43. def _accept_with(cls, target):
  44. if isinstance(target, type):
  45. return _InstrumentationEventsHold(target)
  46. else:
  47. return None
  48. @classmethod
  49. def _listen(cls, event_key, propagate=True, **kw):
  50. target, identifier, fn = (
  51. event_key.dispatch_target,
  52. event_key.identifier,
  53. event_key._listen_fn,
  54. )
  55. def listen(target_cls, *arg):
  56. listen_cls = target()
  57. # if weakref were collected, however this is not something
  58. # that normally happens. it was occurring during test teardown
  59. # between mapper/registry/instrumentation_manager, however this
  60. # interaction was changed to not rely upon the event system.
  61. if listen_cls is None:
  62. return None
  63. if propagate and issubclass(target_cls, listen_cls):
  64. return fn(target_cls, *arg)
  65. elif not propagate and target_cls is listen_cls:
  66. return fn(target_cls, *arg)
  67. def remove(ref):
  68. key = event.registry._EventKey(
  69. None,
  70. identifier,
  71. listen,
  72. instrumentation._instrumentation_factory,
  73. )
  74. getattr(
  75. instrumentation._instrumentation_factory.dispatch, identifier
  76. ).remove(key)
  77. target = weakref.ref(target.class_, remove)
  78. event_key.with_dispatch_target(
  79. instrumentation._instrumentation_factory
  80. ).with_wrapper(listen).base_listen(**kw)
  81. @classmethod
  82. def _clear(cls):
  83. super(InstrumentationEvents, cls)._clear()
  84. instrumentation._instrumentation_factory.dispatch._clear()
  85. def class_instrument(self, cls):
  86. """Called after the given class is instrumented.
  87. To get at the :class:`.ClassManager`, use
  88. :func:`.manager_of_class`.
  89. """
  90. def class_uninstrument(self, cls):
  91. """Called before the given class is uninstrumented.
  92. To get at the :class:`.ClassManager`, use
  93. :func:`.manager_of_class`.
  94. """
  95. def attribute_instrument(self, cls, key, inst):
  96. """Called when an attribute is instrumented."""
  97. class _InstrumentationEventsHold(object):
  98. """temporary marker object used to transfer from _accept_with() to
  99. _listen() on the InstrumentationEvents class.
  100. """
  101. def __init__(self, class_):
  102. self.class_ = class_
  103. dispatch = event.dispatcher(InstrumentationEvents)
  104. class InstanceEvents(event.Events):
  105. """Define events specific to object lifecycle.
  106. e.g.::
  107. from sqlalchemy import event
  108. def my_load_listener(target, context):
  109. print("on load!")
  110. event.listen(SomeClass, 'load', my_load_listener)
  111. Available targets include:
  112. * mapped classes
  113. * unmapped superclasses of mapped or to-be-mapped classes
  114. (using the ``propagate=True`` flag)
  115. * :class:`_orm.Mapper` objects
  116. * the :class:`_orm.Mapper` class itself and the :func:`.mapper`
  117. function indicate listening for all mappers.
  118. Instance events are closely related to mapper events, but
  119. are more specific to the instance and its instrumentation,
  120. rather than its system of persistence.
  121. When using :class:`.InstanceEvents`, several modifiers are
  122. available to the :func:`.event.listen` function.
  123. :param propagate=False: When True, the event listener should
  124. be applied to all inheriting classes as well as the
  125. class which is the target of this listener.
  126. :param raw=False: When True, the "target" argument passed
  127. to applicable event listener functions will be the
  128. instance's :class:`.InstanceState` management
  129. object, rather than the mapped instance itself.
  130. :param restore_load_context=False: Applies to the
  131. :meth:`.InstanceEvents.load` and :meth:`.InstanceEvents.refresh`
  132. events. Restores the loader context of the object when the event
  133. hook is complete, so that ongoing eager load operations continue
  134. to target the object appropriately. A warning is emitted if the
  135. object is moved to a new loader context from within one of these
  136. events if this flag is not set.
  137. .. versionadded:: 1.3.14
  138. """
  139. _target_class_doc = "SomeClass"
  140. _dispatch_target = instrumentation.ClassManager
  141. @classmethod
  142. def _new_classmanager_instance(cls, class_, classmanager):
  143. _InstanceEventsHold.populate(class_, classmanager)
  144. @classmethod
  145. @util.preload_module("sqlalchemy.orm")
  146. def _accept_with(cls, target):
  147. orm = util.preloaded.orm
  148. if isinstance(target, instrumentation.ClassManager):
  149. return target
  150. elif isinstance(target, mapperlib.Mapper):
  151. return target.class_manager
  152. elif target is orm.mapper:
  153. return instrumentation.ClassManager
  154. elif isinstance(target, type):
  155. if issubclass(target, mapperlib.Mapper):
  156. return instrumentation.ClassManager
  157. else:
  158. manager = instrumentation.manager_of_class(target)
  159. if manager:
  160. return manager
  161. else:
  162. return _InstanceEventsHold(target)
  163. return None
  164. @classmethod
  165. def _listen(
  166. cls,
  167. event_key,
  168. raw=False,
  169. propagate=False,
  170. restore_load_context=False,
  171. **kw
  172. ):
  173. target, fn = (event_key.dispatch_target, event_key._listen_fn)
  174. if not raw or restore_load_context:
  175. def wrap(state, *arg, **kw):
  176. if not raw:
  177. target = state.obj()
  178. else:
  179. target = state
  180. if restore_load_context:
  181. runid = state.runid
  182. try:
  183. return fn(target, *arg, **kw)
  184. finally:
  185. if restore_load_context:
  186. state.runid = runid
  187. event_key = event_key.with_wrapper(wrap)
  188. event_key.base_listen(propagate=propagate, **kw)
  189. if propagate:
  190. for mgr in target.subclass_managers(True):
  191. event_key.with_dispatch_target(mgr).base_listen(propagate=True)
  192. @classmethod
  193. def _clear(cls):
  194. super(InstanceEvents, cls)._clear()
  195. _InstanceEventsHold._clear()
  196. def first_init(self, manager, cls):
  197. """Called when the first instance of a particular mapping is called.
  198. This event is called when the ``__init__`` method of a class
  199. is called the first time for that particular class. The event
  200. invokes before ``__init__`` actually proceeds as well as before
  201. the :meth:`.InstanceEvents.init` event is invoked.
  202. """
  203. def init(self, target, args, kwargs):
  204. """Receive an instance when its constructor is called.
  205. This method is only called during a userland construction of
  206. an object, in conjunction with the object's constructor, e.g.
  207. its ``__init__`` method. It is not called when an object is
  208. loaded from the database; see the :meth:`.InstanceEvents.load`
  209. event in order to intercept a database load.
  210. The event is called before the actual ``__init__`` constructor
  211. of the object is called. The ``kwargs`` dictionary may be
  212. modified in-place in order to affect what is passed to
  213. ``__init__``.
  214. :param target: the mapped instance. If
  215. the event is configured with ``raw=True``, this will
  216. instead be the :class:`.InstanceState` state-management
  217. object associated with the instance.
  218. :param args: positional arguments passed to the ``__init__`` method.
  219. This is passed as a tuple and is currently immutable.
  220. :param kwargs: keyword arguments passed to the ``__init__`` method.
  221. This structure *can* be altered in place.
  222. .. seealso::
  223. :meth:`.InstanceEvents.init_failure`
  224. :meth:`.InstanceEvents.load`
  225. """
  226. def init_failure(self, target, args, kwargs):
  227. """Receive an instance when its constructor has been called,
  228. and raised an exception.
  229. This method is only called during a userland construction of
  230. an object, in conjunction with the object's constructor, e.g.
  231. its ``__init__`` method. It is not called when an object is loaded
  232. from the database.
  233. The event is invoked after an exception raised by the ``__init__``
  234. method is caught. After the event
  235. is invoked, the original exception is re-raised outwards, so that
  236. the construction of the object still raises an exception. The
  237. actual exception and stack trace raised should be present in
  238. ``sys.exc_info()``.
  239. :param target: the mapped instance. If
  240. the event is configured with ``raw=True``, this will
  241. instead be the :class:`.InstanceState` state-management
  242. object associated with the instance.
  243. :param args: positional arguments that were passed to the ``__init__``
  244. method.
  245. :param kwargs: keyword arguments that were passed to the ``__init__``
  246. method.
  247. .. seealso::
  248. :meth:`.InstanceEvents.init`
  249. :meth:`.InstanceEvents.load`
  250. """
  251. def _sa_event_merge_wo_load(self, target, context):
  252. """receive an object instance after it was the subject of a merge()
  253. call, when load=False was passed.
  254. The target would be the already-loaded object in the Session which
  255. would have had its attributes overwritten by the incoming object. This
  256. overwrite operation does not use attribute events, instead just
  257. populating dict directly. Therefore the purpose of this event is so
  258. that extensions like sqlalchemy.ext.mutable know that object state has
  259. changed and incoming state needs to be set up for "parents" etc.
  260. This functionality is acceptable to be made public in a later release.
  261. .. versionadded:: 1.4.41
  262. """
  263. def load(self, target, context):
  264. """Receive an object instance after it has been created via
  265. ``__new__``, and after initial attribute population has
  266. occurred.
  267. This typically occurs when the instance is created based on
  268. incoming result rows, and is only called once for that
  269. instance's lifetime.
  270. .. warning::
  271. During a result-row load, this event is invoked when the
  272. first row received for this instance is processed. When using
  273. eager loading with collection-oriented attributes, the additional
  274. rows that are to be loaded / processed in order to load subsequent
  275. collection items have not occurred yet. This has the effect
  276. both that collections will not be fully loaded, as well as that
  277. if an operation occurs within this event handler that emits
  278. another database load operation for the object, the "loading
  279. context" for the object can change and interfere with the
  280. existing eager loaders still in progress.
  281. Examples of what can cause the "loading context" to change within
  282. the event handler include, but are not necessarily limited to:
  283. * accessing deferred attributes that weren't part of the row,
  284. will trigger an "undefer" operation and refresh the object
  285. * accessing attributes on a joined-inheritance subclass that
  286. weren't part of the row, will trigger a refresh operation.
  287. As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The
  288. :paramref:`.InstanceEvents.restore_load_context` option may be
  289. used on the event to prevent this warning; this will ensure that
  290. the existing loading context is maintained for the object after the
  291. event is called::
  292. @event.listens_for(
  293. SomeClass, "load", restore_load_context=True)
  294. def on_load(instance, context):
  295. instance.some_unloaded_attribute
  296. .. versionchanged:: 1.3.14 Added
  297. :paramref:`.InstanceEvents.restore_load_context`
  298. and :paramref:`.SessionEvents.restore_load_context` flags which
  299. apply to "on load" events, which will ensure that the loading
  300. context for an object is restored when the event hook is
  301. complete; a warning is emitted if the load context of the object
  302. changes without this flag being set.
  303. The :meth:`.InstanceEvents.load` event is also available in a
  304. class-method decorator format called :func:`_orm.reconstructor`.
  305. :param target: the mapped instance. If
  306. the event is configured with ``raw=True``, this will
  307. instead be the :class:`.InstanceState` state-management
  308. object associated with the instance.
  309. :param context: the :class:`.QueryContext` corresponding to the
  310. current :class:`_query.Query` in progress. This argument may be
  311. ``None`` if the load does not correspond to a :class:`_query.Query`,
  312. such as during :meth:`.Session.merge`.
  313. .. seealso::
  314. :meth:`.InstanceEvents.init`
  315. :meth:`.InstanceEvents.refresh`
  316. :meth:`.SessionEvents.loaded_as_persistent`
  317. :ref:`mapping_constructors`
  318. """
  319. def refresh(self, target, context, attrs):
  320. """Receive an object instance after one or more attributes have
  321. been refreshed from a query.
  322. Contrast this to the :meth:`.InstanceEvents.load` method, which
  323. is invoked when the object is first loaded from a query.
  324. .. note:: This event is invoked within the loader process before
  325. eager loaders may have been completed, and the object's state may
  326. not be complete. Additionally, invoking row-level refresh
  327. operations on the object will place the object into a new loader
  328. context, interfering with the existing load context. See the note
  329. on :meth:`.InstanceEvents.load` for background on making use of the
  330. :paramref:`.InstanceEvents.restore_load_context` parameter, in
  331. order to resolve this scenario.
  332. :param target: the mapped instance. If
  333. the event is configured with ``raw=True``, this will
  334. instead be the :class:`.InstanceState` state-management
  335. object associated with the instance.
  336. :param context: the :class:`.QueryContext` corresponding to the
  337. current :class:`_query.Query` in progress.
  338. :param attrs: sequence of attribute names which
  339. were populated, or None if all column-mapped, non-deferred
  340. attributes were populated.
  341. .. seealso::
  342. :meth:`.InstanceEvents.load`
  343. """
  344. def refresh_flush(self, target, flush_context, attrs):
  345. """Receive an object instance after one or more attributes that
  346. contain a column-level default or onupdate handler have been refreshed
  347. during persistence of the object's state.
  348. This event is the same as :meth:`.InstanceEvents.refresh` except
  349. it is invoked within the unit of work flush process, and includes
  350. only non-primary-key columns that have column level default or
  351. onupdate handlers, including Python callables as well as server side
  352. defaults and triggers which may be fetched via the RETURNING clause.
  353. .. note::
  354. While the :meth:`.InstanceEvents.refresh_flush` event is triggered
  355. for an object that was INSERTed as well as for an object that was
  356. UPDATEd, the event is geared primarily towards the UPDATE process;
  357. it is mostly an internal artifact that INSERT actions can also
  358. trigger this event, and note that **primary key columns for an
  359. INSERTed row are explicitly omitted** from this event. In order to
  360. intercept the newly INSERTed state of an object, the
  361. :meth:`.SessionEvents.pending_to_persistent` and
  362. :meth:`.MapperEvents.after_insert` are better choices.
  363. .. versionadded:: 1.0.5
  364. :param target: the mapped instance. If
  365. the event is configured with ``raw=True``, this will
  366. instead be the :class:`.InstanceState` state-management
  367. object associated with the instance.
  368. :param flush_context: Internal :class:`.UOWTransaction` object
  369. which handles the details of the flush.
  370. :param attrs: sequence of attribute names which
  371. were populated.
  372. .. seealso::
  373. :ref:`orm_server_defaults`
  374. :ref:`metadata_defaults_toplevel`
  375. """
  376. def expire(self, target, attrs):
  377. """Receive an object instance after its attributes or some subset
  378. have been expired.
  379. 'keys' is a list of attribute names. If None, the entire
  380. state was expired.
  381. :param target: the mapped instance. If
  382. the event is configured with ``raw=True``, this will
  383. instead be the :class:`.InstanceState` state-management
  384. object associated with the instance.
  385. :param attrs: sequence of attribute
  386. names which were expired, or None if all attributes were
  387. expired.
  388. """
  389. def pickle(self, target, state_dict):
  390. """Receive an object instance when its associated state is
  391. being pickled.
  392. :param target: the mapped instance. If
  393. the event is configured with ``raw=True``, this will
  394. instead be the :class:`.InstanceState` state-management
  395. object associated with the instance.
  396. :param state_dict: the dictionary returned by
  397. :class:`.InstanceState.__getstate__`, containing the state
  398. to be pickled.
  399. """
  400. def unpickle(self, target, state_dict):
  401. """Receive an object instance after its associated state has
  402. been unpickled.
  403. :param target: the mapped instance. If
  404. the event is configured with ``raw=True``, this will
  405. instead be the :class:`.InstanceState` state-management
  406. object associated with the instance.
  407. :param state_dict: the dictionary sent to
  408. :class:`.InstanceState.__setstate__`, containing the state
  409. dictionary which was pickled.
  410. """
  411. class _EventsHold(event.RefCollection):
  412. """Hold onto listeners against unmapped, uninstrumented classes.
  413. Establish _listen() for that class' mapper/instrumentation when
  414. those objects are created for that class.
  415. """
  416. def __init__(self, class_):
  417. self.class_ = class_
  418. @classmethod
  419. def _clear(cls):
  420. cls.all_holds.clear()
  421. class HoldEvents(object):
  422. _dispatch_target = None
  423. @classmethod
  424. def _listen(
  425. cls, event_key, raw=False, propagate=False, retval=False, **kw
  426. ):
  427. target = event_key.dispatch_target
  428. if target.class_ in target.all_holds:
  429. collection = target.all_holds[target.class_]
  430. else:
  431. collection = target.all_holds[target.class_] = {}
  432. event.registry._stored_in_collection(event_key, target)
  433. collection[event_key._key] = (
  434. event_key,
  435. raw,
  436. propagate,
  437. retval,
  438. kw,
  439. )
  440. if propagate:
  441. stack = list(target.class_.__subclasses__())
  442. while stack:
  443. subclass = stack.pop(0)
  444. stack.extend(subclass.__subclasses__())
  445. subject = target.resolve(subclass)
  446. if subject is not None:
  447. # we are already going through __subclasses__()
  448. # so leave generic propagate flag False
  449. event_key.with_dispatch_target(subject).listen(
  450. raw=raw, propagate=False, retval=retval, **kw
  451. )
  452. def remove(self, event_key):
  453. target = event_key.dispatch_target
  454. if isinstance(target, _EventsHold):
  455. collection = target.all_holds[target.class_]
  456. del collection[event_key._key]
  457. @classmethod
  458. def populate(cls, class_, subject):
  459. for subclass in class_.__mro__:
  460. if subclass in cls.all_holds:
  461. collection = cls.all_holds[subclass]
  462. for (
  463. event_key,
  464. raw,
  465. propagate,
  466. retval,
  467. kw,
  468. ) in collection.values():
  469. if propagate or subclass is class_:
  470. # since we can't be sure in what order different
  471. # classes in a hierarchy are triggered with
  472. # populate(), we rely upon _EventsHold for all event
  473. # assignment, instead of using the generic propagate
  474. # flag.
  475. event_key.with_dispatch_target(subject).listen(
  476. raw=raw, propagate=False, retval=retval, **kw
  477. )
  478. class _InstanceEventsHold(_EventsHold):
  479. all_holds = weakref.WeakKeyDictionary()
  480. def resolve(self, class_):
  481. return instrumentation.manager_of_class(class_)
  482. class HoldInstanceEvents(_EventsHold.HoldEvents, InstanceEvents):
  483. pass
  484. dispatch = event.dispatcher(HoldInstanceEvents)
  485. class MapperEvents(event.Events):
  486. """Define events specific to mappings.
  487. e.g.::
  488. from sqlalchemy import event
  489. def my_before_insert_listener(mapper, connection, target):
  490. # execute a stored procedure upon INSERT,
  491. # apply the value to the row to be inserted
  492. target.calculated_value = connection.execute(
  493. text("select my_special_function(%d)" % target.special_number)
  494. ).scalar()
  495. # associate the listener function with SomeClass,
  496. # to execute during the "before_insert" hook
  497. event.listen(
  498. SomeClass, 'before_insert', my_before_insert_listener)
  499. Available targets include:
  500. * mapped classes
  501. * unmapped superclasses of mapped or to-be-mapped classes
  502. (using the ``propagate=True`` flag)
  503. * :class:`_orm.Mapper` objects
  504. * the :class:`_orm.Mapper` class itself and the :func:`.mapper`
  505. function indicate listening for all mappers.
  506. Mapper events provide hooks into critical sections of the
  507. mapper, including those related to object instrumentation,
  508. object loading, and object persistence. In particular, the
  509. persistence methods :meth:`~.MapperEvents.before_insert`,
  510. and :meth:`~.MapperEvents.before_update` are popular
  511. places to augment the state being persisted - however, these
  512. methods operate with several significant restrictions. The
  513. user is encouraged to evaluate the
  514. :meth:`.SessionEvents.before_flush` and
  515. :meth:`.SessionEvents.after_flush` methods as more
  516. flexible and user-friendly hooks in which to apply
  517. additional database state during a flush.
  518. When using :class:`.MapperEvents`, several modifiers are
  519. available to the :func:`.event.listen` function.
  520. :param propagate=False: When True, the event listener should
  521. be applied to all inheriting mappers and/or the mappers of
  522. inheriting classes, as well as any
  523. mapper which is the target of this listener.
  524. :param raw=False: When True, the "target" argument passed
  525. to applicable event listener functions will be the
  526. instance's :class:`.InstanceState` management
  527. object, rather than the mapped instance itself.
  528. :param retval=False: when True, the user-defined event function
  529. must have a return value, the purpose of which is either to
  530. control subsequent event propagation, or to otherwise alter
  531. the operation in progress by the mapper. Possible return
  532. values are:
  533. * ``sqlalchemy.orm.interfaces.EXT_CONTINUE`` - continue event
  534. processing normally.
  535. * ``sqlalchemy.orm.interfaces.EXT_STOP`` - cancel all subsequent
  536. event handlers in the chain.
  537. * other values - the return value specified by specific listeners.
  538. """
  539. _target_class_doc = "SomeClass"
  540. _dispatch_target = mapperlib.Mapper
  541. @classmethod
  542. def _new_mapper_instance(cls, class_, mapper):
  543. _MapperEventsHold.populate(class_, mapper)
  544. @classmethod
  545. @util.preload_module("sqlalchemy.orm")
  546. def _accept_with(cls, target):
  547. orm = util.preloaded.orm
  548. if target is orm.mapper:
  549. return mapperlib.Mapper
  550. elif isinstance(target, type):
  551. if issubclass(target, mapperlib.Mapper):
  552. return target
  553. else:
  554. mapper = _mapper_or_none(target)
  555. if mapper is not None:
  556. return mapper
  557. else:
  558. return _MapperEventsHold(target)
  559. else:
  560. return target
  561. @classmethod
  562. def _listen(
  563. cls, event_key, raw=False, retval=False, propagate=False, **kw
  564. ):
  565. target, identifier, fn = (
  566. event_key.dispatch_target,
  567. event_key.identifier,
  568. event_key._listen_fn,
  569. )
  570. if (
  571. identifier in ("before_configured", "after_configured")
  572. and target is not mapperlib.Mapper
  573. ):
  574. util.warn(
  575. "'before_configured' and 'after_configured' ORM events "
  576. "only invoke with the mapper() function or Mapper class "
  577. "as the target."
  578. )
  579. if not raw or not retval:
  580. if not raw:
  581. meth = getattr(cls, identifier)
  582. try:
  583. target_index = (
  584. inspect_getfullargspec(meth)[0].index("target") - 1
  585. )
  586. except ValueError:
  587. target_index = None
  588. def wrap(*arg, **kw):
  589. if not raw and target_index is not None:
  590. arg = list(arg)
  591. arg[target_index] = arg[target_index].obj()
  592. if not retval:
  593. fn(*arg, **kw)
  594. return interfaces.EXT_CONTINUE
  595. else:
  596. return fn(*arg, **kw)
  597. event_key = event_key.with_wrapper(wrap)
  598. if propagate:
  599. for mapper in target.self_and_descendants:
  600. event_key.with_dispatch_target(mapper).base_listen(
  601. propagate=True, **kw
  602. )
  603. else:
  604. event_key.base_listen(**kw)
  605. @classmethod
  606. def _clear(cls):
  607. super(MapperEvents, cls)._clear()
  608. _MapperEventsHold._clear()
  609. def instrument_class(self, mapper, class_):
  610. r"""Receive a class when the mapper is first constructed,
  611. before instrumentation is applied to the mapped class.
  612. This event is the earliest phase of mapper construction.
  613. Most attributes of the mapper are not yet initialized.
  614. This listener can either be applied to the :class:`_orm.Mapper`
  615. class overall, or to any un-mapped class which serves as a base
  616. for classes that will be mapped (using the ``propagate=True`` flag)::
  617. Base = declarative_base()
  618. @event.listens_for(Base, "instrument_class", propagate=True)
  619. def on_new_class(mapper, cls_):
  620. " ... "
  621. :param mapper: the :class:`_orm.Mapper` which is the target
  622. of this event.
  623. :param class\_: the mapped class.
  624. """
  625. def before_mapper_configured(self, mapper, class_):
  626. """Called right before a specific mapper is to be configured.
  627. This event is intended to allow a specific mapper to be skipped during
  628. the configure step, by returning the :attr:`.orm.interfaces.EXT_SKIP`
  629. symbol which indicates to the :func:`.configure_mappers` call that this
  630. particular mapper (or hierarchy of mappers, if ``propagate=True`` is
  631. used) should be skipped in the current configuration run. When one or
  632. more mappers are skipped, the he "new mappers" flag will remain set,
  633. meaning the :func:`.configure_mappers` function will continue to be
  634. called when mappers are used, to continue to try to configure all
  635. available mappers.
  636. In comparison to the other configure-level events,
  637. :meth:`.MapperEvents.before_configured`,
  638. :meth:`.MapperEvents.after_configured`, and
  639. :meth:`.MapperEvents.mapper_configured`, the
  640. :meth;`.MapperEvents.before_mapper_configured` event provides for a
  641. meaningful return value when it is registered with the ``retval=True``
  642. parameter.
  643. .. versionadded:: 1.3
  644. e.g.::
  645. from sqlalchemy.orm import EXT_SKIP
  646. Base = declarative_base()
  647. DontConfigureBase = declarative_base()
  648. @event.listens_for(
  649. DontConfigureBase,
  650. "before_mapper_configured", retval=True, propagate=True)
  651. def dont_configure(mapper, cls):
  652. return EXT_SKIP
  653. .. seealso::
  654. :meth:`.MapperEvents.before_configured`
  655. :meth:`.MapperEvents.after_configured`
  656. :meth:`.MapperEvents.mapper_configured`
  657. """
  658. def mapper_configured(self, mapper, class_):
  659. r"""Called when a specific mapper has completed its own configuration
  660. within the scope of the :func:`.configure_mappers` call.
  661. The :meth:`.MapperEvents.mapper_configured` event is invoked
  662. for each mapper that is encountered when the
  663. :func:`_orm.configure_mappers` function proceeds through the current
  664. list of not-yet-configured mappers.
  665. :func:`_orm.configure_mappers` is typically invoked
  666. automatically as mappings are first used, as well as each time
  667. new mappers have been made available and new mapper use is
  668. detected.
  669. When the event is called, the mapper should be in its final
  670. state, but **not including backrefs** that may be invoked from
  671. other mappers; they might still be pending within the
  672. configuration operation. Bidirectional relationships that
  673. are instead configured via the
  674. :paramref:`.orm.relationship.back_populates` argument
  675. *will* be fully available, since this style of relationship does not
  676. rely upon other possibly-not-configured mappers to know that they
  677. exist.
  678. For an event that is guaranteed to have **all** mappers ready
  679. to go including backrefs that are defined only on other
  680. mappings, use the :meth:`.MapperEvents.after_configured`
  681. event; this event invokes only after all known mappings have been
  682. fully configured.
  683. The :meth:`.MapperEvents.mapper_configured` event, unlike
  684. :meth:`.MapperEvents.before_configured` or
  685. :meth:`.MapperEvents.after_configured`,
  686. is called for each mapper/class individually, and the mapper is
  687. passed to the event itself. It also is called exactly once for
  688. a particular mapper. The event is therefore useful for
  689. configurational steps that benefit from being invoked just once
  690. on a specific mapper basis, which don't require that "backref"
  691. configurations are necessarily ready yet.
  692. :param mapper: the :class:`_orm.Mapper` which is the target
  693. of this event.
  694. :param class\_: the mapped class.
  695. .. seealso::
  696. :meth:`.MapperEvents.before_configured`
  697. :meth:`.MapperEvents.after_configured`
  698. :meth:`.MapperEvents.before_mapper_configured`
  699. """
  700. # TODO: need coverage for this event
  701. def before_configured(self):
  702. """Called before a series of mappers have been configured.
  703. The :meth:`.MapperEvents.before_configured` event is invoked
  704. each time the :func:`_orm.configure_mappers` function is
  705. invoked, before the function has done any of its work.
  706. :func:`_orm.configure_mappers` is typically invoked
  707. automatically as mappings are first used, as well as each time
  708. new mappers have been made available and new mapper use is
  709. detected.
  710. This event can **only** be applied to the :class:`_orm.Mapper` class
  711. or :func:`.mapper` function, and not to individual mappings or
  712. mapped classes. It is only invoked for all mappings as a whole::
  713. from sqlalchemy.orm import mapper
  714. @event.listens_for(mapper, "before_configured")
  715. def go():
  716. # ...
  717. Contrast this event to :meth:`.MapperEvents.after_configured`,
  718. which is invoked after the series of mappers has been configured,
  719. as well as :meth:`.MapperEvents.before_mapper_configured`
  720. and :meth:`.MapperEvents.mapper_configured`, which are both invoked
  721. on a per-mapper basis.
  722. Theoretically this event is called once per
  723. application, but is actually called any time new mappers
  724. are to be affected by a :func:`_orm.configure_mappers`
  725. call. If new mappings are constructed after existing ones have
  726. already been used, this event will likely be called again. To ensure
  727. that a particular event is only called once and no further, the
  728. ``once=True`` argument (new in 0.9.4) can be applied::
  729. from sqlalchemy.orm import mapper
  730. @event.listens_for(mapper, "before_configured", once=True)
  731. def go():
  732. # ...
  733. .. versionadded:: 0.9.3
  734. .. seealso::
  735. :meth:`.MapperEvents.before_mapper_configured`
  736. :meth:`.MapperEvents.mapper_configured`
  737. :meth:`.MapperEvents.after_configured`
  738. """
  739. def after_configured(self):
  740. """Called after a series of mappers have been configured.
  741. The :meth:`.MapperEvents.after_configured` event is invoked
  742. each time the :func:`_orm.configure_mappers` function is
  743. invoked, after the function has completed its work.
  744. :func:`_orm.configure_mappers` is typically invoked
  745. automatically as mappings are first used, as well as each time
  746. new mappers have been made available and new mapper use is
  747. detected.
  748. Contrast this event to the :meth:`.MapperEvents.mapper_configured`
  749. event, which is called on a per-mapper basis while the configuration
  750. operation proceeds; unlike that event, when this event is invoked,
  751. all cross-configurations (e.g. backrefs) will also have been made
  752. available for any mappers that were pending.
  753. Also contrast to :meth:`.MapperEvents.before_configured`,
  754. which is invoked before the series of mappers has been configured.
  755. This event can **only** be applied to the :class:`_orm.Mapper` class
  756. or :func:`.mapper` function, and not to individual mappings or
  757. mapped classes. It is only invoked for all mappings as a whole::
  758. from sqlalchemy.orm import mapper
  759. @event.listens_for(mapper, "after_configured")
  760. def go():
  761. # ...
  762. Theoretically this event is called once per
  763. application, but is actually called any time new mappers
  764. have been affected by a :func:`_orm.configure_mappers`
  765. call. If new mappings are constructed after existing ones have
  766. already been used, this event will likely be called again. To ensure
  767. that a particular event is only called once and no further, the
  768. ``once=True`` argument (new in 0.9.4) can be applied::
  769. from sqlalchemy.orm import mapper
  770. @event.listens_for(mapper, "after_configured", once=True)
  771. def go():
  772. # ...
  773. .. seealso::
  774. :meth:`.MapperEvents.before_mapper_configured`
  775. :meth:`.MapperEvents.mapper_configured`
  776. :meth:`.MapperEvents.before_configured`
  777. """
  778. def before_insert(self, mapper, connection, target):
  779. """Receive an object instance before an INSERT statement
  780. is emitted corresponding to that instance.
  781. This event is used to modify local, non-object related
  782. attributes on the instance before an INSERT occurs, as well
  783. as to emit additional SQL statements on the given
  784. connection.
  785. The event is often called for a batch of objects of the
  786. same class before their INSERT statements are emitted at
  787. once in a later step. In the extremely rare case that
  788. this is not desirable, the :func:`.mapper` can be
  789. configured with ``batch=False``, which will cause
  790. batches of instances to be broken up into individual
  791. (and more poorly performing) event->persist->event
  792. steps.
  793. .. warning::
  794. Mapper-level flush events only allow **very limited operations**,
  795. on attributes local to the row being operated upon only,
  796. as well as allowing any SQL to be emitted on the given
  797. :class:`_engine.Connection`. **Please read fully** the notes
  798. at :ref:`session_persistence_mapper` for guidelines on using
  799. these methods; generally, the :meth:`.SessionEvents.before_flush`
  800. method should be preferred for general on-flush changes.
  801. :param mapper: the :class:`_orm.Mapper` which is the target
  802. of this event.
  803. :param connection: the :class:`_engine.Connection` being used to
  804. emit INSERT statements for this instance. This
  805. provides a handle into the current transaction on the
  806. target database specific to this instance.
  807. :param target: the mapped instance being persisted. If
  808. the event is configured with ``raw=True``, this will
  809. instead be the :class:`.InstanceState` state-management
  810. object associated with the instance.
  811. :return: No return value is supported by this event.
  812. .. seealso::
  813. :ref:`session_persistence_events`
  814. """
  815. def after_insert(self, mapper, connection, target):
  816. """Receive an object instance after an INSERT statement
  817. is emitted corresponding to that instance.
  818. This event is used to modify in-Python-only
  819. state on the instance after an INSERT occurs, as well
  820. as to emit additional SQL statements on the given
  821. connection.
  822. The event is often called for a batch of objects of the
  823. same class after their INSERT statements have been
  824. emitted at once in a previous step. In the extremely
  825. rare case that this is not desirable, the
  826. :func:`.mapper` can be configured with ``batch=False``,
  827. which will cause batches of instances to be broken up
  828. into individual (and more poorly performing)
  829. event->persist->event steps.
  830. .. warning::
  831. Mapper-level flush events only allow **very limited operations**,
  832. on attributes local to the row being operated upon only,
  833. as well as allowing any SQL to be emitted on the given
  834. :class:`_engine.Connection`. **Please read fully** the notes
  835. at :ref:`session_persistence_mapper` for guidelines on using
  836. these methods; generally, the :meth:`.SessionEvents.before_flush`
  837. method should be preferred for general on-flush changes.
  838. :param mapper: the :class:`_orm.Mapper` which is the target
  839. of this event.
  840. :param connection: the :class:`_engine.Connection` being used to
  841. emit INSERT statements for this instance. This
  842. provides a handle into the current transaction on the
  843. target database specific to this instance.
  844. :param target: the mapped instance being persisted. If
  845. the event is configured with ``raw=True``, this will
  846. instead be the :class:`.InstanceState` state-management
  847. object associated with the instance.
  848. :return: No return value is supported by this event.
  849. .. seealso::
  850. :ref:`session_persistence_events`
  851. """
  852. def before_update(self, mapper, connection, target):
  853. """Receive an object instance before an UPDATE statement
  854. is emitted corresponding to that instance.
  855. This event is used to modify local, non-object related
  856. attributes on the instance before an UPDATE occurs, as well
  857. as to emit additional SQL statements on the given
  858. connection.
  859. This method is called for all instances that are
  860. marked as "dirty", *even those which have no net changes
  861. to their column-based attributes*. An object is marked
  862. as dirty when any of its column-based attributes have a
  863. "set attribute" operation called or when any of its
  864. collections are modified. If, at update time, no
  865. column-based attributes have any net changes, no UPDATE
  866. statement will be issued. This means that an instance
  867. being sent to :meth:`~.MapperEvents.before_update` is
  868. *not* a guarantee that an UPDATE statement will be
  869. issued, although you can affect the outcome here by
  870. modifying attributes so that a net change in value does
  871. exist.
  872. To detect if the column-based attributes on the object have net
  873. changes, and will therefore generate an UPDATE statement, use
  874. ``object_session(instance).is_modified(instance,
  875. include_collections=False)``.
  876. The event is often called for a batch of objects of the
  877. same class before their UPDATE statements are emitted at
  878. once in a later step. In the extremely rare case that
  879. this is not desirable, the :func:`.mapper` can be
  880. configured with ``batch=False``, which will cause
  881. batches of instances to be broken up into individual
  882. (and more poorly performing) event->persist->event
  883. steps.
  884. .. warning::
  885. Mapper-level flush events only allow **very limited operations**,
  886. on attributes local to the row being operated upon only,
  887. as well as allowing any SQL to be emitted on the given
  888. :class:`_engine.Connection`. **Please read fully** the notes
  889. at :ref:`session_persistence_mapper` for guidelines on using
  890. these methods; generally, the :meth:`.SessionEvents.before_flush`
  891. method should be preferred for general on-flush changes.
  892. :param mapper: the :class:`_orm.Mapper` which is the target
  893. of this event.
  894. :param connection: the :class:`_engine.Connection` being used to
  895. emit UPDATE statements for this instance. This
  896. provides a handle into the current transaction on the
  897. target database specific to this instance.
  898. :param target: the mapped instance being persisted. If
  899. the event is configured with ``raw=True``, this will
  900. instead be the :class:`.InstanceState` state-management
  901. object associated with the instance.
  902. :return: No return value is supported by this event.
  903. .. seealso::
  904. :ref:`session_persistence_events`
  905. """
  906. def after_update(self, mapper, connection, target):
  907. """Receive an object instance after an UPDATE statement
  908. is emitted corresponding to that instance.
  909. This event is used to modify in-Python-only
  910. state on the instance after an UPDATE occurs, as well
  911. as to emit additional SQL statements on the given
  912. connection.
  913. This method is called for all instances that are
  914. marked as "dirty", *even those which have no net changes
  915. to their column-based attributes*, and for which
  916. no UPDATE statement has proceeded. An object is marked
  917. as dirty when any of its column-based attributes have a
  918. "set attribute" operation called or when any of its
  919. collections are modified. If, at update time, no
  920. column-based attributes have any net changes, no UPDATE
  921. statement will be issued. This means that an instance
  922. being sent to :meth:`~.MapperEvents.after_update` is
  923. *not* a guarantee that an UPDATE statement has been
  924. issued.
  925. To detect if the column-based attributes on the object have net
  926. changes, and therefore resulted in an UPDATE statement, use
  927. ``object_session(instance).is_modified(instance,
  928. include_collections=False)``.
  929. The event is often called for a batch of objects of the
  930. same class after their UPDATE statements have been emitted at
  931. once in a previous step. In the extremely rare case that
  932. this is not desirable, the :func:`.mapper` can be
  933. configured with ``batch=False``, which will cause
  934. batches of instances to be broken up into individual
  935. (and more poorly performing) event->persist->event
  936. steps.
  937. .. warning::
  938. Mapper-level flush events only allow **very limited operations**,
  939. on attributes local to the row being operated upon only,
  940. as well as allowing any SQL to be emitted on the given
  941. :class:`_engine.Connection`. **Please read fully** the notes
  942. at :ref:`session_persistence_mapper` for guidelines on using
  943. these methods; generally, the :meth:`.SessionEvents.before_flush`
  944. method should be preferred for general on-flush changes.
  945. :param mapper: the :class:`_orm.Mapper` which is the target
  946. of this event.
  947. :param connection: the :class:`_engine.Connection` being used to
  948. emit UPDATE statements for this instance. This
  949. provides a handle into the current transaction on the
  950. target database specific to this instance.
  951. :param target: the mapped instance being persisted. If
  952. the event is configured with ``raw=True``, this will
  953. instead be the :class:`.InstanceState` state-management
  954. object associated with the instance.
  955. :return: No return value is supported by this event.
  956. .. seealso::
  957. :ref:`session_persistence_events`
  958. """
  959. def before_delete(self, mapper, connection, target):
  960. """Receive an object instance before a DELETE statement
  961. is emitted corresponding to that instance.
  962. This event is used to emit additional SQL statements on
  963. the given connection as well as to perform application
  964. specific bookkeeping related to a deletion event.
  965. The event is often called for a batch of objects of the
  966. same class before their DELETE statements are emitted at
  967. once in a later step.
  968. .. warning::
  969. Mapper-level flush events only allow **very limited operations**,
  970. on attributes local to the row being operated upon only,
  971. as well as allowing any SQL to be emitted on the given
  972. :class:`_engine.Connection`. **Please read fully** the notes
  973. at :ref:`session_persistence_mapper` for guidelines on using
  974. these methods; generally, the :meth:`.SessionEvents.before_flush`
  975. method should be preferred for general on-flush changes.
  976. :param mapper: the :class:`_orm.Mapper` which is the target
  977. of this event.
  978. :param connection: the :class:`_engine.Connection` being used to
  979. emit DELETE statements for this instance. This
  980. provides a handle into the current transaction on the
  981. target database specific to this instance.
  982. :param target: the mapped instance being deleted. If
  983. the event is configured with ``raw=True``, this will
  984. instead be the :class:`.InstanceState` state-management
  985. object associated with the instance.
  986. :return: No return value is supported by this event.
  987. .. seealso::
  988. :ref:`session_persistence_events`
  989. """
  990. def after_delete(self, mapper, connection, target):
  991. """Receive an object instance after a DELETE statement
  992. has been emitted corresponding to that instance.
  993. This event is used to emit additional SQL statements on
  994. the given connection as well as to perform application
  995. specific bookkeeping related to a deletion event.
  996. The event is often called for a batch of objects of the
  997. same class after their DELETE statements have been emitted at
  998. once in a previous step.
  999. .. warning::
  1000. Mapper-level flush events only allow **very limited operations**,
  1001. on attributes local to the row being operated upon only,
  1002. as well as allowing any SQL to be emitted on the given
  1003. :class:`_engine.Connection`. **Please read fully** the notes
  1004. at :ref:`session_persistence_mapper` for guidelines on using
  1005. these methods; generally, the :meth:`.SessionEvents.before_flush`
  1006. method should be preferred for general on-flush changes.
  1007. :param mapper: the :class:`_orm.Mapper` which is the target
  1008. of this event.
  1009. :param connection: the :class:`_engine.Connection` being used to
  1010. emit DELETE statements for this instance. This
  1011. provides a handle into the current transaction on the
  1012. target database specific to this instance.
  1013. :param target: the mapped instance being deleted. If
  1014. the event is configured with ``raw=True``, this will
  1015. instead be the :class:`.InstanceState` state-management
  1016. object associated with the instance.
  1017. :return: No return value is supported by this event.
  1018. .. seealso::
  1019. :ref:`session_persistence_events`
  1020. """
  1021. class _MapperEventsHold(_EventsHold):
  1022. all_holds = weakref.WeakKeyDictionary()
  1023. def resolve(self, class_):
  1024. return _mapper_or_none(class_)
  1025. class HoldMapperEvents(_EventsHold.HoldEvents, MapperEvents):
  1026. pass
  1027. dispatch = event.dispatcher(HoldMapperEvents)
  1028. _sessionevents_lifecycle_event_names = set()
  1029. class SessionEvents(event.Events):
  1030. """Define events specific to :class:`.Session` lifecycle.
  1031. e.g.::
  1032. from sqlalchemy import event
  1033. from sqlalchemy.orm import sessionmaker
  1034. def my_before_commit(session):
  1035. print("before commit!")
  1036. Session = sessionmaker()
  1037. event.listen(Session, "before_commit", my_before_commit)
  1038. The :func:`~.event.listen` function will accept
  1039. :class:`.Session` objects as well as the return result
  1040. of :class:`~.sessionmaker()` and :class:`~.scoped_session()`.
  1041. Additionally, it accepts the :class:`.Session` class which
  1042. will apply listeners to all :class:`.Session` instances
  1043. globally.
  1044. :param raw=False: When True, the "target" argument passed
  1045. to applicable event listener functions that work on individual
  1046. objects will be the instance's :class:`.InstanceState` management
  1047. object, rather than the mapped instance itself.
  1048. .. versionadded:: 1.3.14
  1049. :param restore_load_context=False: Applies to the
  1050. :meth:`.SessionEvents.loaded_as_persistent` event. Restores the loader
  1051. context of the object when the event hook is complete, so that ongoing
  1052. eager load operations continue to target the object appropriately. A
  1053. warning is emitted if the object is moved to a new loader context from
  1054. within this event if this flag is not set.
  1055. .. versionadded:: 1.3.14
  1056. """
  1057. _target_class_doc = "SomeSessionClassOrObject"
  1058. _dispatch_target = Session
  1059. def _lifecycle_event(fn):
  1060. _sessionevents_lifecycle_event_names.add(fn.__name__)
  1061. return fn
  1062. @classmethod
  1063. def _accept_with(cls, target):
  1064. if isinstance(target, scoped_session):
  1065. target = target.session_factory
  1066. if not isinstance(target, sessionmaker) and (
  1067. not isinstance(target, type) or not issubclass(target, Session)
  1068. ):
  1069. raise exc.ArgumentError(
  1070. "Session event listen on a scoped_session "
  1071. "requires that its creation callable "
  1072. "is associated with the Session class."
  1073. )
  1074. if isinstance(target, sessionmaker):
  1075. return target.class_
  1076. elif isinstance(target, type):
  1077. if issubclass(target, scoped_session):
  1078. return Session
  1079. elif issubclass(target, Session):
  1080. return target
  1081. elif isinstance(target, Session):
  1082. return target
  1083. else:
  1084. # allows alternate SessionEvents-like-classes to be consulted
  1085. return event.Events._accept_with(target)
  1086. @classmethod
  1087. def _listen(cls, event_key, raw=False, restore_load_context=False, **kw):
  1088. is_instance_event = (
  1089. event_key.identifier in _sessionevents_lifecycle_event_names
  1090. )
  1091. if is_instance_event:
  1092. if not raw or restore_load_context:
  1093. fn = event_key._listen_fn
  1094. def wrap(session, state, *arg, **kw):
  1095. if not raw:
  1096. target = state.obj()
  1097. if target is None:
  1098. # existing behavior is that if the object is
  1099. # garbage collected, no event is emitted
  1100. return
  1101. else:
  1102. target = state
  1103. if restore_load_context:
  1104. runid = state.runid
  1105. try:
  1106. return fn(session, target, *arg, **kw)
  1107. finally:
  1108. if restore_load_context:
  1109. state.runid = runid
  1110. event_key = event_key.with_wrapper(wrap)
  1111. event_key.base_listen(**kw)
  1112. def do_orm_execute(self, orm_execute_state):
  1113. """Intercept statement executions that occur on behalf of an
  1114. ORM :class:`.Session` object.
  1115. This event is invoked for all top-level SQL statements invoked from the
  1116. :meth:`_orm.Session.execute` method, as well as related methods such as
  1117. :meth:`_orm.Session.scalars` and :meth:`_orm.Session.scalar`. As of
  1118. SQLAlchemy 1.4, all ORM queries emitted on behalf of a
  1119. :class:`_orm.Session` will flow through this method, so this event hook
  1120. provides the single point at which ORM queries of all types may be
  1121. intercepted before they are invoked, and additionally to replace their
  1122. execution with a different process.
  1123. .. note:: The :meth:`_orm.SessionEvents.do_orm_execute` event hook
  1124. is triggered **for ORM statement executions only**, meaning those
  1125. invoked via the :meth:`_orm.Session.execute` and similar methods on
  1126. the :class:`_orm.Session` object. It does **not** trigger for
  1127. statements that are invoked by SQLAlchemy Core only, i.e. statements
  1128. invoked directly using :meth:`_engine.Connection.execute` or
  1129. otherwise originating from an :class:`_engine.Engine` object without
  1130. any :class:`_orm.Session` involved. To intercept **all** SQL
  1131. executions regardless of whether the Core or ORM APIs are in use,
  1132. see the event hooks at
  1133. :class:`.ConnectionEvents`, such as
  1134. :meth:`.ConnectionEvents.before_execute` and
  1135. :meth:`.ConnectionEvents.before_cursor_execute`.
  1136. This event is a ``do_`` event, meaning it has the capability to replace
  1137. the operation that the :meth:`_orm.Session.execute` method normally
  1138. performs. The intended use for this includes sharding and
  1139. result-caching schemes which may seek to invoke the same statement
  1140. across multiple database connections, returning a result that is
  1141. merged from each of them, or which don't invoke the statement at all,
  1142. instead returning data from a cache.
  1143. The hook intends to replace the use of the
  1144. ``Query._execute_and_instances`` method that could be subclassed prior
  1145. to SQLAlchemy 1.4.
  1146. :param orm_execute_state: an instance of :class:`.ORMExecuteState`
  1147. which contains all information about the current execution, as well
  1148. as helper functions used to derive other commonly required
  1149. information. See that object for details.
  1150. .. seealso::
  1151. :ref:`session_execute_events` - top level documentation on how
  1152. to use :meth:`_orm.SessionEvents.do_orm_execute`
  1153. :class:`.ORMExecuteState` - the object passed to the
  1154. :meth:`_orm.SessionEvents.do_orm_execute` event which contains
  1155. all information about the statement to be invoked. It also
  1156. provides an interface to extend the current statement, options,
  1157. and parameters as well as an option that allows programmatic
  1158. invocation of the statement at any point.
  1159. :ref:`examples_session_orm_events` - includes examples of using
  1160. :meth:`_orm.SessionEvents.do_orm_execute`
  1161. :ref:`examples_caching` - an example of how to integrate
  1162. Dogpile caching with the ORM :class:`_orm.Session` making use
  1163. of the :meth:`_orm.SessionEvents.do_orm_execute` event hook.
  1164. :ref:`examples_sharding` - the Horizontal Sharding example /
  1165. extension relies upon the
  1166. :meth:`_orm.SessionEvents.do_orm_execute` event hook to invoke a
  1167. SQL statement on multiple backends and return a merged result.
  1168. .. versionadded:: 1.4
  1169. """
  1170. def after_transaction_create(self, session, transaction):
  1171. """Execute when a new :class:`.SessionTransaction` is created.
  1172. This event differs from :meth:`~.SessionEvents.after_begin`
  1173. in that it occurs for each :class:`.SessionTransaction`
  1174. overall, as opposed to when transactions are begun
  1175. on individual database connections. It is also invoked
  1176. for nested transactions and subtransactions, and is always
  1177. matched by a corresponding
  1178. :meth:`~.SessionEvents.after_transaction_end` event
  1179. (assuming normal operation of the :class:`.Session`).
  1180. :param session: the target :class:`.Session`.
  1181. :param transaction: the target :class:`.SessionTransaction`.
  1182. To detect if this is the outermost
  1183. :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
  1184. SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
  1185. is ``None``::
  1186. @event.listens_for(session, "after_transaction_create")
  1187. def after_transaction_create(session, transaction):
  1188. if transaction.parent is None:
  1189. # work with top-level transaction
  1190. To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
  1191. :attr:`.SessionTransaction.nested` attribute::
  1192. @event.listens_for(session, "after_transaction_create")
  1193. def after_transaction_create(session, transaction):
  1194. if transaction.nested:
  1195. # work with SAVEPOINT transaction
  1196. .. seealso::
  1197. :class:`.SessionTransaction`
  1198. :meth:`~.SessionEvents.after_transaction_end`
  1199. """
  1200. def after_transaction_end(self, session, transaction):
  1201. """Execute when the span of a :class:`.SessionTransaction` ends.
  1202. This event differs from :meth:`~.SessionEvents.after_commit`
  1203. in that it corresponds to all :class:`.SessionTransaction`
  1204. objects in use, including those for nested transactions
  1205. and subtransactions, and is always matched by a corresponding
  1206. :meth:`~.SessionEvents.after_transaction_create` event.
  1207. :param session: the target :class:`.Session`.
  1208. :param transaction: the target :class:`.SessionTransaction`.
  1209. To detect if this is the outermost
  1210. :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
  1211. SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
  1212. is ``None``::
  1213. @event.listens_for(session, "after_transaction_create")
  1214. def after_transaction_end(session, transaction):
  1215. if transaction.parent is None:
  1216. # work with top-level transaction
  1217. To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
  1218. :attr:`.SessionTransaction.nested` attribute::
  1219. @event.listens_for(session, "after_transaction_create")
  1220. def after_transaction_end(session, transaction):
  1221. if transaction.nested:
  1222. # work with SAVEPOINT transaction
  1223. .. seealso::
  1224. :class:`.SessionTransaction`
  1225. :meth:`~.SessionEvents.after_transaction_create`
  1226. """
  1227. def before_commit(self, session):
  1228. """Execute before commit is called.
  1229. .. note::
  1230. The :meth:`~.SessionEvents.before_commit` hook is *not* per-flush,
  1231. that is, the :class:`.Session` can emit SQL to the database
  1232. many times within the scope of a transaction.
  1233. For interception of these events, use the
  1234. :meth:`~.SessionEvents.before_flush`,
  1235. :meth:`~.SessionEvents.after_flush`, or
  1236. :meth:`~.SessionEvents.after_flush_postexec`
  1237. events.
  1238. :param session: The target :class:`.Session`.
  1239. .. seealso::
  1240. :meth:`~.SessionEvents.after_commit`
  1241. :meth:`~.SessionEvents.after_begin`
  1242. :meth:`~.SessionEvents.after_transaction_create`
  1243. :meth:`~.SessionEvents.after_transaction_end`
  1244. """
  1245. def after_commit(self, session):
  1246. """Execute after a commit has occurred.
  1247. .. note::
  1248. The :meth:`~.SessionEvents.after_commit` hook is *not* per-flush,
  1249. that is, the :class:`.Session` can emit SQL to the database
  1250. many times within the scope of a transaction.
  1251. For interception of these events, use the
  1252. :meth:`~.SessionEvents.before_flush`,
  1253. :meth:`~.SessionEvents.after_flush`, or
  1254. :meth:`~.SessionEvents.after_flush_postexec`
  1255. events.
  1256. .. note::
  1257. The :class:`.Session` is not in an active transaction
  1258. when the :meth:`~.SessionEvents.after_commit` event is invoked,
  1259. and therefore can not emit SQL. To emit SQL corresponding to
  1260. every transaction, use the :meth:`~.SessionEvents.before_commit`
  1261. event.
  1262. :param session: The target :class:`.Session`.
  1263. .. seealso::
  1264. :meth:`~.SessionEvents.before_commit`
  1265. :meth:`~.SessionEvents.after_begin`
  1266. :meth:`~.SessionEvents.after_transaction_create`
  1267. :meth:`~.SessionEvents.after_transaction_end`
  1268. """
  1269. def after_rollback(self, session):
  1270. """Execute after a real DBAPI rollback has occurred.
  1271. Note that this event only fires when the *actual* rollback against
  1272. the database occurs - it does *not* fire each time the
  1273. :meth:`.Session.rollback` method is called, if the underlying
  1274. DBAPI transaction has already been rolled back. In many
  1275. cases, the :class:`.Session` will not be in
  1276. an "active" state during this event, as the current
  1277. transaction is not valid. To acquire a :class:`.Session`
  1278. which is active after the outermost rollback has proceeded,
  1279. use the :meth:`.SessionEvents.after_soft_rollback` event, checking the
  1280. :attr:`.Session.is_active` flag.
  1281. :param session: The target :class:`.Session`.
  1282. """
  1283. def after_soft_rollback(self, session, previous_transaction):
  1284. """Execute after any rollback has occurred, including "soft"
  1285. rollbacks that don't actually emit at the DBAPI level.
  1286. This corresponds to both nested and outer rollbacks, i.e.
  1287. the innermost rollback that calls the DBAPI's
  1288. rollback() method, as well as the enclosing rollback
  1289. calls that only pop themselves from the transaction stack.
  1290. The given :class:`.Session` can be used to invoke SQL and
  1291. :meth:`.Session.query` operations after an outermost rollback
  1292. by first checking the :attr:`.Session.is_active` flag::
  1293. @event.listens_for(Session, "after_soft_rollback")
  1294. def do_something(session, previous_transaction):
  1295. if session.is_active:
  1296. session.execute("select * from some_table")
  1297. :param session: The target :class:`.Session`.
  1298. :param previous_transaction: The :class:`.SessionTransaction`
  1299. transactional marker object which was just closed. The current
  1300. :class:`.SessionTransaction` for the given :class:`.Session` is
  1301. available via the :attr:`.Session.transaction` attribute.
  1302. """
  1303. def before_flush(self, session, flush_context, instances):
  1304. """Execute before flush process has started.
  1305. :param session: The target :class:`.Session`.
  1306. :param flush_context: Internal :class:`.UOWTransaction` object
  1307. which handles the details of the flush.
  1308. :param instances: Usually ``None``, this is the collection of
  1309. objects which can be passed to the :meth:`.Session.flush` method
  1310. (note this usage is deprecated).
  1311. .. seealso::
  1312. :meth:`~.SessionEvents.after_flush`
  1313. :meth:`~.SessionEvents.after_flush_postexec`
  1314. :ref:`session_persistence_events`
  1315. """
  1316. def after_flush(self, session, flush_context):
  1317. """Execute after flush has completed, but before commit has been
  1318. called.
  1319. Note that the session's state is still in pre-flush, i.e. 'new',
  1320. 'dirty', and 'deleted' lists still show pre-flush state as well
  1321. as the history settings on instance attributes.
  1322. .. warning:: This event runs after the :class:`.Session` has emitted
  1323. SQL to modify the database, but **before** it has altered its
  1324. internal state to reflect those changes, including that newly
  1325. inserted objects are placed into the identity map. ORM operations
  1326. emitted within this event such as loads of related items
  1327. may produce new identity map entries that will immediately
  1328. be replaced, sometimes causing confusing results. SQLAlchemy will
  1329. emit a warning for this condition as of version 1.3.9.
  1330. :param session: The target :class:`.Session`.
  1331. :param flush_context: Internal :class:`.UOWTransaction` object
  1332. which handles the details of the flush.
  1333. .. seealso::
  1334. :meth:`~.SessionEvents.before_flush`
  1335. :meth:`~.SessionEvents.after_flush_postexec`
  1336. :ref:`session_persistence_events`
  1337. """
  1338. def after_flush_postexec(self, session, flush_context):
  1339. """Execute after flush has completed, and after the post-exec
  1340. state occurs.
  1341. This will be when the 'new', 'dirty', and 'deleted' lists are in
  1342. their final state. An actual commit() may or may not have
  1343. occurred, depending on whether or not the flush started its own
  1344. transaction or participated in a larger transaction.
  1345. :param session: The target :class:`.Session`.
  1346. :param flush_context: Internal :class:`.UOWTransaction` object
  1347. which handles the details of the flush.
  1348. .. seealso::
  1349. :meth:`~.SessionEvents.before_flush`
  1350. :meth:`~.SessionEvents.after_flush`
  1351. :ref:`session_persistence_events`
  1352. """
  1353. def after_begin(self, session, transaction, connection):
  1354. """Execute after a transaction is begun on a connection
  1355. :param session: The target :class:`.Session`.
  1356. :param transaction: The :class:`.SessionTransaction`.
  1357. :param connection: The :class:`_engine.Connection` object
  1358. which will be used for SQL statements.
  1359. .. seealso::
  1360. :meth:`~.SessionEvents.before_commit`
  1361. :meth:`~.SessionEvents.after_commit`
  1362. :meth:`~.SessionEvents.after_transaction_create`
  1363. :meth:`~.SessionEvents.after_transaction_end`
  1364. """
  1365. @_lifecycle_event
  1366. def before_attach(self, session, instance):
  1367. """Execute before an instance is attached to a session.
  1368. This is called before an add, delete or merge causes
  1369. the object to be part of the session.
  1370. .. seealso::
  1371. :meth:`~.SessionEvents.after_attach`
  1372. :ref:`session_lifecycle_events`
  1373. """
  1374. @_lifecycle_event
  1375. def after_attach(self, session, instance):
  1376. """Execute after an instance is attached to a session.
  1377. This is called after an add, delete or merge.
  1378. .. note::
  1379. As of 0.8, this event fires off *after* the item
  1380. has been fully associated with the session, which is
  1381. different than previous releases. For event
  1382. handlers that require the object not yet
  1383. be part of session state (such as handlers which
  1384. may autoflush while the target object is not
  1385. yet complete) consider the
  1386. new :meth:`.before_attach` event.
  1387. .. seealso::
  1388. :meth:`~.SessionEvents.before_attach`
  1389. :ref:`session_lifecycle_events`
  1390. """
  1391. @event._legacy_signature(
  1392. "0.9",
  1393. ["session", "query", "query_context", "result"],
  1394. lambda update_context: (
  1395. update_context.session,
  1396. update_context.query,
  1397. None,
  1398. update_context.result,
  1399. ),
  1400. )
  1401. def after_bulk_update(self, update_context):
  1402. """Execute after an ORM UPDATE against a WHERE expression has been
  1403. invoked.
  1404. This is called as a result of the :meth:`_query.Query.update` method.
  1405. :param update_context: an "update context" object which contains
  1406. details about the update, including these attributes:
  1407. * ``session`` - the :class:`.Session` involved
  1408. * ``query`` -the :class:`_query.Query`
  1409. object that this update operation
  1410. was called upon.
  1411. * ``values`` The "values" dictionary that was passed to
  1412. :meth:`_query.Query.update`.
  1413. * ``result`` the :class:`_engine.CursorResult`
  1414. returned as a result of the
  1415. bulk UPDATE operation.
  1416. .. versionchanged:: 1.4 the update_context no longer has a
  1417. ``QueryContext`` object associated with it.
  1418. .. seealso::
  1419. :meth:`.QueryEvents.before_compile_update`
  1420. :meth:`.SessionEvents.after_bulk_delete`
  1421. """
  1422. @event._legacy_signature(
  1423. "0.9",
  1424. ["session", "query", "query_context", "result"],
  1425. lambda delete_context: (
  1426. delete_context.session,
  1427. delete_context.query,
  1428. None,
  1429. delete_context.result,
  1430. ),
  1431. )
  1432. def after_bulk_delete(self, delete_context):
  1433. """Execute after ORM DELETE against a WHERE expression has been
  1434. invoked.
  1435. This is called as a result of the :meth:`_query.Query.delete` method.
  1436. :param delete_context: a "delete context" object which contains
  1437. details about the update, including these attributes:
  1438. * ``session`` - the :class:`.Session` involved
  1439. * ``query`` -the :class:`_query.Query`
  1440. object that this update operation
  1441. was called upon.
  1442. * ``result`` the :class:`_engine.CursorResult`
  1443. returned as a result of the
  1444. bulk DELETE operation.
  1445. .. versionchanged:: 1.4 the update_context no longer has a
  1446. ``QueryContext`` object associated with it.
  1447. .. seealso::
  1448. :meth:`.QueryEvents.before_compile_delete`
  1449. :meth:`.SessionEvents.after_bulk_update`
  1450. """
  1451. @_lifecycle_event
  1452. def transient_to_pending(self, session, instance):
  1453. """Intercept the "transient to pending" transition for a specific
  1454. object.
  1455. This event is a specialization of the
  1456. :meth:`.SessionEvents.after_attach` event which is only invoked
  1457. for this specific transition. It is invoked typically during the
  1458. :meth:`.Session.add` call.
  1459. :param session: target :class:`.Session`
  1460. :param instance: the ORM-mapped instance being operated upon.
  1461. .. versionadded:: 1.1
  1462. .. seealso::
  1463. :ref:`session_lifecycle_events`
  1464. """
  1465. @_lifecycle_event
  1466. def pending_to_transient(self, session, instance):
  1467. """Intercept the "pending to transient" transition for a specific
  1468. object.
  1469. This less common transition occurs when an pending object that has
  1470. not been flushed is evicted from the session; this can occur
  1471. when the :meth:`.Session.rollback` method rolls back the transaction,
  1472. or when the :meth:`.Session.expunge` method is used.
  1473. :param session: target :class:`.Session`
  1474. :param instance: the ORM-mapped instance being operated upon.
  1475. .. versionadded:: 1.1
  1476. .. seealso::
  1477. :ref:`session_lifecycle_events`
  1478. """
  1479. @_lifecycle_event
  1480. def persistent_to_transient(self, session, instance):
  1481. """Intercept the "persistent to transient" transition for a specific
  1482. object.
  1483. This less common transition occurs when an pending object that has
  1484. has been flushed is evicted from the session; this can occur
  1485. when the :meth:`.Session.rollback` method rolls back the transaction.
  1486. :param session: target :class:`.Session`
  1487. :param instance: the ORM-mapped instance being operated upon.
  1488. .. versionadded:: 1.1
  1489. .. seealso::
  1490. :ref:`session_lifecycle_events`
  1491. """
  1492. @_lifecycle_event
  1493. def pending_to_persistent(self, session, instance):
  1494. """Intercept the "pending to persistent"" transition for a specific
  1495. object.
  1496. This event is invoked within the flush process, and is
  1497. similar to scanning the :attr:`.Session.new` collection within
  1498. the :meth:`.SessionEvents.after_flush` event. However, in this
  1499. case the object has already been moved to the persistent state
  1500. when the event is called.
  1501. :param session: target :class:`.Session`
  1502. :param instance: the ORM-mapped instance being operated upon.
  1503. .. versionadded:: 1.1
  1504. .. seealso::
  1505. :ref:`session_lifecycle_events`
  1506. """
  1507. @_lifecycle_event
  1508. def detached_to_persistent(self, session, instance):
  1509. """Intercept the "detached to persistent" transition for a specific
  1510. object.
  1511. This event is a specialization of the
  1512. :meth:`.SessionEvents.after_attach` event which is only invoked
  1513. for this specific transition. It is invoked typically during the
  1514. :meth:`.Session.add` call, as well as during the
  1515. :meth:`.Session.delete` call if the object was not previously
  1516. associated with the
  1517. :class:`.Session` (note that an object marked as "deleted" remains
  1518. in the "persistent" state until the flush proceeds).
  1519. .. note::
  1520. If the object becomes persistent as part of a call to
  1521. :meth:`.Session.delete`, the object is **not** yet marked as
  1522. deleted when this event is called. To detect deleted objects,
  1523. check the ``deleted`` flag sent to the
  1524. :meth:`.SessionEvents.persistent_to_detached` to event after the
  1525. flush proceeds, or check the :attr:`.Session.deleted` collection
  1526. within the :meth:`.SessionEvents.before_flush` event if deleted
  1527. objects need to be intercepted before the flush.
  1528. :param session: target :class:`.Session`
  1529. :param instance: the ORM-mapped instance being operated upon.
  1530. .. versionadded:: 1.1
  1531. .. seealso::
  1532. :ref:`session_lifecycle_events`
  1533. """
  1534. @_lifecycle_event
  1535. def loaded_as_persistent(self, session, instance):
  1536. """Intercept the "loaded as persistent" transition for a specific
  1537. object.
  1538. This event is invoked within the ORM loading process, and is invoked
  1539. very similarly to the :meth:`.InstanceEvents.load` event. However,
  1540. the event here is linkable to a :class:`.Session` class or instance,
  1541. rather than to a mapper or class hierarchy, and integrates
  1542. with the other session lifecycle events smoothly. The object
  1543. is guaranteed to be present in the session's identity map when
  1544. this event is called.
  1545. .. note:: This event is invoked within the loader process before
  1546. eager loaders may have been completed, and the object's state may
  1547. not be complete. Additionally, invoking row-level refresh
  1548. operations on the object will place the object into a new loader
  1549. context, interfering with the existing load context. See the note
  1550. on :meth:`.InstanceEvents.load` for background on making use of the
  1551. :paramref:`.SessionEvents.restore_load_context` parameter, which
  1552. works in the same manner as that of
  1553. :paramref:`.InstanceEvents.restore_load_context`, in order to
  1554. resolve this scenario.
  1555. :param session: target :class:`.Session`
  1556. :param instance: the ORM-mapped instance being operated upon.
  1557. .. versionadded:: 1.1
  1558. .. seealso::
  1559. :ref:`session_lifecycle_events`
  1560. """
  1561. @_lifecycle_event
  1562. def persistent_to_deleted(self, session, instance):
  1563. """Intercept the "persistent to deleted" transition for a specific
  1564. object.
  1565. This event is invoked when a persistent object's identity
  1566. is deleted from the database within a flush, however the object
  1567. still remains associated with the :class:`.Session` until the
  1568. transaction completes.
  1569. If the transaction is rolled back, the object moves again
  1570. to the persistent state, and the
  1571. :meth:`.SessionEvents.deleted_to_persistent` event is called.
  1572. If the transaction is committed, the object becomes detached,
  1573. which will emit the :meth:`.SessionEvents.deleted_to_detached`
  1574. event.
  1575. Note that while the :meth:`.Session.delete` method is the primary
  1576. public interface to mark an object as deleted, many objects
  1577. get deleted due to cascade rules, which are not always determined
  1578. until flush time. Therefore, there's no way to catch
  1579. every object that will be deleted until the flush has proceeded.
  1580. the :meth:`.SessionEvents.persistent_to_deleted` event is therefore
  1581. invoked at the end of a flush.
  1582. .. versionadded:: 1.1
  1583. .. seealso::
  1584. :ref:`session_lifecycle_events`
  1585. """
  1586. @_lifecycle_event
  1587. def deleted_to_persistent(self, session, instance):
  1588. """Intercept the "deleted to persistent" transition for a specific
  1589. object.
  1590. This transition occurs only when an object that's been deleted
  1591. successfully in a flush is restored due to a call to
  1592. :meth:`.Session.rollback`. The event is not called under
  1593. any other circumstances.
  1594. .. versionadded:: 1.1
  1595. .. seealso::
  1596. :ref:`session_lifecycle_events`
  1597. """
  1598. @_lifecycle_event
  1599. def deleted_to_detached(self, session, instance):
  1600. """Intercept the "deleted to detached" transition for a specific
  1601. object.
  1602. This event is invoked when a deleted object is evicted
  1603. from the session. The typical case when this occurs is when
  1604. the transaction for a :class:`.Session` in which the object
  1605. was deleted is committed; the object moves from the deleted
  1606. state to the detached state.
  1607. It is also invoked for objects that were deleted in a flush
  1608. when the :meth:`.Session.expunge_all` or :meth:`.Session.close`
  1609. events are called, as well as if the object is individually
  1610. expunged from its deleted state via :meth:`.Session.expunge`.
  1611. .. versionadded:: 1.1
  1612. .. seealso::
  1613. :ref:`session_lifecycle_events`
  1614. """
  1615. @_lifecycle_event
  1616. def persistent_to_detached(self, session, instance):
  1617. """Intercept the "persistent to detached" transition for a specific
  1618. object.
  1619. This event is invoked when a persistent object is evicted
  1620. from the session. There are many conditions that cause this
  1621. to happen, including:
  1622. * using a method such as :meth:`.Session.expunge`
  1623. or :meth:`.Session.close`
  1624. * Calling the :meth:`.Session.rollback` method, when the object
  1625. was part of an INSERT statement for that session's transaction
  1626. :param session: target :class:`.Session`
  1627. :param instance: the ORM-mapped instance being operated upon.
  1628. :param deleted: boolean. If True, indicates this object moved
  1629. to the detached state because it was marked as deleted and flushed.
  1630. .. versionadded:: 1.1
  1631. .. seealso::
  1632. :ref:`session_lifecycle_events`
  1633. """
  1634. class AttributeEvents(event.Events):
  1635. r"""Define events for object attributes.
  1636. These are typically defined on the class-bound descriptor for the
  1637. target class.
  1638. For example, to register a listener that will receive the
  1639. :meth:`_orm.AttributeEvents.append` event::
  1640. from sqlalchemy import event
  1641. @event.listens_for(MyClass.collection, 'append', propagate=True)
  1642. def my_append_listener(target, value, initiator):
  1643. print("received append event for target: %s" % target)
  1644. Listeners have the option to return a possibly modified version of the
  1645. value, when the :paramref:`.AttributeEvents.retval` flag is passed to
  1646. :func:`.event.listen` or :func:`.event.listens_for`, such as below,
  1647. illustrated using the :meth:`_orm.AttributeEvents.set` event::
  1648. def validate_phone(target, value, oldvalue, initiator):
  1649. "Strip non-numeric characters from a phone number"
  1650. return re.sub(r'\D', '', value)
  1651. # setup listener on UserContact.phone attribute, instructing
  1652. # it to use the return value
  1653. listen(UserContact.phone, 'set', validate_phone, retval=True)
  1654. A validation function like the above can also raise an exception
  1655. such as :exc:`ValueError` to halt the operation.
  1656. The :paramref:`.AttributeEvents.propagate` flag is also important when
  1657. applying listeners to mapped classes that also have mapped subclasses,
  1658. as when using mapper inheritance patterns::
  1659. @event.listens_for(MySuperClass.attr, 'set', propagate=True)
  1660. def receive_set(target, value, initiator):
  1661. print("value set: %s" % target)
  1662. The full list of modifiers available to the :func:`.event.listen`
  1663. and :func:`.event.listens_for` functions are below.
  1664. :param active_history=False: When True, indicates that the
  1665. "set" event would like to receive the "old" value being
  1666. replaced unconditionally, even if this requires firing off
  1667. database loads. Note that ``active_history`` can also be
  1668. set directly via :func:`.column_property` and
  1669. :func:`_orm.relationship`.
  1670. :param propagate=False: When True, the listener function will
  1671. be established not just for the class attribute given, but
  1672. for attributes of the same name on all current subclasses
  1673. of that class, as well as all future subclasses of that
  1674. class, using an additional listener that listens for
  1675. instrumentation events.
  1676. :param raw=False: When True, the "target" argument to the
  1677. event will be the :class:`.InstanceState` management
  1678. object, rather than the mapped instance itself.
  1679. :param retval=False: when True, the user-defined event
  1680. listening must return the "value" argument from the
  1681. function. This gives the listening function the opportunity
  1682. to change the value that is ultimately used for a "set"
  1683. or "append" event.
  1684. """
  1685. _target_class_doc = "SomeClass.some_attribute"
  1686. _dispatch_target = QueryableAttribute
  1687. @staticmethod
  1688. def _set_dispatch(cls, dispatch_cls):
  1689. dispatch = event.Events._set_dispatch(cls, dispatch_cls)
  1690. dispatch_cls._active_history = False
  1691. return dispatch
  1692. @classmethod
  1693. def _accept_with(cls, target):
  1694. # TODO: coverage
  1695. if isinstance(target, interfaces.MapperProperty):
  1696. return getattr(target.parent.class_, target.key)
  1697. else:
  1698. return target
  1699. @classmethod
  1700. def _listen(
  1701. cls,
  1702. event_key,
  1703. active_history=False,
  1704. raw=False,
  1705. retval=False,
  1706. propagate=False,
  1707. ):
  1708. target, fn = event_key.dispatch_target, event_key._listen_fn
  1709. if active_history:
  1710. target.dispatch._active_history = True
  1711. if not raw or not retval:
  1712. def wrap(target, *arg):
  1713. if not raw:
  1714. target = target.obj()
  1715. if not retval:
  1716. if arg:
  1717. value = arg[0]
  1718. else:
  1719. value = None
  1720. fn(target, *arg)
  1721. return value
  1722. else:
  1723. return fn(target, *arg)
  1724. event_key = event_key.with_wrapper(wrap)
  1725. event_key.base_listen(propagate=propagate)
  1726. if propagate:
  1727. manager = instrumentation.manager_of_class(target.class_)
  1728. for mgr in manager.subclass_managers(True):
  1729. event_key.with_dispatch_target(mgr[target.key]).base_listen(
  1730. propagate=True
  1731. )
  1732. if active_history:
  1733. mgr[target.key].dispatch._active_history = True
  1734. def append(self, target, value, initiator):
  1735. """Receive a collection append event.
  1736. The append event is invoked for each element as it is appended
  1737. to the collection. This occurs for single-item appends as well
  1738. as for a "bulk replace" operation.
  1739. :param target: the object instance receiving the event.
  1740. If the listener is registered with ``raw=True``, this will
  1741. be the :class:`.InstanceState` object.
  1742. :param value: the value being appended. If this listener
  1743. is registered with ``retval=True``, the listener
  1744. function must return this value, or a new value which
  1745. replaces it.
  1746. :param initiator: An instance of :class:`.attributes.Event`
  1747. representing the initiation of the event. May be modified
  1748. from its original value by backref handlers in order to control
  1749. chained event propagation, as well as be inspected for information
  1750. about the source of the event.
  1751. :return: if the event was registered with ``retval=True``,
  1752. the given value, or a new effective value, should be returned.
  1753. .. seealso::
  1754. :class:`.AttributeEvents` - background on listener options such
  1755. as propagation to subclasses.
  1756. :meth:`.AttributeEvents.bulk_replace`
  1757. """
  1758. def append_wo_mutation(self, target, value, initiator):
  1759. """Receive a collection append event where the collection was not
  1760. actually mutated.
  1761. This event differs from :meth:`_orm.AttributeEvents.append` in that
  1762. it is fired off for de-duplicating collections such as sets and
  1763. dictionaries, when the object already exists in the target collection.
  1764. The event does not have a return value and the identity of the
  1765. given object cannot be changed.
  1766. The event is used for cascading objects into a :class:`_orm.Session`
  1767. when the collection has already been mutated via a backref event.
  1768. :param target: the object instance receiving the event.
  1769. If the listener is registered with ``raw=True``, this will
  1770. be the :class:`.InstanceState` object.
  1771. :param value: the value that would be appended if the object did not
  1772. already exist in the collection.
  1773. :param initiator: An instance of :class:`.attributes.Event`
  1774. representing the initiation of the event. May be modified
  1775. from its original value by backref handlers in order to control
  1776. chained event propagation, as well as be inspected for information
  1777. about the source of the event.
  1778. :return: No return value is defined for this event.
  1779. .. versionadded:: 1.4.15
  1780. """
  1781. def bulk_replace(self, target, values, initiator):
  1782. """Receive a collection 'bulk replace' event.
  1783. This event is invoked for a sequence of values as they are incoming
  1784. to a bulk collection set operation, which can be
  1785. modified in place before the values are treated as ORM objects.
  1786. This is an "early hook" that runs before the bulk replace routine
  1787. attempts to reconcile which objects are already present in the
  1788. collection and which are being removed by the net replace operation.
  1789. It is typical that this method be combined with use of the
  1790. :meth:`.AttributeEvents.append` event. When using both of these
  1791. events, note that a bulk replace operation will invoke
  1792. the :meth:`.AttributeEvents.append` event for all new items,
  1793. even after :meth:`.AttributeEvents.bulk_replace` has been invoked
  1794. for the collection as a whole. In order to determine if an
  1795. :meth:`.AttributeEvents.append` event is part of a bulk replace,
  1796. use the symbol :attr:`~.attributes.OP_BULK_REPLACE` to test the
  1797. incoming initiator::
  1798. from sqlalchemy.orm.attributes import OP_BULK_REPLACE
  1799. @event.listens_for(SomeObject.collection, "bulk_replace")
  1800. def process_collection(target, values, initiator):
  1801. values[:] = [_make_value(value) for value in values]
  1802. @event.listens_for(SomeObject.collection, "append", retval=True)
  1803. def process_collection(target, value, initiator):
  1804. # make sure bulk_replace didn't already do it
  1805. if initiator is None or initiator.op is not OP_BULK_REPLACE:
  1806. return _make_value(value)
  1807. else:
  1808. return value
  1809. .. versionadded:: 1.2
  1810. :param target: the object instance receiving the event.
  1811. If the listener is registered with ``raw=True``, this will
  1812. be the :class:`.InstanceState` object.
  1813. :param value: a sequence (e.g. a list) of the values being set. The
  1814. handler can modify this list in place.
  1815. :param initiator: An instance of :class:`.attributes.Event`
  1816. representing the initiation of the event.
  1817. .. seealso::
  1818. :class:`.AttributeEvents` - background on listener options such
  1819. as propagation to subclasses.
  1820. """
  1821. def remove(self, target, value, initiator):
  1822. """Receive a collection remove event.
  1823. :param target: the object instance receiving the event.
  1824. If the listener is registered with ``raw=True``, this will
  1825. be the :class:`.InstanceState` object.
  1826. :param value: the value being removed.
  1827. :param initiator: An instance of :class:`.attributes.Event`
  1828. representing the initiation of the event. May be modified
  1829. from its original value by backref handlers in order to control
  1830. chained event propagation.
  1831. .. versionchanged:: 0.9.0 the ``initiator`` argument is now
  1832. passed as a :class:`.attributes.Event` object, and may be
  1833. modified by backref handlers within a chain of backref-linked
  1834. events.
  1835. :return: No return value is defined for this event.
  1836. .. seealso::
  1837. :class:`.AttributeEvents` - background on listener options such
  1838. as propagation to subclasses.
  1839. """
  1840. def set(self, target, value, oldvalue, initiator):
  1841. """Receive a scalar set event.
  1842. :param target: the object instance receiving the event.
  1843. If the listener is registered with ``raw=True``, this will
  1844. be the :class:`.InstanceState` object.
  1845. :param value: the value being set. If this listener
  1846. is registered with ``retval=True``, the listener
  1847. function must return this value, or a new value which
  1848. replaces it.
  1849. :param oldvalue: the previous value being replaced. This
  1850. may also be the symbol ``NEVER_SET`` or ``NO_VALUE``.
  1851. If the listener is registered with ``active_history=True``,
  1852. the previous value of the attribute will be loaded from
  1853. the database if the existing value is currently unloaded
  1854. or expired.
  1855. :param initiator: An instance of :class:`.attributes.Event`
  1856. representing the initiation of the event. May be modified
  1857. from its original value by backref handlers in order to control
  1858. chained event propagation.
  1859. .. versionchanged:: 0.9.0 the ``initiator`` argument is now
  1860. passed as a :class:`.attributes.Event` object, and may be
  1861. modified by backref handlers within a chain of backref-linked
  1862. events.
  1863. :return: if the event was registered with ``retval=True``,
  1864. the given value, or a new effective value, should be returned.
  1865. .. seealso::
  1866. :class:`.AttributeEvents` - background on listener options such
  1867. as propagation to subclasses.
  1868. """
  1869. def init_scalar(self, target, value, dict_):
  1870. r"""Receive a scalar "init" event.
  1871. This event is invoked when an uninitialized, unpersisted scalar
  1872. attribute is accessed, e.g. read::
  1873. x = my_object.some_attribute
  1874. The ORM's default behavior when this occurs for an un-initialized
  1875. attribute is to return the value ``None``; note this differs from
  1876. Python's usual behavior of raising ``AttributeError``. The
  1877. event here can be used to customize what value is actually returned,
  1878. with the assumption that the event listener would be mirroring
  1879. a default generator that is configured on the Core
  1880. :class:`_schema.Column`
  1881. object as well.
  1882. Since a default generator on a :class:`_schema.Column`
  1883. might also produce
  1884. a changing value such as a timestamp, the
  1885. :meth:`.AttributeEvents.init_scalar`
  1886. event handler can also be used to **set** the newly returned value, so
  1887. that a Core-level default generation function effectively fires off
  1888. only once, but at the moment the attribute is accessed on the
  1889. non-persisted object. Normally, no change to the object's state
  1890. is made when an uninitialized attribute is accessed (much older
  1891. SQLAlchemy versions did in fact change the object's state).
  1892. If a default generator on a column returned a particular constant,
  1893. a handler might be used as follows::
  1894. SOME_CONSTANT = 3.1415926
  1895. class MyClass(Base):
  1896. # ...
  1897. some_attribute = Column(Numeric, default=SOME_CONSTANT)
  1898. @event.listens_for(
  1899. MyClass.some_attribute, "init_scalar",
  1900. retval=True, propagate=True)
  1901. def _init_some_attribute(target, dict_, value):
  1902. dict_['some_attribute'] = SOME_CONSTANT
  1903. return SOME_CONSTANT
  1904. Above, we initialize the attribute ``MyClass.some_attribute`` to the
  1905. value of ``SOME_CONSTANT``. The above code includes the following
  1906. features:
  1907. * By setting the value ``SOME_CONSTANT`` in the given ``dict_``,
  1908. we indicate that this value is to be persisted to the database.
  1909. This supersedes the use of ``SOME_CONSTANT`` in the default generator
  1910. for the :class:`_schema.Column`. The ``active_column_defaults.py``
  1911. example given at :ref:`examples_instrumentation` illustrates using
  1912. the same approach for a changing default, e.g. a timestamp
  1913. generator. In this particular example, it is not strictly
  1914. necessary to do this since ``SOME_CONSTANT`` would be part of the
  1915. INSERT statement in either case.
  1916. * By establishing the ``retval=True`` flag, the value we return
  1917. from the function will be returned by the attribute getter.
  1918. Without this flag, the event is assumed to be a passive observer
  1919. and the return value of our function is ignored.
  1920. * The ``propagate=True`` flag is significant if the mapped class
  1921. includes inheriting subclasses, which would also make use of this
  1922. event listener. Without this flag, an inheriting subclass will
  1923. not use our event handler.
  1924. In the above example, the attribute set event
  1925. :meth:`.AttributeEvents.set` as well as the related validation feature
  1926. provided by :obj:`_orm.validates` is **not** invoked when we apply our
  1927. value to the given ``dict_``. To have these events to invoke in
  1928. response to our newly generated value, apply the value to the given
  1929. object as a normal attribute set operation::
  1930. SOME_CONSTANT = 3.1415926
  1931. @event.listens_for(
  1932. MyClass.some_attribute, "init_scalar",
  1933. retval=True, propagate=True)
  1934. def _init_some_attribute(target, dict_, value):
  1935. # will also fire off attribute set events
  1936. target.some_attribute = SOME_CONSTANT
  1937. return SOME_CONSTANT
  1938. When multiple listeners are set up, the generation of the value
  1939. is "chained" from one listener to the next by passing the value
  1940. returned by the previous listener that specifies ``retval=True``
  1941. as the ``value`` argument of the next listener.
  1942. .. versionadded:: 1.1
  1943. :param target: the object instance receiving the event.
  1944. If the listener is registered with ``raw=True``, this will
  1945. be the :class:`.InstanceState` object.
  1946. :param value: the value that is to be returned before this event
  1947. listener were invoked. This value begins as the value ``None``,
  1948. however will be the return value of the previous event handler
  1949. function if multiple listeners are present.
  1950. :param dict\_: the attribute dictionary of this mapped object.
  1951. This is normally the ``__dict__`` of the object, but in all cases
  1952. represents the destination that the attribute system uses to get
  1953. at the actual value of this attribute. Placing the value in this
  1954. dictionary has the effect that the value will be used in the
  1955. INSERT statement generated by the unit of work.
  1956. .. seealso::
  1957. :meth:`.AttributeEvents.init_collection` - collection version
  1958. of this event
  1959. :class:`.AttributeEvents` - background on listener options such
  1960. as propagation to subclasses.
  1961. :ref:`examples_instrumentation` - see the
  1962. ``active_column_defaults.py`` example.
  1963. """
  1964. def init_collection(self, target, collection, collection_adapter):
  1965. """Receive a 'collection init' event.
  1966. This event is triggered for a collection-based attribute, when
  1967. the initial "empty collection" is first generated for a blank
  1968. attribute, as well as for when the collection is replaced with
  1969. a new one, such as via a set event.
  1970. E.g., given that ``User.addresses`` is a relationship-based
  1971. collection, the event is triggered here::
  1972. u1 = User()
  1973. u1.addresses.append(a1) # <- new collection
  1974. and also during replace operations::
  1975. u1.addresses = [a2, a3] # <- new collection
  1976. :param target: the object instance receiving the event.
  1977. If the listener is registered with ``raw=True``, this will
  1978. be the :class:`.InstanceState` object.
  1979. :param collection: the new collection. This will always be generated
  1980. from what was specified as
  1981. :paramref:`_orm.relationship.collection_class`, and will always
  1982. be empty.
  1983. :param collection_adapter: the :class:`.CollectionAdapter` that will
  1984. mediate internal access to the collection.
  1985. .. versionadded:: 1.0.0 :meth:`.AttributeEvents.init_collection`
  1986. and :meth:`.AttributeEvents.dispose_collection` events.
  1987. .. seealso::
  1988. :class:`.AttributeEvents` - background on listener options such
  1989. as propagation to subclasses.
  1990. :meth:`.AttributeEvents.init_scalar` - "scalar" version of this
  1991. event.
  1992. """
  1993. def dispose_collection(self, target, collection, collection_adapter):
  1994. """Receive a 'collection dispose' event.
  1995. This event is triggered for a collection-based attribute when
  1996. a collection is replaced, that is::
  1997. u1.addresses.append(a1)
  1998. u1.addresses = [a2, a3] # <- old collection is disposed
  1999. The old collection received will contain its previous contents.
  2000. .. versionchanged:: 1.2 The collection passed to
  2001. :meth:`.AttributeEvents.dispose_collection` will now have its
  2002. contents before the dispose intact; previously, the collection
  2003. would be empty.
  2004. .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection`
  2005. and :meth:`.AttributeEvents.dispose_collection` events.
  2006. .. seealso::
  2007. :class:`.AttributeEvents` - background on listener options such
  2008. as propagation to subclasses.
  2009. """
  2010. def modified(self, target, initiator):
  2011. """Receive a 'modified' event.
  2012. This event is triggered when the :func:`.attributes.flag_modified`
  2013. function is used to trigger a modify event on an attribute without
  2014. any specific value being set.
  2015. .. versionadded:: 1.2
  2016. :param target: the object instance receiving the event.
  2017. If the listener is registered with ``raw=True``, this will
  2018. be the :class:`.InstanceState` object.
  2019. :param initiator: An instance of :class:`.attributes.Event`
  2020. representing the initiation of the event.
  2021. .. seealso::
  2022. :class:`.AttributeEvents` - background on listener options such
  2023. as propagation to subclasses.
  2024. """
  2025. class QueryEvents(event.Events):
  2026. """Represent events within the construction of a :class:`_query.Query`
  2027. object.
  2028. The :class:`_orm.QueryEvents` hooks are now superseded by the
  2029. :meth:`_orm.SessionEvents.do_orm_execute` event hook.
  2030. """
  2031. _target_class_doc = "SomeQuery"
  2032. _dispatch_target = Query
  2033. def before_compile(self, query):
  2034. """Receive the :class:`_query.Query`
  2035. object before it is composed into a
  2036. core :class:`_expression.Select` object.
  2037. .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile` event
  2038. is superseded by the much more capable
  2039. :meth:`_orm.SessionEvents.do_orm_execute` hook. In version 1.4,
  2040. the :meth:`_orm.QueryEvents.before_compile` event is **no longer
  2041. used** for ORM-level attribute loads, such as loads of deferred
  2042. or expired attributes as well as relationship loaders. See the
  2043. new examples in :ref:`examples_session_orm_events` which
  2044. illustrate new ways of intercepting and modifying ORM queries
  2045. for the most common purpose of adding arbitrary filter criteria.
  2046. This event is intended to allow changes to the query given::
  2047. @event.listens_for(Query, "before_compile", retval=True)
  2048. def no_deleted(query):
  2049. for desc in query.column_descriptions:
  2050. if desc['type'] is User:
  2051. entity = desc['entity']
  2052. query = query.filter(entity.deleted == False)
  2053. return query
  2054. The event should normally be listened with the ``retval=True``
  2055. parameter set, so that the modified query may be returned.
  2056. The :meth:`.QueryEvents.before_compile` event by default
  2057. will disallow "baked" queries from caching a query, if the event
  2058. hook returns a new :class:`_query.Query` object.
  2059. This affects both direct
  2060. use of the baked query extension as well as its operation within
  2061. lazy loaders and eager loaders for relationships. In order to
  2062. re-establish the query being cached, apply the event adding the
  2063. ``bake_ok`` flag::
  2064. @event.listens_for(
  2065. Query, "before_compile", retval=True, bake_ok=True)
  2066. def my_event(query):
  2067. for desc in query.column_descriptions:
  2068. if desc['type'] is User:
  2069. entity = desc['entity']
  2070. query = query.filter(entity.deleted == False)
  2071. return query
  2072. When ``bake_ok`` is set to True, the event hook will only be invoked
  2073. once, and not called for subsequent invocations of a particular query
  2074. that is being cached.
  2075. .. versionadded:: 1.3.11 - added the "bake_ok" flag to the
  2076. :meth:`.QueryEvents.before_compile` event and disallowed caching via
  2077. the "baked" extension from occurring for event handlers that
  2078. return a new :class:`_query.Query` object if this flag is not set.
  2079. .. seealso::
  2080. :meth:`.QueryEvents.before_compile_update`
  2081. :meth:`.QueryEvents.before_compile_delete`
  2082. :ref:`baked_with_before_compile`
  2083. """
  2084. def before_compile_update(self, query, update_context):
  2085. """Allow modifications to the :class:`_query.Query` object within
  2086. :meth:`_query.Query.update`.
  2087. .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile_update`
  2088. event is superseded by the much more capable
  2089. :meth:`_orm.SessionEvents.do_orm_execute` hook.
  2090. Like the :meth:`.QueryEvents.before_compile` event, if the event
  2091. is to be used to alter the :class:`_query.Query` object, it should
  2092. be configured with ``retval=True``, and the modified
  2093. :class:`_query.Query` object returned, as in ::
  2094. @event.listens_for(Query, "before_compile_update", retval=True)
  2095. def no_deleted(query, update_context):
  2096. for desc in query.column_descriptions:
  2097. if desc['type'] is User:
  2098. entity = desc['entity']
  2099. query = query.filter(entity.deleted == False)
  2100. update_context.values['timestamp'] = datetime.utcnow()
  2101. return query
  2102. The ``.values`` dictionary of the "update context" object can also
  2103. be modified in place as illustrated above.
  2104. :param query: a :class:`_query.Query` instance; this is also
  2105. the ``.query`` attribute of the given "update context"
  2106. object.
  2107. :param update_context: an "update context" object which is
  2108. the same kind of object as described in
  2109. :paramref:`.QueryEvents.after_bulk_update.update_context`.
  2110. The object has a ``.values`` attribute in an UPDATE context which is
  2111. the dictionary of parameters passed to :meth:`_query.Query.update`.
  2112. This
  2113. dictionary can be modified to alter the VALUES clause of the
  2114. resulting UPDATE statement.
  2115. .. versionadded:: 1.2.17
  2116. .. seealso::
  2117. :meth:`.QueryEvents.before_compile`
  2118. :meth:`.QueryEvents.before_compile_delete`
  2119. """
  2120. def before_compile_delete(self, query, delete_context):
  2121. """Allow modifications to the :class:`_query.Query` object within
  2122. :meth:`_query.Query.delete`.
  2123. .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile_delete`
  2124. event is superseded by the much more capable
  2125. :meth:`_orm.SessionEvents.do_orm_execute` hook.
  2126. Like the :meth:`.QueryEvents.before_compile` event, this event
  2127. should be configured with ``retval=True``, and the modified
  2128. :class:`_query.Query` object returned, as in ::
  2129. @event.listens_for(Query, "before_compile_delete", retval=True)
  2130. def no_deleted(query, delete_context):
  2131. for desc in query.column_descriptions:
  2132. if desc['type'] is User:
  2133. entity = desc['entity']
  2134. query = query.filter(entity.deleted == False)
  2135. return query
  2136. :param query: a :class:`_query.Query` instance; this is also
  2137. the ``.query`` attribute of the given "delete context"
  2138. object.
  2139. :param delete_context: a "delete context" object which is
  2140. the same kind of object as described in
  2141. :paramref:`.QueryEvents.after_bulk_delete.delete_context`.
  2142. .. versionadded:: 1.2.17
  2143. .. seealso::
  2144. :meth:`.QueryEvents.before_compile`
  2145. :meth:`.QueryEvents.before_compile_update`
  2146. """
  2147. @classmethod
  2148. def _listen(cls, event_key, retval=False, bake_ok=False, **kw):
  2149. fn = event_key._listen_fn
  2150. if not retval:
  2151. def wrap(*arg, **kw):
  2152. if not retval:
  2153. query = arg[0]
  2154. fn(*arg, **kw)
  2155. return query
  2156. else:
  2157. return fn(*arg, **kw)
  2158. event_key = event_key.with_wrapper(wrap)
  2159. else:
  2160. # don't assume we can apply an attribute to the callable
  2161. def wrap(*arg, **kw):
  2162. return fn(*arg, **kw)
  2163. event_key = event_key.with_wrapper(wrap)
  2164. wrap._bake_ok = bake_ok
  2165. event_key.base_listen(**kw)