events.py 124 KB

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