events.py 110 KB

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