events.py 125 KB

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