events.py 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255
  1. # orm/events.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """ORM event interfaces.
  8. """
  9. 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(
  376. SomeClass, "load", restore_load_context=True)
  377. def on_load(instance, context):
  378. instance.some_unloaded_attribute
  379. .. versionchanged:: 1.3.14 Added
  380. :paramref:`.InstanceEvents.restore_load_context`
  381. and :paramref:`.SessionEvents.restore_load_context` flags which
  382. apply to "on load" events, which will ensure that the loading
  383. context for an object is restored when the event hook is
  384. complete; a warning is emitted if the load context of the object
  385. changes without this flag being set.
  386. The :meth:`.InstanceEvents.load` event is also available in a
  387. class-method decorator format called :func:`_orm.reconstructor`.
  388. :param target: the mapped instance. If
  389. the event is configured with ``raw=True``, this will
  390. instead be the :class:`.InstanceState` state-management
  391. object associated with the instance.
  392. :param context: the :class:`.QueryContext` corresponding to the
  393. current :class:`_query.Query` in progress. This argument may be
  394. ``None`` if the load does not correspond to a :class:`_query.Query`,
  395. such as during :meth:`.Session.merge`.
  396. .. seealso::
  397. :meth:`.InstanceEvents.init`
  398. :meth:`.InstanceEvents.refresh`
  399. :meth:`.SessionEvents.loaded_as_persistent`
  400. :ref:`mapping_constructors`
  401. """
  402. def refresh(
  403. self, target: _O, context: QueryContext, attrs: Optional[Iterable[str]]
  404. ) -> None:
  405. """Receive an object instance after one or more attributes have
  406. been refreshed from a query.
  407. Contrast this to the :meth:`.InstanceEvents.load` method, which
  408. is invoked when the object is first loaded from a query.
  409. .. note:: This event is invoked within the loader process before
  410. eager loaders may have been completed, and the object's state may
  411. not be complete. Additionally, invoking row-level refresh
  412. operations on the object will place the object into a new loader
  413. context, interfering with the existing load context. See the note
  414. on :meth:`.InstanceEvents.load` for background on making use of the
  415. :paramref:`.InstanceEvents.restore_load_context` parameter, in
  416. order to resolve this scenario.
  417. :param target: the mapped instance. If
  418. the event is configured with ``raw=True``, this will
  419. instead be the :class:`.InstanceState` state-management
  420. object associated with the instance.
  421. :param context: the :class:`.QueryContext` corresponding to the
  422. current :class:`_query.Query` in progress.
  423. :param attrs: sequence of attribute names which
  424. were populated, or None if all column-mapped, non-deferred
  425. attributes were populated.
  426. .. seealso::
  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:`orm_server_defaults`
  463. :ref:`metadata_defaults_toplevel`
  464. """
  465. def expire(self, target: _O, attrs: Optional[Iterable[str]]) -> None:
  466. """Receive an object instance after its attributes or some subset
  467. have been expired.
  468. 'keys' is a list of attribute names. If None, the entire
  469. state was expired.
  470. :param target: the mapped instance. If
  471. the event is configured with ``raw=True``, this will
  472. instead be the :class:`.InstanceState` state-management
  473. object associated with the instance.
  474. :param attrs: sequence of attribute
  475. names which were expired, or None if all attributes were
  476. expired.
  477. """
  478. def pickle(self, target: _O, state_dict: _InstanceDict) -> None:
  479. """Receive an object instance when its associated state is
  480. being pickled.
  481. :param target: the mapped instance. If
  482. the event is configured with ``raw=True``, this will
  483. instead be the :class:`.InstanceState` state-management
  484. object associated with the instance.
  485. :param state_dict: the dictionary returned by
  486. :class:`.InstanceState.__getstate__`, containing the state
  487. to be pickled.
  488. """
  489. def unpickle(self, target: _O, state_dict: _InstanceDict) -> None:
  490. """Receive an object instance after its associated state has
  491. been unpickled.
  492. :param target: the mapped instance. If
  493. the event is configured with ``raw=True``, this will
  494. instead be the :class:`.InstanceState` state-management
  495. object associated with the instance.
  496. :param state_dict: the dictionary sent to
  497. :class:`.InstanceState.__setstate__`, containing the state
  498. dictionary which was pickled.
  499. """
  500. class _EventsHold(event.RefCollection[_ET]):
  501. """Hold onto listeners against unmapped, uninstrumented classes.
  502. Establish _listen() for that class' mapper/instrumentation when
  503. those objects are created for that class.
  504. """
  505. all_holds: weakref.WeakKeyDictionary[Any, Any]
  506. def __init__(
  507. self,
  508. class_: Union[DeclarativeAttributeIntercept, DeclarativeMeta, type],
  509. ) -> None:
  510. self.class_ = class_
  511. @classmethod
  512. def _clear(cls) -> None:
  513. cls.all_holds.clear()
  514. class HoldEvents(Generic[_ET2]):
  515. _dispatch_target: Optional[Type[_ET2]] = None
  516. @classmethod
  517. def _listen(
  518. cls,
  519. event_key: _EventKey[_ET2],
  520. raw: bool = False,
  521. propagate: bool = False,
  522. retval: bool = False,
  523. **kw: Any,
  524. ) -> None:
  525. target = event_key.dispatch_target
  526. if target.class_ in target.all_holds:
  527. collection = target.all_holds[target.class_]
  528. else:
  529. collection = target.all_holds[target.class_] = {}
  530. event.registry._stored_in_collection(event_key, target)
  531. collection[event_key._key] = (
  532. event_key,
  533. raw,
  534. propagate,
  535. retval,
  536. kw,
  537. )
  538. if propagate:
  539. stack = list(target.class_.__subclasses__())
  540. while stack:
  541. subclass = stack.pop(0)
  542. stack.extend(subclass.__subclasses__())
  543. subject = target.resolve(subclass)
  544. if subject is not None:
  545. # we are already going through __subclasses__()
  546. # so leave generic propagate flag False
  547. event_key.with_dispatch_target(subject).listen(
  548. raw=raw, propagate=False, retval=retval, **kw
  549. )
  550. def remove(self, event_key: _EventKey[_ET]) -> None:
  551. target = event_key.dispatch_target
  552. if isinstance(target, _EventsHold):
  553. collection = target.all_holds[target.class_]
  554. del collection[event_key._key]
  555. @classmethod
  556. def populate(
  557. cls,
  558. class_: Union[DeclarativeAttributeIntercept, DeclarativeMeta, type],
  559. subject: Union[ClassManager[_O], Mapper[_O]],
  560. ) -> None:
  561. for subclass in class_.__mro__:
  562. if subclass in cls.all_holds:
  563. collection = cls.all_holds[subclass]
  564. for (
  565. event_key,
  566. raw,
  567. propagate,
  568. retval,
  569. kw,
  570. ) in collection.values():
  571. if propagate or subclass is class_:
  572. # since we can't be sure in what order different
  573. # classes in a hierarchy are triggered with
  574. # populate(), we rely upon _EventsHold for all event
  575. # assignment, instead of using the generic propagate
  576. # flag.
  577. event_key.with_dispatch_target(subject).listen(
  578. raw=raw, propagate=False, retval=retval, **kw
  579. )
  580. class _InstanceEventsHold(_EventsHold[_ET]):
  581. all_holds: weakref.WeakKeyDictionary[
  582. Any, Any
  583. ] = weakref.WeakKeyDictionary()
  584. def resolve(self, class_: Type[_O]) -> Optional[ClassManager[_O]]:
  585. return instrumentation.opt_manager_of_class(class_)
  586. class HoldInstanceEvents(_EventsHold.HoldEvents[_ET], InstanceEvents): # type: ignore [misc] # noqa: E501
  587. pass
  588. dispatch = event.dispatcher(HoldInstanceEvents)
  589. class MapperEvents(event.Events[mapperlib.Mapper[Any]]):
  590. """Define events specific to mappings.
  591. e.g.::
  592. from sqlalchemy import event
  593. def my_before_insert_listener(mapper, connection, target):
  594. # execute a stored procedure upon INSERT,
  595. # apply the value to the row to be inserted
  596. target.calculated_value = connection.execute(
  597. text("select my_special_function(%d)" % target.special_number)
  598. ).scalar()
  599. # associate the listener function with SomeClass,
  600. # to execute during the "before_insert" hook
  601. event.listen(
  602. 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 he "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", retval=True, propagate=True)
  809. def dont_configure(mapper, cls):
  810. return EXT_SKIP
  811. .. seealso::
  812. :meth:`.MapperEvents.before_configured`
  813. :meth:`.MapperEvents.after_configured`
  814. :meth:`.MapperEvents.mapper_configured`
  815. """
  816. def mapper_configured(self, mapper: Mapper[_O], class_: Type[_O]) -> None:
  817. r"""Called when a specific mapper has completed its own configuration
  818. within the scope of the :func:`.configure_mappers` call.
  819. The :meth:`.MapperEvents.mapper_configured` event is invoked
  820. for each mapper that is encountered when the
  821. :func:`_orm.configure_mappers` function proceeds through the current
  822. list of not-yet-configured mappers.
  823. :func:`_orm.configure_mappers` is typically invoked
  824. automatically as mappings are first used, as well as each time
  825. new mappers have been made available and new mapper use is
  826. detected.
  827. When the event is called, the mapper should be in its final
  828. state, but **not including backrefs** that may be invoked from
  829. other mappers; they might still be pending within the
  830. configuration operation. Bidirectional relationships that
  831. are instead configured via the
  832. :paramref:`.orm.relationship.back_populates` argument
  833. *will* be fully available, since this style of relationship does not
  834. rely upon other possibly-not-configured mappers to know that they
  835. exist.
  836. For an event that is guaranteed to have **all** mappers ready
  837. to go including backrefs that are defined only on other
  838. mappings, use the :meth:`.MapperEvents.after_configured`
  839. event; this event invokes only after all known mappings have been
  840. fully configured.
  841. The :meth:`.MapperEvents.mapper_configured` event, unlike
  842. :meth:`.MapperEvents.before_configured` or
  843. :meth:`.MapperEvents.after_configured`,
  844. is called for each mapper/class individually, and the mapper is
  845. passed to the event itself. It also is called exactly once for
  846. a particular mapper. The event is therefore useful for
  847. configurational steps that benefit from being invoked just once
  848. on a specific mapper basis, which don't require that "backref"
  849. configurations are necessarily ready yet.
  850. :param mapper: the :class:`_orm.Mapper` which is the target
  851. of this event.
  852. :param class\_: the mapped class.
  853. .. seealso::
  854. :meth:`.MapperEvents.before_configured`
  855. :meth:`.MapperEvents.after_configured`
  856. :meth:`.MapperEvents.before_mapper_configured`
  857. """
  858. # TODO: need coverage for this event
  859. def before_configured(self) -> None:
  860. """Called before a series of mappers have been configured.
  861. The :meth:`.MapperEvents.before_configured` event is invoked
  862. each time the :func:`_orm.configure_mappers` function is
  863. invoked, before the function has done any of its work.
  864. :func:`_orm.configure_mappers` is typically invoked
  865. automatically as mappings are first used, as well as each time
  866. new mappers have been made available and new mapper use is
  867. detected.
  868. This event can **only** be applied to the :class:`_orm.Mapper` class,
  869. and not to individual mappings or mapped classes. It is only invoked
  870. for all mappings as a whole::
  871. from sqlalchemy.orm import Mapper
  872. @event.listens_for(Mapper, "before_configured")
  873. def go():
  874. ...
  875. Contrast this event to :meth:`.MapperEvents.after_configured`,
  876. which is invoked after the series of mappers has been configured,
  877. as well as :meth:`.MapperEvents.before_mapper_configured`
  878. and :meth:`.MapperEvents.mapper_configured`, which are both invoked
  879. on a per-mapper basis.
  880. Theoretically this event is called once per
  881. application, but is actually called any time new mappers
  882. are to be affected by a :func:`_orm.configure_mappers`
  883. call. If new mappings are constructed after existing ones have
  884. already been used, this event will likely be called again. To ensure
  885. that a particular event is only called once and no further, the
  886. ``once=True`` argument (new in 0.9.4) can be applied::
  887. from sqlalchemy.orm import mapper
  888. @event.listens_for(mapper, "before_configured", once=True)
  889. def go():
  890. ...
  891. .. seealso::
  892. :meth:`.MapperEvents.before_mapper_configured`
  893. :meth:`.MapperEvents.mapper_configured`
  894. :meth:`.MapperEvents.after_configured`
  895. """
  896. def after_configured(self) -> None:
  897. """Called after a series of mappers have been configured.
  898. The :meth:`.MapperEvents.after_configured` event is invoked
  899. each time the :func:`_orm.configure_mappers` function is
  900. invoked, after the function has completed its work.
  901. :func:`_orm.configure_mappers` is typically invoked
  902. automatically as mappings are first used, as well as each time
  903. new mappers have been made available and new mapper use is
  904. detected.
  905. Contrast this event to the :meth:`.MapperEvents.mapper_configured`
  906. event, which is called on a per-mapper basis while the configuration
  907. operation proceeds; unlike that event, when this event is invoked,
  908. all cross-configurations (e.g. backrefs) will also have been made
  909. available for any mappers that were pending.
  910. Also contrast to :meth:`.MapperEvents.before_configured`,
  911. which is invoked before the series of mappers has been configured.
  912. This event can **only** be applied to the :class:`_orm.Mapper` class,
  913. and not to individual mappings or
  914. mapped classes. It is only invoked for all mappings as a whole::
  915. from sqlalchemy.orm import Mapper
  916. @event.listens_for(Mapper, "after_configured")
  917. def go():
  918. # ...
  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. # ...
  930. .. seealso::
  931. :meth:`.MapperEvents.before_mapper_configured`
  932. :meth:`.MapperEvents.mapper_configured`
  933. :meth:`.MapperEvents.before_configured`
  934. """
  935. def before_insert(
  936. self, mapper: Mapper[_O], connection: Connection, target: _O
  937. ) -> None:
  938. """Receive an object instance before an INSERT statement
  939. is emitted corresponding to that instance.
  940. .. note:: this event **only** applies to the
  941. :ref:`session flush operation <session_flushing>`
  942. and does **not** apply to the ORM DML operations described at
  943. :ref:`orm_expression_update_delete`. To intercept ORM
  944. DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.
  945. This event is used to modify local, non-object related
  946. attributes on the instance before an INSERT occurs, as well
  947. as to emit additional SQL statements on the given
  948. connection.
  949. The event is often called for a batch of objects of the
  950. same class before their INSERT statements are emitted at
  951. once in a later step. In the extremely rare case that
  952. this is not desirable, the :class:`_orm.Mapper` object can be
  953. configured with ``batch=False``, which will cause
  954. batches of instances to be broken up into individual
  955. (and more poorly performing) event->persist->event
  956. steps.
  957. .. warning::
  958. Mapper-level flush events only allow **very limited operations**,
  959. on attributes local to the row being operated upon only,
  960. as well as allowing any SQL to be emitted on the given
  961. :class:`_engine.Connection`. **Please read fully** the notes
  962. at :ref:`session_persistence_mapper` for guidelines on using
  963. these methods; generally, the :meth:`.SessionEvents.before_flush`
  964. method should be preferred for general on-flush changes.
  965. :param mapper: the :class:`_orm.Mapper` which is the target
  966. of this event.
  967. :param connection: the :class:`_engine.Connection` being used to
  968. emit INSERT statements for this instance. This
  969. provides a handle into the current transaction on the
  970. target database specific to this instance.
  971. :param target: the mapped instance being persisted. If
  972. the event is configured with ``raw=True``, this will
  973. instead be the :class:`.InstanceState` state-management
  974. object associated with the instance.
  975. :return: No return value is supported by this event.
  976. .. seealso::
  977. :ref:`session_persistence_events`
  978. """
  979. def after_insert(
  980. self, mapper: Mapper[_O], connection: Connection, target: _O
  981. ) -> None:
  982. """Receive an object instance after an INSERT statement
  983. is emitted corresponding to that instance.
  984. .. note:: this event **only** applies to the
  985. :ref:`session flush operation <session_flushing>`
  986. and does **not** apply to the ORM DML operations described at
  987. :ref:`orm_expression_update_delete`. To intercept ORM
  988. DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.
  989. This event is used to modify in-Python-only
  990. state on the instance after an INSERT occurs, as well
  991. as to emit additional SQL statements on the given
  992. connection.
  993. The event is often called for a batch of objects of the
  994. same class after their INSERT statements have been
  995. emitted at once in a previous step. In the extremely
  996. rare case that this is not desirable, the
  997. :class:`_orm.Mapper` object can be configured with ``batch=False``,
  998. which will cause batches of instances to be broken up
  999. into individual (and more poorly performing)
  1000. event->persist->event steps.
  1001. .. warning::
  1002. Mapper-level flush events only allow **very limited operations**,
  1003. on attributes local to the row being operated upon only,
  1004. as well as allowing any SQL to be emitted on the given
  1005. :class:`_engine.Connection`. **Please read fully** the notes
  1006. at :ref:`session_persistence_mapper` for guidelines on using
  1007. these methods; generally, the :meth:`.SessionEvents.before_flush`
  1008. method should be preferred for general on-flush changes.
  1009. :param mapper: the :class:`_orm.Mapper` which is the target
  1010. of this event.
  1011. :param connection: the :class:`_engine.Connection` being used to
  1012. emit INSERT statements for this instance. This
  1013. provides a handle into the current transaction on the
  1014. target database specific to this instance.
  1015. :param target: the mapped instance being persisted. If
  1016. the event is configured with ``raw=True``, this will
  1017. instead be the :class:`.InstanceState` state-management
  1018. object associated with the instance.
  1019. :return: No return value is supported by this event.
  1020. .. seealso::
  1021. :ref:`session_persistence_events`
  1022. """
  1023. def before_update(
  1024. self, mapper: Mapper[_O], connection: Connection, target: _O
  1025. ) -> None:
  1026. """Receive an object instance before an UPDATE statement
  1027. is emitted corresponding to that instance.
  1028. .. note:: this event **only** applies to the
  1029. :ref:`session flush operation <session_flushing>`
  1030. and does **not** apply to the ORM DML operations described at
  1031. :ref:`orm_expression_update_delete`. To intercept ORM
  1032. DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.
  1033. This event is used to modify local, non-object related
  1034. attributes on the instance before an UPDATE occurs, as well
  1035. as to emit additional SQL statements on the given
  1036. connection.
  1037. This method is called for all instances that are
  1038. marked as "dirty", *even those which have no net changes
  1039. to their column-based attributes*. An object is marked
  1040. as dirty when any of its column-based attributes have a
  1041. "set attribute" operation called or when any of its
  1042. collections are modified. If, at update time, no
  1043. column-based attributes have any net changes, no UPDATE
  1044. statement will be issued. This means that an instance
  1045. being sent to :meth:`~.MapperEvents.before_update` is
  1046. *not* a guarantee that an UPDATE statement will be
  1047. issued, although you can affect the outcome here by
  1048. modifying attributes so that a net change in value does
  1049. exist.
  1050. To detect if the column-based attributes on the object have net
  1051. changes, and will therefore generate an UPDATE statement, use
  1052. ``object_session(instance).is_modified(instance,
  1053. include_collections=False)``.
  1054. The event is often called for a batch of objects of the
  1055. same class before their UPDATE statements are emitted at
  1056. once in a later step. In the extremely rare case that
  1057. this is not desirable, the :class:`_orm.Mapper` can be
  1058. configured with ``batch=False``, which will cause
  1059. batches of instances to be broken up into individual
  1060. (and more poorly performing) event->persist->event
  1061. steps.
  1062. .. warning::
  1063. Mapper-level flush events only allow **very limited operations**,
  1064. on attributes local to the row being operated upon only,
  1065. as well as allowing any SQL to be emitted on the given
  1066. :class:`_engine.Connection`. **Please read fully** the notes
  1067. at :ref:`session_persistence_mapper` for guidelines on using
  1068. these methods; generally, the :meth:`.SessionEvents.before_flush`
  1069. method should be preferred for general on-flush changes.
  1070. :param mapper: the :class:`_orm.Mapper` which is the target
  1071. of this event.
  1072. :param connection: the :class:`_engine.Connection` being used to
  1073. emit UPDATE statements for this instance. This
  1074. provides a handle into the current transaction on the
  1075. target database specific to this instance.
  1076. :param target: the mapped instance being persisted. If
  1077. the event is configured with ``raw=True``, this will
  1078. instead be the :class:`.InstanceState` state-management
  1079. object associated with the instance.
  1080. :return: No return value is supported by this event.
  1081. .. seealso::
  1082. :ref:`session_persistence_events`
  1083. """
  1084. def after_update(
  1085. self, mapper: Mapper[_O], connection: Connection, target: _O
  1086. ) -> None:
  1087. """Receive an object instance after an UPDATE statement
  1088. is emitted corresponding to that instance.
  1089. .. note:: this event **only** applies to the
  1090. :ref:`session flush operation <session_flushing>`
  1091. and does **not** apply to the ORM DML operations described at
  1092. :ref:`orm_expression_update_delete`. To intercept ORM
  1093. DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.
  1094. This event is used to modify in-Python-only
  1095. state on the instance after an UPDATE occurs, as well
  1096. as to emit additional SQL statements on the given
  1097. connection.
  1098. This method is called for all instances that are
  1099. marked as "dirty", *even those which have no net changes
  1100. to their column-based attributes*, and for which
  1101. no UPDATE statement has proceeded. An object is marked
  1102. as dirty when any of its column-based attributes have a
  1103. "set attribute" operation called or when any of its
  1104. collections are modified. If, at update time, no
  1105. column-based attributes have any net changes, no UPDATE
  1106. statement will be issued. This means that an instance
  1107. being sent to :meth:`~.MapperEvents.after_update` is
  1108. *not* a guarantee that an UPDATE statement has been
  1109. issued.
  1110. To detect if the column-based attributes on the object have net
  1111. changes, and therefore resulted in an UPDATE statement, use
  1112. ``object_session(instance).is_modified(instance,
  1113. include_collections=False)``.
  1114. The event is often called for a batch of objects of the
  1115. same class after their UPDATE statements have been emitted at
  1116. once in a previous step. In the extremely rare case that
  1117. this is not desirable, the :class:`_orm.Mapper` can be
  1118. configured with ``batch=False``, which will cause
  1119. batches of instances to be broken up into individual
  1120. (and more poorly performing) event->persist->event
  1121. steps.
  1122. .. warning::
  1123. Mapper-level flush events only allow **very limited operations**,
  1124. on attributes local to the row being operated upon only,
  1125. as well as allowing any SQL to be emitted on the given
  1126. :class:`_engine.Connection`. **Please read fully** the notes
  1127. at :ref:`session_persistence_mapper` for guidelines on using
  1128. these methods; generally, the :meth:`.SessionEvents.before_flush`
  1129. method should be preferred for general on-flush changes.
  1130. :param mapper: the :class:`_orm.Mapper` which is the target
  1131. of this event.
  1132. :param connection: the :class:`_engine.Connection` being used to
  1133. emit UPDATE statements for this instance. This
  1134. provides a handle into the current transaction on the
  1135. target database specific to this instance.
  1136. :param target: the mapped instance being persisted. If
  1137. the event is configured with ``raw=True``, this will
  1138. instead be the :class:`.InstanceState` state-management
  1139. object associated with the instance.
  1140. :return: No return value is supported by this event.
  1141. .. seealso::
  1142. :ref:`session_persistence_events`
  1143. """
  1144. def before_delete(
  1145. self, mapper: Mapper[_O], connection: Connection, target: _O
  1146. ) -> None:
  1147. """Receive an object instance before a DELETE statement
  1148. is emitted corresponding to that instance.
  1149. .. note:: this event **only** applies to the
  1150. :ref:`session flush operation <session_flushing>`
  1151. and does **not** apply to the ORM DML operations described at
  1152. :ref:`orm_expression_update_delete`. To intercept ORM
  1153. DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.
  1154. This event is used to emit additional SQL statements on
  1155. the given connection as well as to perform application
  1156. specific bookkeeping related to a deletion event.
  1157. The event is often called for a batch of objects of the
  1158. same class before their DELETE statements are emitted at
  1159. once in a later step.
  1160. .. warning::
  1161. Mapper-level flush events only allow **very limited operations**,
  1162. on attributes local to the row being operated upon only,
  1163. as well as allowing any SQL to be emitted on the given
  1164. :class:`_engine.Connection`. **Please read fully** the notes
  1165. at :ref:`session_persistence_mapper` for guidelines on using
  1166. these methods; generally, the :meth:`.SessionEvents.before_flush`
  1167. method should be preferred for general on-flush changes.
  1168. :param mapper: the :class:`_orm.Mapper` which is the target
  1169. of this event.
  1170. :param connection: the :class:`_engine.Connection` being used to
  1171. emit DELETE statements for this instance. This
  1172. provides a handle into the current transaction on the
  1173. target database specific to this instance.
  1174. :param target: the mapped instance being deleted. If
  1175. the event is configured with ``raw=True``, this will
  1176. instead be the :class:`.InstanceState` state-management
  1177. object associated with the instance.
  1178. :return: No return value is supported by this event.
  1179. .. seealso::
  1180. :ref:`session_persistence_events`
  1181. """
  1182. def after_delete(
  1183. self, mapper: Mapper[_O], connection: Connection, target: _O
  1184. ) -> None:
  1185. """Receive an object instance after a DELETE statement
  1186. has been emitted corresponding to that instance.
  1187. .. note:: this event **only** applies to the
  1188. :ref:`session flush operation <session_flushing>`
  1189. and does **not** apply to the ORM DML operations described at
  1190. :ref:`orm_expression_update_delete`. To intercept ORM
  1191. DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.
  1192. This event is used to emit additional SQL statements on
  1193. the given connection as well as to perform application
  1194. specific bookkeeping related to a deletion event.
  1195. The event is often called for a batch of objects of the
  1196. same class after their DELETE statements have been emitted at
  1197. once in a previous step.
  1198. .. warning::
  1199. Mapper-level flush events only allow **very limited operations**,
  1200. on attributes local to the row being operated upon only,
  1201. as well as allowing any SQL to be emitted on the given
  1202. :class:`_engine.Connection`. **Please read fully** the notes
  1203. at :ref:`session_persistence_mapper` for guidelines on using
  1204. these methods; generally, the :meth:`.SessionEvents.before_flush`
  1205. method should be preferred for general on-flush changes.
  1206. :param mapper: the :class:`_orm.Mapper` which is the target
  1207. of this event.
  1208. :param connection: the :class:`_engine.Connection` being used to
  1209. emit DELETE statements for this instance. This
  1210. provides a handle into the current transaction on the
  1211. target database specific to this instance.
  1212. :param target: the mapped instance being deleted. If
  1213. the event is configured with ``raw=True``, this will
  1214. instead be the :class:`.InstanceState` state-management
  1215. object associated with the instance.
  1216. :return: No return value is supported by this event.
  1217. .. seealso::
  1218. :ref:`session_persistence_events`
  1219. """
  1220. class _MapperEventsHold(_EventsHold[_ET]):
  1221. all_holds = weakref.WeakKeyDictionary()
  1222. def resolve(
  1223. self, class_: Union[Type[_T], _InternalEntityType[_T]]
  1224. ) -> Optional[Mapper[_T]]:
  1225. return _mapper_or_none(class_)
  1226. class HoldMapperEvents(_EventsHold.HoldEvents[_ET], MapperEvents): # type: ignore [misc] # noqa: E501
  1227. pass
  1228. dispatch = event.dispatcher(HoldMapperEvents)
  1229. _sessionevents_lifecycle_event_names: Set[str] = set()
  1230. class SessionEvents(event.Events[Session]):
  1231. """Define events specific to :class:`.Session` lifecycle.
  1232. e.g.::
  1233. from sqlalchemy import event
  1234. from sqlalchemy.orm import sessionmaker
  1235. def my_before_commit(session):
  1236. print("before commit!")
  1237. Session = sessionmaker()
  1238. event.listen(Session, "before_commit", my_before_commit)
  1239. The :func:`~.event.listen` function will accept
  1240. :class:`.Session` objects as well as the return result
  1241. of :class:`~.sessionmaker()` and :class:`~.scoped_session()`.
  1242. Additionally, it accepts the :class:`.Session` class which
  1243. will apply listeners to all :class:`.Session` instances
  1244. globally.
  1245. :param raw=False: When True, the "target" argument passed
  1246. to applicable event listener functions that work on individual
  1247. objects will be the instance's :class:`.InstanceState` management
  1248. object, rather than the mapped instance itself.
  1249. .. versionadded:: 1.3.14
  1250. :param restore_load_context=False: Applies to the
  1251. :meth:`.SessionEvents.loaded_as_persistent` event. Restores the loader
  1252. context of the object when the event hook is complete, so that ongoing
  1253. eager load operations continue to target the object appropriately. A
  1254. warning is emitted if the object is moved to a new loader context from
  1255. within this event if this flag is not set.
  1256. .. versionadded:: 1.3.14
  1257. """
  1258. _target_class_doc = "SomeSessionClassOrObject"
  1259. _dispatch_target = Session
  1260. def _lifecycle_event( # type: ignore [misc]
  1261. fn: Callable[[SessionEvents, Session, Any], None]
  1262. ) -> Callable[[SessionEvents, Session, Any], None]:
  1263. _sessionevents_lifecycle_event_names.add(fn.__name__)
  1264. return fn
  1265. @classmethod
  1266. def _accept_with( # type: ignore [return]
  1267. cls, target: Any, identifier: str
  1268. ) -> Union[Session, type]:
  1269. if isinstance(target, scoped_session):
  1270. target = target.session_factory
  1271. if not isinstance(target, sessionmaker) and (
  1272. not isinstance(target, type) or not issubclass(target, Session)
  1273. ):
  1274. raise exc.ArgumentError(
  1275. "Session event listen on a scoped_session "
  1276. "requires that its creation callable "
  1277. "is associated with the Session class."
  1278. )
  1279. if isinstance(target, sessionmaker):
  1280. return target.class_
  1281. elif isinstance(target, type):
  1282. if issubclass(target, scoped_session):
  1283. return Session
  1284. elif issubclass(target, Session):
  1285. return target
  1286. elif isinstance(target, Session):
  1287. return target
  1288. elif hasattr(target, "_no_async_engine_events"):
  1289. target._no_async_engine_events()
  1290. else:
  1291. # allows alternate SessionEvents-like-classes to be consulted
  1292. return event.Events._accept_with(target, identifier) # type: ignore [return-value] # noqa: E501
  1293. @classmethod
  1294. def _listen(
  1295. cls,
  1296. event_key: Any,
  1297. *,
  1298. raw: bool = False,
  1299. restore_load_context: bool = False,
  1300. **kw: Any,
  1301. ) -> None:
  1302. is_instance_event = (
  1303. event_key.identifier in _sessionevents_lifecycle_event_names
  1304. )
  1305. if is_instance_event:
  1306. if not raw or restore_load_context:
  1307. fn = event_key._listen_fn
  1308. def wrap(
  1309. session: Session,
  1310. state: InstanceState[_O],
  1311. *arg: Any,
  1312. **kw: Any,
  1313. ) -> Optional[Any]:
  1314. if not raw:
  1315. target = state.obj()
  1316. if target is None:
  1317. # existing behavior is that if the object is
  1318. # garbage collected, no event is emitted
  1319. return None
  1320. else:
  1321. target = state # type: ignore [assignment]
  1322. if restore_load_context:
  1323. runid = state.runid
  1324. try:
  1325. return fn(session, target, *arg, **kw)
  1326. finally:
  1327. if restore_load_context:
  1328. state.runid = runid
  1329. event_key = event_key.with_wrapper(wrap)
  1330. event_key.base_listen(**kw)
  1331. def do_orm_execute(self, orm_execute_state: ORMExecuteState) -> None:
  1332. """Intercept statement executions that occur on behalf of an
  1333. ORM :class:`.Session` object.
  1334. This event is invoked for all top-level SQL statements invoked from the
  1335. :meth:`_orm.Session.execute` method, as well as related methods such as
  1336. :meth:`_orm.Session.scalars` and :meth:`_orm.Session.scalar`. As of
  1337. SQLAlchemy 1.4, all ORM queries that run through the
  1338. :meth:`_orm.Session.execute` method as well as related methods
  1339. :meth:`_orm.Session.scalars`, :meth:`_orm.Session.scalar` etc.
  1340. will participate in this event.
  1341. This event hook does **not** apply to the queries that are
  1342. emitted internally within the ORM flush process, i.e. the
  1343. process described at :ref:`session_flushing`.
  1344. .. note:: The :meth:`_orm.SessionEvents.do_orm_execute` event hook
  1345. is triggered **for ORM statement executions only**, meaning those
  1346. invoked via the :meth:`_orm.Session.execute` and similar methods on
  1347. the :class:`_orm.Session` object. It does **not** trigger for
  1348. statements that are invoked by SQLAlchemy Core only, i.e. statements
  1349. invoked directly using :meth:`_engine.Connection.execute` or
  1350. otherwise originating from an :class:`_engine.Engine` object without
  1351. any :class:`_orm.Session` involved. To intercept **all** SQL
  1352. executions regardless of whether the Core or ORM APIs are in use,
  1353. see the event hooks at :class:`.ConnectionEvents`, such as
  1354. :meth:`.ConnectionEvents.before_execute` and
  1355. :meth:`.ConnectionEvents.before_cursor_execute`.
  1356. Also, this event hook does **not** apply to queries that are
  1357. emitted internally within the ORM flush process,
  1358. i.e. the process described at :ref:`session_flushing`; to
  1359. intercept steps within the flush process, see the event
  1360. hooks described at :ref:`session_persistence_events` as
  1361. well as :ref:`session_persistence_mapper`.
  1362. This event is a ``do_`` event, meaning it has the capability to replace
  1363. the operation that the :meth:`_orm.Session.execute` method normally
  1364. performs. The intended use for this includes sharding and
  1365. result-caching schemes which may seek to invoke the same statement
  1366. across multiple database connections, returning a result that is
  1367. merged from each of them, or which don't invoke the statement at all,
  1368. instead returning data from a cache.
  1369. The hook intends to replace the use of the
  1370. ``Query._execute_and_instances`` method that could be subclassed prior
  1371. to SQLAlchemy 1.4.
  1372. :param orm_execute_state: an instance of :class:`.ORMExecuteState`
  1373. which contains all information about the current execution, as well
  1374. as helper functions used to derive other commonly required
  1375. information. See that object for details.
  1376. .. seealso::
  1377. :ref:`session_execute_events` - top level documentation on how
  1378. to use :meth:`_orm.SessionEvents.do_orm_execute`
  1379. :class:`.ORMExecuteState` - the object passed to the
  1380. :meth:`_orm.SessionEvents.do_orm_execute` event which contains
  1381. all information about the statement to be invoked. It also
  1382. provides an interface to extend the current statement, options,
  1383. and parameters as well as an option that allows programmatic
  1384. invocation of the statement at any point.
  1385. :ref:`examples_session_orm_events` - includes examples of using
  1386. :meth:`_orm.SessionEvents.do_orm_execute`
  1387. :ref:`examples_caching` - an example of how to integrate
  1388. Dogpile caching with the ORM :class:`_orm.Session` making use
  1389. of the :meth:`_orm.SessionEvents.do_orm_execute` event hook.
  1390. :ref:`examples_sharding` - the Horizontal Sharding example /
  1391. extension relies upon the
  1392. :meth:`_orm.SessionEvents.do_orm_execute` event hook to invoke a
  1393. SQL statement on multiple backends and return a merged result.
  1394. .. versionadded:: 1.4
  1395. """
  1396. def after_transaction_create(
  1397. self, session: Session, transaction: SessionTransaction
  1398. ) -> None:
  1399. """Execute when a new :class:`.SessionTransaction` is created.
  1400. This event differs from :meth:`~.SessionEvents.after_begin`
  1401. in that it occurs for each :class:`.SessionTransaction`
  1402. overall, as opposed to when transactions are begun
  1403. on individual database connections. It is also invoked
  1404. for nested transactions and subtransactions, and is always
  1405. matched by a corresponding
  1406. :meth:`~.SessionEvents.after_transaction_end` event
  1407. (assuming normal operation of the :class:`.Session`).
  1408. :param session: the target :class:`.Session`.
  1409. :param transaction: the target :class:`.SessionTransaction`.
  1410. To detect if this is the outermost
  1411. :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
  1412. SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
  1413. is ``None``::
  1414. @event.listens_for(session, "after_transaction_create")
  1415. def after_transaction_create(session, transaction):
  1416. if transaction.parent is None:
  1417. # work with top-level transaction
  1418. To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
  1419. :attr:`.SessionTransaction.nested` attribute::
  1420. @event.listens_for(session, "after_transaction_create")
  1421. def after_transaction_create(session, transaction):
  1422. if transaction.nested:
  1423. # work with SAVEPOINT transaction
  1424. .. seealso::
  1425. :class:`.SessionTransaction`
  1426. :meth:`~.SessionEvents.after_transaction_end`
  1427. """
  1428. def after_transaction_end(
  1429. self, session: Session, transaction: SessionTransaction
  1430. ) -> None:
  1431. """Execute when the span of a :class:`.SessionTransaction` ends.
  1432. This event differs from :meth:`~.SessionEvents.after_commit`
  1433. in that it corresponds to all :class:`.SessionTransaction`
  1434. objects in use, including those for nested transactions
  1435. and subtransactions, and is always matched by a corresponding
  1436. :meth:`~.SessionEvents.after_transaction_create` event.
  1437. :param session: the target :class:`.Session`.
  1438. :param transaction: the target :class:`.SessionTransaction`.
  1439. To detect if this is the outermost
  1440. :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
  1441. SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
  1442. is ``None``::
  1443. @event.listens_for(session, "after_transaction_create")
  1444. def after_transaction_end(session, transaction):
  1445. if transaction.parent is None:
  1446. # work with top-level transaction
  1447. To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
  1448. :attr:`.SessionTransaction.nested` attribute::
  1449. @event.listens_for(session, "after_transaction_create")
  1450. def after_transaction_end(session, transaction):
  1451. if transaction.nested:
  1452. # work with SAVEPOINT transaction
  1453. .. seealso::
  1454. :class:`.SessionTransaction`
  1455. :meth:`~.SessionEvents.after_transaction_create`
  1456. """
  1457. def before_commit(self, session: Session) -> None:
  1458. """Execute before commit is called.
  1459. .. note::
  1460. The :meth:`~.SessionEvents.before_commit` hook is *not* per-flush,
  1461. that is, the :class:`.Session` can emit SQL to the database
  1462. many times within the scope of a transaction.
  1463. For interception of these events, use the
  1464. :meth:`~.SessionEvents.before_flush`,
  1465. :meth:`~.SessionEvents.after_flush`, or
  1466. :meth:`~.SessionEvents.after_flush_postexec`
  1467. events.
  1468. :param session: The target :class:`.Session`.
  1469. .. seealso::
  1470. :meth:`~.SessionEvents.after_commit`
  1471. :meth:`~.SessionEvents.after_begin`
  1472. :meth:`~.SessionEvents.after_transaction_create`
  1473. :meth:`~.SessionEvents.after_transaction_end`
  1474. """
  1475. def after_commit(self, session: Session) -> None:
  1476. """Execute after a commit has occurred.
  1477. .. note::
  1478. The :meth:`~.SessionEvents.after_commit` hook is *not* per-flush,
  1479. that is, the :class:`.Session` can emit SQL to the database
  1480. many times within the scope of a transaction.
  1481. For interception of these events, use the
  1482. :meth:`~.SessionEvents.before_flush`,
  1483. :meth:`~.SessionEvents.after_flush`, or
  1484. :meth:`~.SessionEvents.after_flush_postexec`
  1485. events.
  1486. .. note::
  1487. The :class:`.Session` is not in an active transaction
  1488. when the :meth:`~.SessionEvents.after_commit` event is invoked,
  1489. and therefore can not emit SQL. To emit SQL corresponding to
  1490. every transaction, use the :meth:`~.SessionEvents.before_commit`
  1491. event.
  1492. :param session: The target :class:`.Session`.
  1493. .. seealso::
  1494. :meth:`~.SessionEvents.before_commit`
  1495. :meth:`~.SessionEvents.after_begin`
  1496. :meth:`~.SessionEvents.after_transaction_create`
  1497. :meth:`~.SessionEvents.after_transaction_end`
  1498. """
  1499. def after_rollback(self, session: Session) -> None:
  1500. """Execute after a real DBAPI rollback has occurred.
  1501. Note that this event only fires when the *actual* rollback against
  1502. the database occurs - it does *not* fire each time the
  1503. :meth:`.Session.rollback` method is called, if the underlying
  1504. DBAPI transaction has already been rolled back. In many
  1505. cases, the :class:`.Session` will not be in
  1506. an "active" state during this event, as the current
  1507. transaction is not valid. To acquire a :class:`.Session`
  1508. which is active after the outermost rollback has proceeded,
  1509. use the :meth:`.SessionEvents.after_soft_rollback` event, checking the
  1510. :attr:`.Session.is_active` flag.
  1511. :param session: The target :class:`.Session`.
  1512. """
  1513. def after_soft_rollback(
  1514. self, session: Session, previous_transaction: SessionTransaction
  1515. ) -> None:
  1516. """Execute after any rollback has occurred, including "soft"
  1517. rollbacks that don't actually emit at the DBAPI level.
  1518. This corresponds to both nested and outer rollbacks, i.e.
  1519. the innermost rollback that calls the DBAPI's
  1520. rollback() method, as well as the enclosing rollback
  1521. calls that only pop themselves from the transaction stack.
  1522. The given :class:`.Session` can be used to invoke SQL and
  1523. :meth:`.Session.query` operations after an outermost rollback
  1524. by first checking the :attr:`.Session.is_active` flag::
  1525. @event.listens_for(Session, "after_soft_rollback")
  1526. def do_something(session, previous_transaction):
  1527. if session.is_active:
  1528. session.execute("select * from some_table")
  1529. :param session: The target :class:`.Session`.
  1530. :param previous_transaction: The :class:`.SessionTransaction`
  1531. transactional marker object which was just closed. The current
  1532. :class:`.SessionTransaction` for the given :class:`.Session` is
  1533. available via the :attr:`.Session.transaction` attribute.
  1534. """
  1535. def before_flush(
  1536. self,
  1537. session: Session,
  1538. flush_context: UOWTransaction,
  1539. instances: Optional[Sequence[_O]],
  1540. ) -> None:
  1541. """Execute before flush process has started.
  1542. :param session: The target :class:`.Session`.
  1543. :param flush_context: Internal :class:`.UOWTransaction` object
  1544. which handles the details of the flush.
  1545. :param instances: Usually ``None``, this is the collection of
  1546. objects which can be passed to the :meth:`.Session.flush` method
  1547. (note this usage is deprecated).
  1548. .. seealso::
  1549. :meth:`~.SessionEvents.after_flush`
  1550. :meth:`~.SessionEvents.after_flush_postexec`
  1551. :ref:`session_persistence_events`
  1552. """
  1553. def after_flush(
  1554. self, session: Session, flush_context: UOWTransaction
  1555. ) -> None:
  1556. """Execute after flush has completed, but before commit has been
  1557. called.
  1558. Note that the session's state is still in pre-flush, i.e. 'new',
  1559. 'dirty', and 'deleted' lists still show pre-flush state as well
  1560. as the history settings on instance attributes.
  1561. .. warning:: This event runs after the :class:`.Session` has emitted
  1562. SQL to modify the database, but **before** it has altered its
  1563. internal state to reflect those changes, including that newly
  1564. inserted objects are placed into the identity map. ORM operations
  1565. emitted within this event such as loads of related items
  1566. may produce new identity map entries that will immediately
  1567. be replaced, sometimes causing confusing results. SQLAlchemy will
  1568. emit a warning for this condition as of version 1.3.9.
  1569. :param session: The target :class:`.Session`.
  1570. :param flush_context: Internal :class:`.UOWTransaction` object
  1571. which handles the details of the flush.
  1572. .. seealso::
  1573. :meth:`~.SessionEvents.before_flush`
  1574. :meth:`~.SessionEvents.after_flush_postexec`
  1575. :ref:`session_persistence_events`
  1576. """
  1577. def after_flush_postexec(
  1578. self, session: Session, flush_context: UOWTransaction
  1579. ) -> None:
  1580. """Execute after flush has completed, and after the post-exec
  1581. state occurs.
  1582. This will be when the 'new', 'dirty', and 'deleted' lists are in
  1583. their final state. An actual commit() may or may not have
  1584. occurred, depending on whether or not the flush started its own
  1585. transaction or participated in a larger transaction.
  1586. :param session: The target :class:`.Session`.
  1587. :param flush_context: Internal :class:`.UOWTransaction` object
  1588. which handles the details of the flush.
  1589. .. seealso::
  1590. :meth:`~.SessionEvents.before_flush`
  1591. :meth:`~.SessionEvents.after_flush`
  1592. :ref:`session_persistence_events`
  1593. """
  1594. def after_begin(
  1595. self,
  1596. session: Session,
  1597. transaction: SessionTransaction,
  1598. connection: Connection,
  1599. ) -> None:
  1600. """Execute after a transaction is begun on a connection.
  1601. .. note:: This event is called within the process of the
  1602. :class:`_orm.Session` modifying its own internal state.
  1603. To invoke SQL operations within this hook, use the
  1604. :class:`_engine.Connection` provided to the event;
  1605. do not run SQL operations using the :class:`_orm.Session`
  1606. directly.
  1607. :param session: The target :class:`.Session`.
  1608. :param transaction: The :class:`.SessionTransaction`.
  1609. :param connection: The :class:`_engine.Connection` object
  1610. which will be used for SQL statements.
  1611. .. seealso::
  1612. :meth:`~.SessionEvents.before_commit`
  1613. :meth:`~.SessionEvents.after_commit`
  1614. :meth:`~.SessionEvents.after_transaction_create`
  1615. :meth:`~.SessionEvents.after_transaction_end`
  1616. """
  1617. @_lifecycle_event
  1618. def before_attach(self, session: Session, instance: _O) -> None:
  1619. """Execute before an instance is attached to a session.
  1620. This is called before an add, delete or merge causes
  1621. the object to be part of the session.
  1622. .. seealso::
  1623. :meth:`~.SessionEvents.after_attach`
  1624. :ref:`session_lifecycle_events`
  1625. """
  1626. @_lifecycle_event
  1627. def after_attach(self, session: Session, instance: _O) -> None:
  1628. """Execute after an instance is attached to a session.
  1629. This is called after an add, delete or merge.
  1630. .. note::
  1631. As of 0.8, this event fires off *after* the item
  1632. has been fully associated with the session, which is
  1633. different than previous releases. For event
  1634. handlers that require the object not yet
  1635. be part of session state (such as handlers which
  1636. may autoflush while the target object is not
  1637. yet complete) consider the
  1638. new :meth:`.before_attach` event.
  1639. .. seealso::
  1640. :meth:`~.SessionEvents.before_attach`
  1641. :ref:`session_lifecycle_events`
  1642. """
  1643. @event._legacy_signature(
  1644. "0.9",
  1645. ["session", "query", "query_context", "result"],
  1646. lambda update_context: (
  1647. update_context.session,
  1648. update_context.query,
  1649. None,
  1650. update_context.result,
  1651. ),
  1652. )
  1653. def after_bulk_update(self, update_context: _O) -> None:
  1654. """Event for after the legacy :meth:`_orm.Query.update` method
  1655. has been called.
  1656. .. legacy:: The :meth:`_orm.SessionEvents.after_bulk_update` method
  1657. is a legacy event hook as of SQLAlchemy 2.0. The event
  1658. **does not participate** in :term:`2.0 style` invocations
  1659. using :func:`_dml.update` documented at
  1660. :ref:`orm_queryguide_update_delete_where`. For 2.0 style use,
  1661. the :meth:`_orm.SessionEvents.do_orm_execute` hook will intercept
  1662. these calls.
  1663. :param update_context: an "update context" object which contains
  1664. details about the update, including these attributes:
  1665. * ``session`` - the :class:`.Session` involved
  1666. * ``query`` -the :class:`_query.Query`
  1667. object that this update operation
  1668. was called upon.
  1669. * ``values`` The "values" dictionary that was passed to
  1670. :meth:`_query.Query.update`.
  1671. * ``result`` the :class:`_engine.CursorResult`
  1672. returned as a result of the
  1673. bulk UPDATE operation.
  1674. .. versionchanged:: 1.4 the update_context no longer has a
  1675. ``QueryContext`` object associated with it.
  1676. .. seealso::
  1677. :meth:`.QueryEvents.before_compile_update`
  1678. :meth:`.SessionEvents.after_bulk_delete`
  1679. """
  1680. @event._legacy_signature(
  1681. "0.9",
  1682. ["session", "query", "query_context", "result"],
  1683. lambda delete_context: (
  1684. delete_context.session,
  1685. delete_context.query,
  1686. None,
  1687. delete_context.result,
  1688. ),
  1689. )
  1690. def after_bulk_delete(self, delete_context: _O) -> None:
  1691. """Event for after the legacy :meth:`_orm.Query.delete` method
  1692. has been called.
  1693. .. legacy:: The :meth:`_orm.SessionEvents.after_bulk_delete` method
  1694. is a legacy event hook as of SQLAlchemy 2.0. The event
  1695. **does not participate** in :term:`2.0 style` invocations
  1696. using :func:`_dml.delete` documented at
  1697. :ref:`orm_queryguide_update_delete_where`. For 2.0 style use,
  1698. the :meth:`_orm.SessionEvents.do_orm_execute` hook will intercept
  1699. these calls.
  1700. :param delete_context: a "delete context" object which contains
  1701. details about the update, including these attributes:
  1702. * ``session`` - the :class:`.Session` involved
  1703. * ``query`` -the :class:`_query.Query`
  1704. object that this update operation
  1705. was called upon.
  1706. * ``result`` the :class:`_engine.CursorResult`
  1707. returned as a result of the
  1708. bulk DELETE operation.
  1709. .. versionchanged:: 1.4 the update_context no longer has a
  1710. ``QueryContext`` object associated with it.
  1711. .. seealso::
  1712. :meth:`.QueryEvents.before_compile_delete`
  1713. :meth:`.SessionEvents.after_bulk_update`
  1714. """
  1715. @_lifecycle_event
  1716. def transient_to_pending(self, session: Session, instance: _O) -> None:
  1717. """Intercept the "transient to pending" transition for a specific
  1718. object.
  1719. This event is a specialization of the
  1720. :meth:`.SessionEvents.after_attach` event which is only invoked
  1721. for this specific transition. It is invoked typically during the
  1722. :meth:`.Session.add` call.
  1723. :param session: target :class:`.Session`
  1724. :param instance: the ORM-mapped instance being operated upon.
  1725. .. seealso::
  1726. :ref:`session_lifecycle_events`
  1727. """
  1728. @_lifecycle_event
  1729. def pending_to_transient(self, session: Session, instance: _O) -> None:
  1730. """Intercept the "pending to transient" transition for a specific
  1731. object.
  1732. This less common transition occurs when an pending object that has
  1733. not been flushed is evicted from the session; this can occur
  1734. when the :meth:`.Session.rollback` method rolls back the transaction,
  1735. or when the :meth:`.Session.expunge` method is used.
  1736. :param session: target :class:`.Session`
  1737. :param instance: the ORM-mapped instance being operated upon.
  1738. .. seealso::
  1739. :ref:`session_lifecycle_events`
  1740. """
  1741. @_lifecycle_event
  1742. def persistent_to_transient(self, session: Session, instance: _O) -> None:
  1743. """Intercept the "persistent to transient" transition for a specific
  1744. object.
  1745. This less common transition occurs when an pending object that has
  1746. has been flushed is evicted from the session; this can occur
  1747. when the :meth:`.Session.rollback` method rolls back the transaction.
  1748. :param session: target :class:`.Session`
  1749. :param instance: the ORM-mapped instance being operated upon.
  1750. .. seealso::
  1751. :ref:`session_lifecycle_events`
  1752. """
  1753. @_lifecycle_event
  1754. def pending_to_persistent(self, session: Session, instance: _O) -> None:
  1755. """Intercept the "pending to persistent"" transition for a specific
  1756. object.
  1757. This event is invoked within the flush process, and is
  1758. similar to scanning the :attr:`.Session.new` collection within
  1759. the :meth:`.SessionEvents.after_flush` event. However, in this
  1760. case the object has already been moved to the persistent state
  1761. when the event is called.
  1762. :param session: target :class:`.Session`
  1763. :param instance: the ORM-mapped instance being operated upon.
  1764. .. seealso::
  1765. :ref:`session_lifecycle_events`
  1766. """
  1767. @_lifecycle_event
  1768. def detached_to_persistent(self, session: Session, instance: _O) -> None:
  1769. """Intercept the "detached to persistent" transition for a specific
  1770. object.
  1771. This event is a specialization of the
  1772. :meth:`.SessionEvents.after_attach` event which is only invoked
  1773. for this specific transition. It is invoked typically during the
  1774. :meth:`.Session.add` call, as well as during the
  1775. :meth:`.Session.delete` call if the object was not previously
  1776. associated with the
  1777. :class:`.Session` (note that an object marked as "deleted" remains
  1778. in the "persistent" state until the flush proceeds).
  1779. .. note::
  1780. If the object becomes persistent as part of a call to
  1781. :meth:`.Session.delete`, the object is **not** yet marked as
  1782. deleted when this event is called. To detect deleted objects,
  1783. check the ``deleted`` flag sent to the
  1784. :meth:`.SessionEvents.persistent_to_detached` to event after the
  1785. flush proceeds, or check the :attr:`.Session.deleted` collection
  1786. within the :meth:`.SessionEvents.before_flush` event if deleted
  1787. objects need to be intercepted before the flush.
  1788. :param session: target :class:`.Session`
  1789. :param instance: the ORM-mapped instance being operated upon.
  1790. .. seealso::
  1791. :ref:`session_lifecycle_events`
  1792. """
  1793. @_lifecycle_event
  1794. def loaded_as_persistent(self, session: Session, instance: _O) -> None:
  1795. """Intercept the "loaded as persistent" transition for a specific
  1796. object.
  1797. This event is invoked within the ORM loading process, and is invoked
  1798. very similarly to the :meth:`.InstanceEvents.load` event. However,
  1799. the event here is linkable to a :class:`.Session` class or instance,
  1800. rather than to a mapper or class hierarchy, and integrates
  1801. with the other session lifecycle events smoothly. The object
  1802. is guaranteed to be present in the session's identity map when
  1803. this event is called.
  1804. .. note:: This event is invoked within the loader process before
  1805. eager loaders may have been completed, and the object's state may
  1806. not be complete. Additionally, invoking row-level refresh
  1807. operations on the object will place the object into a new loader
  1808. context, interfering with the existing load context. See the note
  1809. on :meth:`.InstanceEvents.load` for background on making use of the
  1810. :paramref:`.SessionEvents.restore_load_context` parameter, which
  1811. works in the same manner as that of
  1812. :paramref:`.InstanceEvents.restore_load_context`, in order to
  1813. resolve this scenario.
  1814. :param session: target :class:`.Session`
  1815. :param instance: the ORM-mapped instance being operated upon.
  1816. .. seealso::
  1817. :ref:`session_lifecycle_events`
  1818. """
  1819. @_lifecycle_event
  1820. def persistent_to_deleted(self, session: Session, instance: _O) -> None:
  1821. """Intercept the "persistent to deleted" transition for a specific
  1822. object.
  1823. This event is invoked when a persistent object's identity
  1824. is deleted from the database within a flush, however the object
  1825. still remains associated with the :class:`.Session` until the
  1826. transaction completes.
  1827. If the transaction is rolled back, the object moves again
  1828. to the persistent state, and the
  1829. :meth:`.SessionEvents.deleted_to_persistent` event is called.
  1830. If the transaction is committed, the object becomes detached,
  1831. which will emit the :meth:`.SessionEvents.deleted_to_detached`
  1832. event.
  1833. Note that while the :meth:`.Session.delete` method is the primary
  1834. public interface to mark an object as deleted, many objects
  1835. get deleted due to cascade rules, which are not always determined
  1836. until flush time. Therefore, there's no way to catch
  1837. every object that will be deleted until the flush has proceeded.
  1838. the :meth:`.SessionEvents.persistent_to_deleted` event is therefore
  1839. invoked at the end of a flush.
  1840. .. seealso::
  1841. :ref:`session_lifecycle_events`
  1842. """
  1843. @_lifecycle_event
  1844. def deleted_to_persistent(self, session: Session, instance: _O) -> None:
  1845. """Intercept the "deleted to persistent" transition for a specific
  1846. object.
  1847. This transition occurs only when an object that's been deleted
  1848. successfully in a flush is restored due to a call to
  1849. :meth:`.Session.rollback`. The event is not called under
  1850. any other circumstances.
  1851. .. seealso::
  1852. :ref:`session_lifecycle_events`
  1853. """
  1854. @_lifecycle_event
  1855. def deleted_to_detached(self, session: Session, instance: _O) -> None:
  1856. """Intercept the "deleted to detached" transition for a specific
  1857. object.
  1858. This event is invoked when a deleted object is evicted
  1859. from the session. The typical case when this occurs is when
  1860. the transaction for a :class:`.Session` in which the object
  1861. was deleted is committed; the object moves from the deleted
  1862. state to the detached state.
  1863. It is also invoked for objects that were deleted in a flush
  1864. when the :meth:`.Session.expunge_all` or :meth:`.Session.close`
  1865. events are called, as well as if the object is individually
  1866. expunged from its deleted state via :meth:`.Session.expunge`.
  1867. .. seealso::
  1868. :ref:`session_lifecycle_events`
  1869. """
  1870. @_lifecycle_event
  1871. def persistent_to_detached(self, session: Session, instance: _O) -> None:
  1872. """Intercept the "persistent to detached" transition for a specific
  1873. object.
  1874. This event is invoked when a persistent object is evicted
  1875. from the session. There are many conditions that cause this
  1876. to happen, including:
  1877. * using a method such as :meth:`.Session.expunge`
  1878. or :meth:`.Session.close`
  1879. * Calling the :meth:`.Session.rollback` method, when the object
  1880. was part of an INSERT statement for that session's transaction
  1881. :param session: target :class:`.Session`
  1882. :param instance: the ORM-mapped instance being operated upon.
  1883. :param deleted: boolean. If True, indicates this object moved
  1884. to the detached state because it was marked as deleted and flushed.
  1885. .. seealso::
  1886. :ref:`session_lifecycle_events`
  1887. """
  1888. class AttributeEvents(event.Events[QueryableAttribute[Any]]):
  1889. r"""Define events for object attributes.
  1890. These are typically defined on the class-bound descriptor for the
  1891. target class.
  1892. For example, to register a listener that will receive the
  1893. :meth:`_orm.AttributeEvents.append` event::
  1894. from sqlalchemy import event
  1895. @event.listens_for(MyClass.collection, 'append', propagate=True)
  1896. def my_append_listener(target, value, initiator):
  1897. print("received append event for target: %s" % target)
  1898. Listeners have the option to return a possibly modified version of the
  1899. value, when the :paramref:`.AttributeEvents.retval` flag is passed to
  1900. :func:`.event.listen` or :func:`.event.listens_for`, such as below,
  1901. illustrated using the :meth:`_orm.AttributeEvents.set` event::
  1902. def validate_phone(target, value, oldvalue, initiator):
  1903. "Strip non-numeric characters from a phone number"
  1904. return re.sub(r'\D', '', value)
  1905. # setup listener on UserContact.phone attribute, instructing
  1906. # it to use the return value
  1907. listen(UserContact.phone, 'set', validate_phone, retval=True)
  1908. A validation function like the above can also raise an exception
  1909. such as :exc:`ValueError` to halt the operation.
  1910. The :paramref:`.AttributeEvents.propagate` flag is also important when
  1911. applying listeners to mapped classes that also have mapped subclasses,
  1912. as when using mapper inheritance patterns::
  1913. @event.listens_for(MySuperClass.attr, 'set', propagate=True)
  1914. def receive_set(target, value, initiator):
  1915. print("value set: %s" % target)
  1916. The full list of modifiers available to the :func:`.event.listen`
  1917. and :func:`.event.listens_for` functions are below.
  1918. :param active_history=False: When True, indicates that the
  1919. "set" event would like to receive the "old" value being
  1920. replaced unconditionally, even if this requires firing off
  1921. database loads. Note that ``active_history`` can also be
  1922. set directly via :func:`.column_property` and
  1923. :func:`_orm.relationship`.
  1924. :param propagate=False: When True, the listener function will
  1925. be established not just for the class attribute given, but
  1926. for attributes of the same name on all current subclasses
  1927. of that class, as well as all future subclasses of that
  1928. class, using an additional listener that listens for
  1929. instrumentation events.
  1930. :param raw=False: When True, the "target" argument to the
  1931. event will be the :class:`.InstanceState` management
  1932. object, rather than the mapped instance itself.
  1933. :param retval=False: when True, the user-defined event
  1934. listening must return the "value" argument from the
  1935. function. This gives the listening function the opportunity
  1936. to change the value that is ultimately used for a "set"
  1937. or "append" event.
  1938. """
  1939. _target_class_doc = "SomeClass.some_attribute"
  1940. _dispatch_target = QueryableAttribute
  1941. @staticmethod
  1942. def _set_dispatch(
  1943. cls: Type[_HasEventsDispatch[Any]], dispatch_cls: Type[_Dispatch[Any]]
  1944. ) -> _Dispatch[Any]:
  1945. dispatch = event.Events._set_dispatch(cls, dispatch_cls)
  1946. dispatch_cls._active_history = False
  1947. return dispatch
  1948. @classmethod
  1949. def _accept_with(
  1950. cls,
  1951. target: Union[QueryableAttribute[Any], Type[QueryableAttribute[Any]]],
  1952. identifier: str,
  1953. ) -> Union[QueryableAttribute[Any], Type[QueryableAttribute[Any]]]:
  1954. # TODO: coverage
  1955. if isinstance(target, interfaces.MapperProperty):
  1956. return getattr(target.parent.class_, target.key)
  1957. else:
  1958. return target
  1959. @classmethod
  1960. def _listen( # type: ignore [override]
  1961. cls,
  1962. event_key: _EventKey[QueryableAttribute[Any]],
  1963. active_history: bool = False,
  1964. raw: bool = False,
  1965. retval: bool = False,
  1966. propagate: bool = False,
  1967. include_key: bool = False,
  1968. ) -> None:
  1969. target, fn = event_key.dispatch_target, event_key._listen_fn
  1970. if active_history:
  1971. target.dispatch._active_history = True
  1972. if not raw or not retval or not include_key:
  1973. def wrap(target: InstanceState[_O], *arg: Any, **kw: Any) -> Any:
  1974. if not raw:
  1975. target = target.obj() # type: ignore [assignment]
  1976. if not retval:
  1977. if arg:
  1978. value = arg[0]
  1979. else:
  1980. value = None
  1981. if include_key:
  1982. fn(target, *arg, **kw)
  1983. else:
  1984. fn(target, *arg)
  1985. return value
  1986. else:
  1987. if include_key:
  1988. return fn(target, *arg, **kw)
  1989. else:
  1990. return fn(target, *arg)
  1991. event_key = event_key.with_wrapper(wrap)
  1992. event_key.base_listen(propagate=propagate)
  1993. if propagate:
  1994. manager = instrumentation.manager_of_class(target.class_)
  1995. for mgr in manager.subclass_managers(True): # type: ignore [no-untyped-call] # noqa: E501
  1996. event_key.with_dispatch_target(mgr[target.key]).base_listen(
  1997. propagate=True
  1998. )
  1999. if active_history:
  2000. mgr[target.key].dispatch._active_history = True
  2001. def append(
  2002. self,
  2003. target: _O,
  2004. value: _T,
  2005. initiator: Event,
  2006. *,
  2007. key: EventConstants = NO_KEY,
  2008. ) -> Optional[_T]:
  2009. """Receive a collection append event.
  2010. The append event is invoked for each element as it is appended
  2011. to the collection. This occurs for single-item appends as well
  2012. as for a "bulk replace" operation.
  2013. :param target: the object instance receiving the event.
  2014. If the listener is registered with ``raw=True``, this will
  2015. be the :class:`.InstanceState` object.
  2016. :param value: the value being appended. If this listener
  2017. is registered with ``retval=True``, the listener
  2018. function must return this value, or a new value which
  2019. replaces it.
  2020. :param initiator: An instance of :class:`.attributes.Event`
  2021. representing the initiation of the event. May be modified
  2022. from its original value by backref handlers in order to control
  2023. chained event propagation, as well as be inspected for information
  2024. about the source of the event.
  2025. :param key: When the event is established using the
  2026. :paramref:`.AttributeEvents.include_key` parameter set to
  2027. True, this will be the key used in the operation, such as
  2028. ``collection[some_key_or_index] = value``.
  2029. The parameter is not passed
  2030. to the event at all if the the
  2031. :paramref:`.AttributeEvents.include_key`
  2032. was not used to set up the event; this is to allow backwards
  2033. compatibility with existing event handlers that don't include the
  2034. ``key`` parameter.
  2035. .. versionadded:: 2.0
  2036. :return: if the event was registered with ``retval=True``,
  2037. the given value, or a new effective value, should be returned.
  2038. .. seealso::
  2039. :class:`.AttributeEvents` - background on listener options such
  2040. as propagation to subclasses.
  2041. :meth:`.AttributeEvents.bulk_replace`
  2042. """
  2043. def append_wo_mutation(
  2044. self,
  2045. target: _O,
  2046. value: _T,
  2047. initiator: Event,
  2048. *,
  2049. key: EventConstants = NO_KEY,
  2050. ) -> None:
  2051. """Receive a collection append event where the collection was not
  2052. actually mutated.
  2053. This event differs from :meth:`_orm.AttributeEvents.append` in that
  2054. it is fired off for de-duplicating collections such as sets and
  2055. dictionaries, when the object already exists in the target collection.
  2056. The event does not have a return value and the identity of the
  2057. given object cannot be changed.
  2058. The event is used for cascading objects into a :class:`_orm.Session`
  2059. when the collection has already been mutated via a backref event.
  2060. :param target: the object instance receiving the event.
  2061. If the listener is registered with ``raw=True``, this will
  2062. be the :class:`.InstanceState` object.
  2063. :param value: the value that would be appended if the object did not
  2064. already exist in the collection.
  2065. :param initiator: An instance of :class:`.attributes.Event`
  2066. representing the initiation of the event. May be modified
  2067. from its original value by backref handlers in order to control
  2068. chained event propagation, as well as be inspected for information
  2069. about the source of the event.
  2070. :param key: When the event is established using the
  2071. :paramref:`.AttributeEvents.include_key` parameter set to
  2072. True, this will be the key used in the operation, such as
  2073. ``collection[some_key_or_index] = value``.
  2074. The parameter is not passed
  2075. to the event at all if the the
  2076. :paramref:`.AttributeEvents.include_key`
  2077. was not used to set up the event; this is to allow backwards
  2078. compatibility with existing event handlers that don't include the
  2079. ``key`` parameter.
  2080. .. versionadded:: 2.0
  2081. :return: No return value is defined for this event.
  2082. .. versionadded:: 1.4.15
  2083. """
  2084. def bulk_replace(
  2085. self,
  2086. target: _O,
  2087. values: Iterable[_T],
  2088. initiator: Event,
  2089. *,
  2090. keys: Optional[Iterable[EventConstants]] = None,
  2091. ) -> None:
  2092. """Receive a collection 'bulk replace' event.
  2093. This event is invoked for a sequence of values as they are incoming
  2094. to a bulk collection set operation, which can be
  2095. modified in place before the values are treated as ORM objects.
  2096. This is an "early hook" that runs before the bulk replace routine
  2097. attempts to reconcile which objects are already present in the
  2098. collection and which are being removed by the net replace operation.
  2099. It is typical that this method be combined with use of the
  2100. :meth:`.AttributeEvents.append` event. When using both of these
  2101. events, note that a bulk replace operation will invoke
  2102. the :meth:`.AttributeEvents.append` event for all new items,
  2103. even after :meth:`.AttributeEvents.bulk_replace` has been invoked
  2104. for the collection as a whole. In order to determine if an
  2105. :meth:`.AttributeEvents.append` event is part of a bulk replace,
  2106. use the symbol :attr:`~.attributes.OP_BULK_REPLACE` to test the
  2107. incoming initiator::
  2108. from sqlalchemy.orm.attributes import OP_BULK_REPLACE
  2109. @event.listens_for(SomeObject.collection, "bulk_replace")
  2110. def process_collection(target, values, initiator):
  2111. values[:] = [_make_value(value) for value in values]
  2112. @event.listens_for(SomeObject.collection, "append", retval=True)
  2113. def process_collection(target, value, initiator):
  2114. # make sure bulk_replace didn't already do it
  2115. if initiator is None or initiator.op is not OP_BULK_REPLACE:
  2116. return _make_value(value)
  2117. else:
  2118. return value
  2119. .. versionadded:: 1.2
  2120. :param target: the object instance receiving the event.
  2121. If the listener is registered with ``raw=True``, this will
  2122. be the :class:`.InstanceState` object.
  2123. :param value: a sequence (e.g. a list) of the values being set. The
  2124. handler can modify this list in place.
  2125. :param initiator: An instance of :class:`.attributes.Event`
  2126. representing the initiation of the event.
  2127. :param keys: When the event is established using the
  2128. :paramref:`.AttributeEvents.include_key` parameter set to
  2129. True, this will be the sequence of keys used in the operation,
  2130. typically only for a dictionary update. The parameter is not passed
  2131. to the event at all if the the
  2132. :paramref:`.AttributeEvents.include_key`
  2133. was not used to set up the event; this is to allow backwards
  2134. compatibility with existing event handlers that don't include the
  2135. ``key`` parameter.
  2136. .. versionadded:: 2.0
  2137. .. seealso::
  2138. :class:`.AttributeEvents` - background on listener options such
  2139. as propagation to subclasses.
  2140. """
  2141. def remove(
  2142. self,
  2143. target: _O,
  2144. value: _T,
  2145. initiator: Event,
  2146. *,
  2147. key: EventConstants = NO_KEY,
  2148. ) -> None:
  2149. """Receive a collection remove event.
  2150. :param target: the object instance receiving the event.
  2151. If the listener is registered with ``raw=True``, this will
  2152. be the :class:`.InstanceState` object.
  2153. :param value: the value being removed.
  2154. :param initiator: An instance of :class:`.attributes.Event`
  2155. representing the initiation of the event. May be modified
  2156. from its original value by backref handlers in order to control
  2157. chained event propagation.
  2158. :param key: When the event is established using the
  2159. :paramref:`.AttributeEvents.include_key` parameter set to
  2160. True, this will be the key used in the operation, such as
  2161. ``del collection[some_key_or_index]``. The parameter is not passed
  2162. to the event at all if the the
  2163. :paramref:`.AttributeEvents.include_key`
  2164. was not used to set up the event; this is to allow backwards
  2165. compatibility with existing event handlers that don't include the
  2166. ``key`` parameter.
  2167. .. versionadded:: 2.0
  2168. :return: No return value is defined for this event.
  2169. .. seealso::
  2170. :class:`.AttributeEvents` - background on listener options such
  2171. as propagation to subclasses.
  2172. """
  2173. def set(
  2174. self, target: _O, value: _T, oldvalue: _T, initiator: Event
  2175. ) -> None:
  2176. """Receive a scalar set event.
  2177. :param target: the object instance receiving the event.
  2178. If the listener is registered with ``raw=True``, this will
  2179. be the :class:`.InstanceState` object.
  2180. :param value: the value being set. If this listener
  2181. is registered with ``retval=True``, the listener
  2182. function must return this value, or a new value which
  2183. replaces it.
  2184. :param oldvalue: the previous value being replaced. This
  2185. may also be the symbol ``NEVER_SET`` or ``NO_VALUE``.
  2186. If the listener is registered with ``active_history=True``,
  2187. the previous value of the attribute will be loaded from
  2188. the database if the existing value is currently unloaded
  2189. or expired.
  2190. :param initiator: An instance of :class:`.attributes.Event`
  2191. representing the initiation of the event. May be modified
  2192. from its original value by backref handlers in order to control
  2193. chained event propagation.
  2194. :return: if the event was registered with ``retval=True``,
  2195. the given value, or a new effective value, should be returned.
  2196. .. seealso::
  2197. :class:`.AttributeEvents` - background on listener options such
  2198. as propagation to subclasses.
  2199. """
  2200. def init_scalar(
  2201. self, target: _O, value: _T, dict_: Dict[Any, Any]
  2202. ) -> None:
  2203. r"""Receive a scalar "init" event.
  2204. This event is invoked when an uninitialized, unpersisted scalar
  2205. attribute is accessed, e.g. read::
  2206. x = my_object.some_attribute
  2207. The ORM's default behavior when this occurs for an un-initialized
  2208. attribute is to return the value ``None``; note this differs from
  2209. Python's usual behavior of raising ``AttributeError``. The
  2210. event here can be used to customize what value is actually returned,
  2211. with the assumption that the event listener would be mirroring
  2212. a default generator that is configured on the Core
  2213. :class:`_schema.Column`
  2214. object as well.
  2215. Since a default generator on a :class:`_schema.Column`
  2216. might also produce
  2217. a changing value such as a timestamp, the
  2218. :meth:`.AttributeEvents.init_scalar`
  2219. event handler can also be used to **set** the newly returned value, so
  2220. that a Core-level default generation function effectively fires off
  2221. only once, but at the moment the attribute is accessed on the
  2222. non-persisted object. Normally, no change to the object's state
  2223. is made when an uninitialized attribute is accessed (much older
  2224. SQLAlchemy versions did in fact change the object's state).
  2225. If a default generator on a column returned a particular constant,
  2226. a handler might be used as follows::
  2227. SOME_CONSTANT = 3.1415926
  2228. class MyClass(Base):
  2229. # ...
  2230. some_attribute = Column(Numeric, default=SOME_CONSTANT)
  2231. @event.listens_for(
  2232. MyClass.some_attribute, "init_scalar",
  2233. retval=True, propagate=True)
  2234. def _init_some_attribute(target, dict_, value):
  2235. dict_['some_attribute'] = SOME_CONSTANT
  2236. return SOME_CONSTANT
  2237. Above, we initialize the attribute ``MyClass.some_attribute`` to the
  2238. value of ``SOME_CONSTANT``. The above code includes the following
  2239. features:
  2240. * By setting the value ``SOME_CONSTANT`` in the given ``dict_``,
  2241. we indicate that this value is to be persisted to the database.
  2242. This supersedes the use of ``SOME_CONSTANT`` in the default generator
  2243. for the :class:`_schema.Column`. The ``active_column_defaults.py``
  2244. example given at :ref:`examples_instrumentation` illustrates using
  2245. the same approach for a changing default, e.g. a timestamp
  2246. generator. In this particular example, it is not strictly
  2247. necessary to do this since ``SOME_CONSTANT`` would be part of the
  2248. INSERT statement in either case.
  2249. * By establishing the ``retval=True`` flag, the value we return
  2250. from the function will be returned by the attribute getter.
  2251. Without this flag, the event is assumed to be a passive observer
  2252. and the return value of our function is ignored.
  2253. * The ``propagate=True`` flag is significant if the mapped class
  2254. includes inheriting subclasses, which would also make use of this
  2255. event listener. Without this flag, an inheriting subclass will
  2256. not use our event handler.
  2257. In the above example, the attribute set event
  2258. :meth:`.AttributeEvents.set` as well as the related validation feature
  2259. provided by :obj:`_orm.validates` is **not** invoked when we apply our
  2260. value to the given ``dict_``. To have these events to invoke in
  2261. response to our newly generated value, apply the value to the given
  2262. object as a normal attribute set operation::
  2263. SOME_CONSTANT = 3.1415926
  2264. @event.listens_for(
  2265. MyClass.some_attribute, "init_scalar",
  2266. retval=True, propagate=True)
  2267. def _init_some_attribute(target, dict_, value):
  2268. # will also fire off attribute set events
  2269. target.some_attribute = SOME_CONSTANT
  2270. return SOME_CONSTANT
  2271. When multiple listeners are set up, the generation of the value
  2272. is "chained" from one listener to the next by passing the value
  2273. returned by the previous listener that specifies ``retval=True``
  2274. as the ``value`` argument of the next listener.
  2275. :param target: the object instance receiving the event.
  2276. If the listener is registered with ``raw=True``, this will
  2277. be the :class:`.InstanceState` object.
  2278. :param value: the value that is to be returned before this event
  2279. listener were invoked. This value begins as the value ``None``,
  2280. however will be the return value of the previous event handler
  2281. function if multiple listeners are present.
  2282. :param dict\_: the attribute dictionary of this mapped object.
  2283. This is normally the ``__dict__`` of the object, but in all cases
  2284. represents the destination that the attribute system uses to get
  2285. at the actual value of this attribute. Placing the value in this
  2286. dictionary has the effect that the value will be used in the
  2287. INSERT statement generated by the unit of work.
  2288. .. seealso::
  2289. :meth:`.AttributeEvents.init_collection` - collection version
  2290. of this event
  2291. :class:`.AttributeEvents` - background on listener options such
  2292. as propagation to subclasses.
  2293. :ref:`examples_instrumentation` - see the
  2294. ``active_column_defaults.py`` example.
  2295. """
  2296. def init_collection(
  2297. self,
  2298. target: _O,
  2299. collection: Type[Collection[Any]],
  2300. collection_adapter: CollectionAdapter,
  2301. ) -> None:
  2302. """Receive a 'collection init' event.
  2303. This event is triggered for a collection-based attribute, when
  2304. the initial "empty collection" is first generated for a blank
  2305. attribute, as well as for when the collection is replaced with
  2306. a new one, such as via a set event.
  2307. E.g., given that ``User.addresses`` is a relationship-based
  2308. collection, the event is triggered here::
  2309. u1 = User()
  2310. u1.addresses.append(a1) # <- new collection
  2311. and also during replace operations::
  2312. u1.addresses = [a2, a3] # <- new collection
  2313. :param target: the object instance receiving the event.
  2314. If the listener is registered with ``raw=True``, this will
  2315. be the :class:`.InstanceState` object.
  2316. :param collection: the new collection. This will always be generated
  2317. from what was specified as
  2318. :paramref:`_orm.relationship.collection_class`, and will always
  2319. be empty.
  2320. :param collection_adapter: the :class:`.CollectionAdapter` that will
  2321. mediate internal access to the collection.
  2322. .. seealso::
  2323. :class:`.AttributeEvents` - background on listener options such
  2324. as propagation to subclasses.
  2325. :meth:`.AttributeEvents.init_scalar` - "scalar" version of this
  2326. event.
  2327. """
  2328. def dispose_collection(
  2329. self,
  2330. target: _O,
  2331. collection: Collection[Any],
  2332. collection_adapter: CollectionAdapter,
  2333. ) -> None:
  2334. """Receive a 'collection dispose' event.
  2335. This event is triggered for a collection-based attribute when
  2336. a collection is replaced, that is::
  2337. u1.addresses.append(a1)
  2338. u1.addresses = [a2, a3] # <- old collection is disposed
  2339. The old collection received will contain its previous contents.
  2340. .. versionchanged:: 1.2 The collection passed to
  2341. :meth:`.AttributeEvents.dispose_collection` will now have its
  2342. contents before the dispose intact; previously, the collection
  2343. would be empty.
  2344. .. seealso::
  2345. :class:`.AttributeEvents` - background on listener options such
  2346. as propagation to subclasses.
  2347. """
  2348. def modified(self, target: _O, initiator: Event) -> None:
  2349. """Receive a 'modified' event.
  2350. This event is triggered when the :func:`.attributes.flag_modified`
  2351. function is used to trigger a modify event on an attribute without
  2352. any specific value being set.
  2353. .. versionadded:: 1.2
  2354. :param target: the object instance receiving the event.
  2355. If the listener is registered with ``raw=True``, this will
  2356. be the :class:`.InstanceState` object.
  2357. :param initiator: An instance of :class:`.attributes.Event`
  2358. representing the initiation of the event.
  2359. .. seealso::
  2360. :class:`.AttributeEvents` - background on listener options such
  2361. as propagation to subclasses.
  2362. """
  2363. class QueryEvents(event.Events[Query[Any]]):
  2364. """Represent events within the construction of a :class:`_query.Query`
  2365. object.
  2366. .. legacy:: The :class:`_orm.QueryEvents` event methods are legacy
  2367. as of SQLAlchemy 2.0, and only apply to direct use of the
  2368. :class:`_orm.Query` object. They are not used for :term:`2.0 style`
  2369. statements. For events to intercept and modify 2.0 style ORM use,
  2370. use the :meth:`_orm.SessionEvents.do_orm_execute` hook.
  2371. The :class:`_orm.QueryEvents` hooks are now superseded by the
  2372. :meth:`_orm.SessionEvents.do_orm_execute` event hook.
  2373. """
  2374. _target_class_doc = "SomeQuery"
  2375. _dispatch_target = Query
  2376. def before_compile(self, query: Query[Any]) -> None:
  2377. """Receive the :class:`_query.Query`
  2378. object before it is composed into a
  2379. core :class:`_expression.Select` object.
  2380. .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile` event
  2381. is superseded by the much more capable
  2382. :meth:`_orm.SessionEvents.do_orm_execute` hook. In version 1.4,
  2383. the :meth:`_orm.QueryEvents.before_compile` event is **no longer
  2384. used** for ORM-level attribute loads, such as loads of deferred
  2385. or expired attributes as well as relationship loaders. See the
  2386. new examples in :ref:`examples_session_orm_events` which
  2387. illustrate new ways of intercepting and modifying ORM queries
  2388. for the most common purpose of adding arbitrary filter criteria.
  2389. This event is intended to allow changes to the query given::
  2390. @event.listens_for(Query, "before_compile", retval=True)
  2391. def no_deleted(query):
  2392. for desc in query.column_descriptions:
  2393. if desc['type'] is User:
  2394. entity = desc['entity']
  2395. query = query.filter(entity.deleted == False)
  2396. return query
  2397. The event should normally be listened with the ``retval=True``
  2398. parameter set, so that the modified query may be returned.
  2399. The :meth:`.QueryEvents.before_compile` event by default
  2400. will disallow "baked" queries from caching a query, if the event
  2401. hook returns a new :class:`_query.Query` object.
  2402. This affects both direct
  2403. use of the baked query extension as well as its operation within
  2404. lazy loaders and eager loaders for relationships. In order to
  2405. re-establish the query being cached, apply the event adding the
  2406. ``bake_ok`` flag::
  2407. @event.listens_for(
  2408. Query, "before_compile", retval=True, bake_ok=True)
  2409. def my_event(query):
  2410. for desc in query.column_descriptions:
  2411. if desc['type'] is User:
  2412. entity = desc['entity']
  2413. query = query.filter(entity.deleted == False)
  2414. return query
  2415. When ``bake_ok`` is set to True, the event hook will only be invoked
  2416. once, and not called for subsequent invocations of a particular query
  2417. that is being cached.
  2418. .. versionadded:: 1.3.11 - added the "bake_ok" flag to the
  2419. :meth:`.QueryEvents.before_compile` event and disallowed caching via
  2420. the "baked" extension from occurring for event handlers that
  2421. return a new :class:`_query.Query` object if this flag is not set.
  2422. .. seealso::
  2423. :meth:`.QueryEvents.before_compile_update`
  2424. :meth:`.QueryEvents.before_compile_delete`
  2425. :ref:`baked_with_before_compile`
  2426. """
  2427. def before_compile_update(
  2428. self, query: Query[Any], update_context: BulkUpdate
  2429. ) -> None:
  2430. """Allow modifications to the :class:`_query.Query` object within
  2431. :meth:`_query.Query.update`.
  2432. .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile_update`
  2433. event is superseded by the much more capable
  2434. :meth:`_orm.SessionEvents.do_orm_execute` hook.
  2435. Like the :meth:`.QueryEvents.before_compile` event, if the event
  2436. is to be used to alter the :class:`_query.Query` object, it should
  2437. be configured with ``retval=True``, and the modified
  2438. :class:`_query.Query` object returned, as in ::
  2439. @event.listens_for(Query, "before_compile_update", retval=True)
  2440. def no_deleted(query, update_context):
  2441. for desc in query.column_descriptions:
  2442. if desc['type'] is User:
  2443. entity = desc['entity']
  2444. query = query.filter(entity.deleted == False)
  2445. update_context.values['timestamp'] = datetime.utcnow()
  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. """
  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)