
    ,h%                      % S r SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ	r	  SS	KJ
r
  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ r   SSK!J"r"  SSK#J$r$  SSK#J%r%  S S!KJ&r&  S S"KJ'r'  S S#KJ(r(  S S$K&J)r)  S S%K*J+r+  S S&K,J-r-  \(       ax  SS'KJ.r.  SS(K/J0r0  SS)K/J1r1  SS*K/J2r2  SS+K/J3r3  SS,KJ4r4  SS-KJ5r5  SS.K#J6r6  SS/K#J7r7  SS0K8J9r9  S S1K:J;r;  S S2K<J=r=  S S3K<J>r>  S S4K*J?r?  S S5K@JArA  S S6KBJCrC  S S7KDJErE  S S8KDJFrF  S S9KGJHrH  S S:KIJJrJ  \" S;\S<9rK\" S=\)S<9rL " S> S?\&R                  \   5      rN " S@ SA5      rO " SB SC\&R                  \\      5      rP " SD SE\&R                  \+   5      rR " SF SG\R\+   5      rS " SH SI\&R                  \R                  \      5      rT " SJ SK\R\+   5      rU\V" 5       rWSL\XSM'    " SN SO\&R                  \$   5      rY " SP SQ\&R                  \\      5      rZ " SR SS\&R                  \ \      5      r[g)TzORM event interfaces.

    )annotations)Any)Callable)
Collection)Dict)Generic)Iterable)Optional)Sequence)Set)Type)TYPE_CHECKING)TypeVar)UnionN   )instrumentation)
interfaces)	mapperlib)QueryableAttribute_mapper_or_none)NO_KEY)ClassManager)InstrumentationFactory)
BulkDelete)
BulkUpdate)Query)scoped_session)Session)sessionmaker   )event)exc)util)EventTarget)_ET)inspect_getfullargspec)ReferenceType)_InstanceDict)_InternalEntityType)_O)_T)Event)EventConstants)ORMExecuteState)SessionTransaction)UOWTransaction)
Connection)	_Dispatch)_HasEventsDispatch)	_EventKey)CollectionAdapter)QueryContext)DeclarativeAttributeIntercept)DeclarativeMeta)Mapper)InstanceState_KT)bound_ET2c                     ^  \ rS rSrSrSr\r\      SS j5       r	\ S       SS jj5       r
\SU 4S jj5       rSS jrSS jr        SS	 jrS
rU =r$ )InstrumentationEventsL   a  Events related to class instrumentation events.

The listeners here support being established against
any new style class, that is any object that is a subclass
of 'type'.  Events will then be fired off for events
against that class.  If the "propagate=True" flag is passed
to event.listen(), the event will fire off for subclasses
of that class as well.

The Python ``type`` builtin is also accepted as a target,
which when used has the effect of events being emitted
for all classes.

Note the "propagate" flag here is defaulted to ``True``,
unlike the other class level events where it defaults
to ``False``.  This means that new subclasses will also
be the subject of these events, when a listener
is established on a superclass.

SomeBaseClassc                D    [        U[        5      (       a  [        U5      $ g N)
isinstancetype_InstrumentationEventsHoldclstarget
identifiers      M/var/www/auris/envauris/lib/python3.13/site-packages/sqlalchemy/orm/events.py_accept_with"InstrumentationEvents._accept_withe   s     fd##-f55    c                <  ^^^^^ UR                   UR                  UR                  smmmSUUU4S jjmSUU4S jjn[        R                  " TR
                  U5      mUR                  [        R                  5      R                  T5      R                  " S0 UD6  g )Nc                   > T" 5       nUc  g T(       a  [        X5      (       a	  T" U /UQ76 $ T(       d  XL a	  T" U /UQ76 $ g rD   )
issubclass)
target_clsarg
listen_clsfn	propagaterJ   s      rL   listen-InstrumentationEvents._listen.<locals>.listen   sM    J !Z
??*+s++:#;*+s++rO   c                   > [         R                  R                  S TT[        R                  5      n[        [        R                  R                  T5      R                  U5        g rD   )r"   registryr5   r   _instrumentation_factorygetattrdispatchremove)refkeyrK   rX   s     rL   r_   -InstrumentationEvents._listen.<locals>.remove   sM    ..**88	C 88AA:fSkrO   )rS   rF   rT   r   returnOptional[Any])r`   zReferenceType[_T]rc   None )dispatch_targetrK   
_listen_fnweakrefr`   class_with_dispatch_targetr   r\   with_wrapperbase_listen)	rI   	event_keyrW   kwr_   rV   rK   rX   rJ   s	     `  @@@@rL   _listenInstrumentationEvents._listenx   s    
 %%     	
B	 	"		 		 V]]F3&&44	

,v
{{	+ 	1-/	1rO   c                r   > [         TU ]  5         [        R                  R                  R                  5         g rD   )super_clearr   r\   r^   rI   	__class__s    rL   rt   InstrumentationEvents._clear   s%    0099@@BrO   c                    g)zuCalled after the given class is instrumented.

To get at the :class:`.ClassManager`, use
:func:`.manager_of_class`.

Nrf   selfrI   s     rL   class_instrument&InstrumentationEvents.class_instrument       rO   c                    g)zxCalled before the given class is uninstrumented.

To get at the :class:`.ClassManager`, use
:func:`.manager_of_class`.

Nrf   ry   s     rL   class_uninstrument(InstrumentationEvents.class_uninstrument   r}   rO   c                    g)z)Called when an attribute is instrumented.Nrf   )rz   rI   ra   insts       rL   attribute_instrument*InstrumentationEvents.attribute_instrument   r}   rO   rf   )rJ   z;Union[InstrumentationFactory, Type[InstrumentationFactory]]rK   strrc   zEOptional[Union[InstrumentationFactory, Type[InstrumentationFactory]]])T)rn   z_EventKey[_T]rW   boolro   r   rc   re   rc   re   )rI   ClassManager[_O]rc   re   )rI   r   ra   r<   r   r+   rc   re   )__name__
__module____qualname____firstlineno____doc___target_class_docr   _dispatch_targetclassmethodrM   rp   rt   r{   r   r   __static_attributes____classcell__rv   s   @rL   r@   r@   L   s    * (-
 
 $ 9=)1%)126)1EH)1	)1 )1V C C8#8*-8578	8 8rO   r@   c                  F    \ rS rSrSrSS jr\R                  " \5      r	Sr
g)rG      zotemporary marker object used to transfer from _accept_with() to
_listen() on the InstrumentationEvents class.

c                    Xl         g rD   rj   rz   rj   s     rL   __init__#_InstrumentationEventsHold.__init__   s    rO   r   N)rj   rF   rc   re   )r   r   r   r   r   r   r"   
dispatcherr@   r^   r   rf   rO   rL   rG   rG      s    
  56HrO   rG   c                  p  ^  \ rS rSrSrSr\r\      SS j5       r	\\
R                  " S5            SS j5       5       r\   S           SS jj5       r\SU 4S jj5       rSS	 jrSS
 jrSS jr      SS jrSS jr        SS jr        SS jrSS jrSS jrSS jrSrU =r$ ) InstanceEvents   a  Define events specific to object lifecycle.

e.g.::

    from sqlalchemy import event


    def my_load_listener(target, context):
        print("on load!")


    event.listen(SomeClass, "load", my_load_listener)

Available targets include:

* mapped classes
* unmapped superclasses of mapped or to-be-mapped classes
  (using the ``propagate=True`` flag)
* :class:`_orm.Mapper` objects
* the :class:`_orm.Mapper` class itself indicates listening for all
  mappers.

Instance events are closely related to mapper events, but
are more specific to the instance and its instrumentation,
rather than its system of persistence.

When using :class:`.InstanceEvents`, several modifiers are
available to the :func:`.event.listen` function.

:param propagate=False: When True, the event listener should
   be applied to all inheriting classes as well as the
   class which is the target of this listener.
:param raw=False: When True, the "target" argument passed
   to applicable event listener functions will be the
   instance's :class:`.InstanceState` management
   object, rather than the mapped instance itself.
:param restore_load_context=False: Applies to the
   :meth:`.InstanceEvents.load` and :meth:`.InstanceEvents.refresh`
   events.  Restores the loader context of the object when the event
   hook is complete, so that ongoing eager load operations continue
   to target the object appropriately.  A warning is emitted if the
   object is moved to a new loader context from within one of these
   events if this flag is not set.

   .. versionadded:: 1.3.14


	SomeClassc                .    [         R                  X5        g rD   )_InstanceEventsHoldpopulate)rI   rj   classmanagers      rL   _new_classmanager_instance)InstanceEvents._new_classmanager_instance  s     	$$V:rO   sqlalchemy.ormc                   [         R                  R                  n[        U[        5      (       a  U$ [        U[
        R                  5      (       a  UR                  $ XR                  L a  [         R                  " SS5        [        $ [        U[        5      (       aO  [        U[
        R                  5      (       a  [        $ [        R                  " U5      nU(       a  U$ [        U5      $ g NzThe `sqlalchemy.orm.mapper()` symbol is deprecated and will be removed in a future release. For the mapper-wide event target, use the 'sqlalchemy.orm.Mapper' class.z2.0)r$   	preloadedormrE   r   r   r:   class_managermapperwarn_deprecatedrF   rR   r   opt_manager_of_classr   )rI   rJ   rK   r   managers        rL   rM   InstanceEvents._accept_with	  s     nn  fl++M	 0 011'''zz!  G 	  %%&)"2"233##)>>vF"N.v66rO   c                B  ^^^	 UR                   UR                  snm	T(       a  T(       a#          SU	UU4S jjnUR                  U5      nUR                  " SSU0UD6  U(       a7  UR	                  S5       H!  nUR                  U5      R                  SS9  M#     g g )Nc                   > T(       d  U R                  5       nOU nT(       a  U R                  n T" U/UQ70 UD6T(       a  WU l        $ $ ! T(       a  WU l        f f = frD   objrunid)staterT   ro   rJ   r   rV   rawrestore_load_contexts        rL   wrap$InstanceEvents._listen.<locals>.wrap9  s[     "'))+F"F'!KKE,f1s1b1+&+ ,+&+ ,s   A ArW   TrW   )r   InstanceState[_O]rT   r   ro   r   rc   rd   rf   )rg   rh   rl   rm   subclass_managersrk   )
rI   rn   r   rW   r   ro   rJ   r   mgrrV   s
     ` `    @rL   rp   InstanceEvents._listen,  s      //1E1E
*,(,03,;>,, , "..t4I8	8R8//5..s3??$?O 6 rO   c                J   > [         TU ]  5         [        R                  5         g rD   )rs   rt   r   ru   s    rL   rt   InstanceEvents._clearP  s    ""$rO   c                    g)a5  Called when the first instance of a particular mapping is called.

This event is called when the ``__init__`` method of a class
is called the first time for that particular class.    The event
invokes before ``__init__`` actually proceeds as well as before
the :meth:`.InstanceEvents.init` event is invoked.

Nrf   )rz   r   rI   s      rL   
first_initInstanceEvents.first_initU  r}   rO   c                    g)a  Receive an instance when its constructor is called.

This method is only called during a userland construction of
an object, in conjunction with the object's constructor, e.g.
its ``__init__`` method.  It is not called when an object is
loaded from the database; see the :meth:`.InstanceEvents.load`
event in order to intercept a database load.

The event is called before the actual ``__init__`` constructor
of the object is called.  The ``kwargs`` dictionary may be
modified in-place in order to affect what is passed to
``__init__``.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param args: positional arguments passed to the ``__init__`` method.
 This is passed as a tuple and is currently immutable.
:param kwargs: keyword arguments passed to the ``__init__`` method.
 This structure *can* be altered in place.

.. seealso::

    :meth:`.InstanceEvents.init_failure`

    :meth:`.InstanceEvents.load`

Nrf   rz   rJ   argskwargss       rL   initInstanceEvents.init_  r}   rO   c                    g)a  Receive an instance when its constructor has been called,
and raised an exception.

This method is only called during a userland construction of
an object, in conjunction with the object's constructor, e.g.
its ``__init__`` method. It is not called when an object is loaded
from the database.

The event is invoked after an exception raised by the ``__init__``
method is caught.  After the event
is invoked, the original exception is re-raised outwards, so that
the construction of the object still raises an exception.   The
actual exception and stack trace raised should be present in
``sys.exc_info()``.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param args: positional arguments that were passed to the ``__init__``
 method.
:param kwargs: keyword arguments that were passed to the ``__init__``
 method.

.. seealso::

    :meth:`.InstanceEvents.init`

    :meth:`.InstanceEvents.load`

Nrf   r   s       rL   init_failureInstanceEvents.init_failure~  r}   rO   c                    g)a]  receive an object instance after it was the subject of a merge()
call, when load=False was passed.

The target would be the already-loaded object in the Session which
would have had its attributes overwritten by the incoming object. This
overwrite operation does not use attribute events, instead just
populating dict directly. Therefore the purpose of this event is so
that extensions like sqlalchemy.ext.mutable know that object state has
changed and incoming state needs to be set up for "parents" etc.

This functionality is acceptable to be made public in a later release.

.. versionadded:: 1.4.41

Nrf   rz   rJ   contexts      rL   _sa_event_merge_wo_load&InstanceEvents._sa_event_merge_wo_load  r}   rO   c                    g)al  Receive an object instance after it has been created via
``__new__``, and after initial attribute population has
occurred.

This typically occurs when the instance is created based on
incoming result rows, and is only called once for that
instance's lifetime.

.. warning::

    During a result-row load, this event is invoked when the
    first row received for this instance is processed.  When using
    eager loading with collection-oriented attributes, the additional
    rows that are to be loaded / processed in order to load subsequent
    collection items have not occurred yet.   This has the effect
    both that collections will not be fully loaded, as well as that
    if an operation occurs within this event handler that emits
    another database load operation for the object, the "loading
    context" for the object can change and interfere with the
    existing eager loaders still in progress.

    Examples of what can cause the "loading context" to change within
    the event handler include, but are not necessarily limited to:

    * accessing deferred attributes that weren't part of the row,
      will trigger an "undefer" operation and refresh the object

    * accessing attributes on a joined-inheritance subclass that
      weren't part of the row, will trigger a refresh operation.

    As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The
    :paramref:`.InstanceEvents.restore_load_context` option may  be
    used on the event to prevent this warning; this will ensure that
    the existing loading context is maintained for the object after the
    event is called::

        @event.listens_for(SomeClass, "load", restore_load_context=True)
        def on_load(instance, context):
            instance.some_unloaded_attribute

    .. versionchanged:: 1.3.14 Added
       :paramref:`.InstanceEvents.restore_load_context`
       and :paramref:`.SessionEvents.restore_load_context` flags which
       apply to "on load" events, which will ensure that the loading
       context for an object is restored when the event hook is
       complete; a warning is emitted if the load context of the object
       changes without this flag being set.


The :meth:`.InstanceEvents.load` event is also available in a
class-method decorator format called :func:`_orm.reconstructor`.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param context: the :class:`.QueryContext` corresponding to the
 current :class:`_query.Query` in progress.  This argument may be
 ``None`` if the load does not correspond to a :class:`_query.Query`,
 such as during :meth:`.Session.merge`.

.. seealso::

    :ref:`mapped_class_load_events`

    :meth:`.InstanceEvents.init`

    :meth:`.InstanceEvents.refresh`

    :meth:`.SessionEvents.loaded_as_persistent`

Nrf   r   s      rL   loadInstanceEvents.load  r}   rO   c                    g)a  Receive an object instance after one or more attributes have
been refreshed from a query.

Contrast this to the :meth:`.InstanceEvents.load` method, which
is invoked when the object is first loaded from a query.

.. note:: This event is invoked within the loader process before
   eager loaders may have been completed, and the object's state may
   not be complete.  Additionally, invoking row-level refresh
   operations on the object will place the object into a new loader
   context, interfering with the existing load context.   See the note
   on :meth:`.InstanceEvents.load` for background on making use of the
   :paramref:`.InstanceEvents.restore_load_context` parameter, in
   order to resolve this scenario.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param context: the :class:`.QueryContext` corresponding to the
 current :class:`_query.Query` in progress.
:param attrs: sequence of attribute names which
 were populated, or None if all column-mapped, non-deferred
 attributes were populated.

.. seealso::

    :ref:`mapped_class_load_events`

    :meth:`.InstanceEvents.load`

Nrf   )rz   rJ   r   attrss       rL   refreshInstanceEvents.refresh  r}   rO   c                    g)a5  Receive an object instance after one or more attributes that
contain a column-level default or onupdate handler have been refreshed
during persistence of the object's state.

This event is the same as :meth:`.InstanceEvents.refresh` except
it is invoked within the unit of work flush process, and includes
only non-primary-key columns that have column level default or
onupdate handlers, including Python callables as well as server side
defaults and triggers which may be fetched via the RETURNING clause.

.. note::

    While the :meth:`.InstanceEvents.refresh_flush` event is triggered
    for an object that was INSERTed as well as for an object that was
    UPDATEd, the event is geared primarily  towards the UPDATE process;
    it is mostly an internal artifact that INSERT actions can also
    trigger this event, and note that **primary key columns for an
    INSERTed row are explicitly omitted** from this event.  In order to
    intercept the newly INSERTed state of an object, the
    :meth:`.SessionEvents.pending_to_persistent` and
    :meth:`.MapperEvents.after_insert` are better choices.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param flush_context: Internal :class:`.UOWTransaction` object
 which handles the details of the flush.
:param attrs: sequence of attribute names which
 were populated.

.. seealso::

    :ref:`mapped_class_load_events`

    :ref:`orm_server_defaults`

    :ref:`metadata_defaults_toplevel`

Nrf   )rz   rJ   flush_contextr   s       rL   refresh_flushInstanceEvents.refresh_flush   r}   rO   c                    g)a  Receive an object instance after its attributes or some subset
have been expired.

'keys' is a list of attribute names.  If None, the entire
state was expired.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param attrs: sequence of attribute
 names which were expired, or None if all attributes were
 expired.

Nrf   )rz   rJ   r   s      rL   expireInstanceEvents.expireO  r}   rO   c                    g)a  Receive an object instance when its associated state is
being pickled.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param state_dict: the dictionary returned by
 :class:`.InstanceState.__getstate__`, containing the state
 to be pickled.

Nrf   rz   rJ   
state_dicts      rL   pickleInstanceEvents.pickle`  r}   rO   c                    g)a  Receive an object instance after its associated state has
been unpickled.

:param target: the mapped instance.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:param state_dict: the dictionary sent to
 :class:`.InstanceState.__setstate__`, containing the state
 dictionary which was pickled.

Nrf   r   s      rL   unpickleInstanceEvents.unpicklen  r}   rO   rf   )rj   ;Union[DeclarativeAttributeIntercept, DeclarativeMeta, type]r   r   rc   re   )rJ   z1Union[ClassManager[Any], Type[ClassManager[Any]]]rK   r   rc   z;Optional[Union[ClassManager[Any], Type[ClassManager[Any]]]]FFF)rn   z_EventKey[ClassManager[Any]]r   r   rW   r   r   r   ro   r   rc   re   r   )r   r   rI   Type[_O]rc   re   )rJ   r+   r   r   r   r   rc   re   )rJ   r+   r   r7   rc   re   )rJ   r+   r   r7   r   Optional[Iterable[str]]rc   re   )rJ   r+   r   r1   r   r   rc   re   )rJ   r+   r   r   rc   re   )rJ   r+   r   r)   rc   re   )r   r   r   r   r   r   r   r   r   r   r$   preload_modulerM   rp   rt   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @rL   r   r      s   /b $#;K; '; 
	; ; 	)*
  
E + B  %*!P/!P !P 	!P
 #!P !P 
!P !PF % %>B#/	&HT""#/"8O"	"H-- &- '	-
 
-^" rO   r   c                      \ rS rSr% SrS\S'       SS jr\SS j5       r " S S\	\
   5      rSS	 jr\      SS
 j5       rSrg)_EventsHoldi}  zHold onto listeners against unmapped, uninstrumented classes.

Establish _listen() for that class' mapper/instrumentation when
those objects are created for that class.

#weakref.WeakKeyDictionary[Any, Any]	all_holdsc                    Xl         g rD   r   r   s     rL   r   _EventsHold.__init__  s	     rO   c                8    U R                   R                  5         g rD   )r   clear)rI   s    rL   rt   _EventsHold._clear  s    rO   c                  X    \ rS rSr% SrS\S'   \   S           SS jj5       rSrg)	_EventsHold.HoldEventsi  NzOptional[Type[_ET2]]r   c                f   UR                   nUR                  UR                  ;   a  UR                  UR                     nO0 =ovR                  UR                  '   [        R                  R                  X5        UUUUU4XqR                  '   U(       a  [        UR                  R                  5       5      nU(       as  UR                  S5      n	UR                  U	R                  5       5        UR                  U	5      n
U
b%  UR                  U
5      R                  " SUSUS.UD6  U(       a  Mr  g g g )Nr   Fr   rW   retvalrf   )rg   rj   r   r"   r[   _stored_in_collection_keylist__subclasses__popextendresolverk   rX   )rI   rn   r   rW   r   ro   rJ   
collectionstacksubclasssubjects              rL   rp   _EventsHold.HoldEvents._listen  s    ..F}} 0 00#--fmm<
?AA
--fmm<NN00C*J~~& V]]99;<$yy|HLL!8!8!:;$nnX6G* "66w?FF  #uVGI e rO   rf   r   )rn   z_EventKey[_ET2]r   r   rW   r   r   r   ro   r   rc   re   )	r   r   r   r   r   __annotations__r   rp   r   rf   rO   rL   
HoldEventsr     se    15.5	 # #	&#	 #	 	#	
 #	 #	 #	 
#	rO   r	  c                    UR                   n[        U[        5      (       a&  UR                  UR                     nX1R
                  	 g g rD   )rg   rE   r   r   rj   r   )rz   rn   rJ   r  s       rL   r_   _EventsHold.remove  s=    **fk**))&--8J>>* +rO   c           	        UR                    Hr  nX0R                  ;   d  M  U R                  U   nUR                  5        H;  u  nnnnn	U(       d  X1L d  M  UR                  U5      R                  " SUSUS.U	D6  M=     Mt     g )NFr   rf   )__mro__r   valuesrk   rX   )
rI   rj   r  r  r  rn   r   rW   r   ro   s
             rL   r   _EventsHold.populate  s     H==( ]]84
  &&( H$6 "66w?FF  #uVGI ) 'rO   r   N)rj   r   rc   re   r   )rn   _EventKey[_ET]rc   re   )rj   r   r  z#Union[ClassManager[_O], Mapper[_O]]rc   re   )r   r   r   r   r   r  r   r   rt   r   r>   r	  r_   r   r   rf   rO   rL   r   r   }  s     32K 
  'WT] 'R+ K 5 
	 rO   r   c                      \ rS rSr% \R
                  " 5       rS\S'   S	S jr " S S\	R                  \   \5      r\R                  " \5      rSrg)
r   i  r   r   c                .    [         R                  " U5      $ rD   )r   r   r   s     rL   r  _InstanceEventsHold.resolve  s    33F;;rO   c                      \ rS rSrSrg)&_InstanceEventsHold.HoldInstanceEventsi  rf   Nr   r   r   r   r   rf   rO   rL   HoldInstanceEventsr        rO   r  rf   N)rj   r   rc   zOptional[ClassManager[_O]])r   r   r   r   ri   WeakKeyDictionaryr   r  r  r   r	  r&   r   r  r"   r   r^   r   rf   rO   rL   r   r     sL    !!# 2 <[33C8.   23HrO   r   c                    ^  \ rS rSrSrSr\R                  r\	      SS j5       r
\	\R                  " S5            SS j5       5       r\	   S           SS jj5       r\	SU 4S jj5       rSS	 jr      SS
 jr      SS jrSS jrSS jrSS jr        SS jr        SS jr        SS jr        SS jr        SS jr        SS jrSrU =r$ )MapperEventsi  a	  Define events specific to mappings.

e.g.::

    from sqlalchemy import event


    def my_before_insert_listener(mapper, connection, target):
        # execute a stored procedure upon INSERT,
        # apply the value to the row to be inserted
        target.calculated_value = connection.execute(
            text("select my_special_function(%d)" % target.special_number)
        ).scalar()


    # associate the listener function with SomeClass,
    # to execute during the "before_insert" hook
    event.listen(SomeClass, "before_insert", my_before_insert_listener)

Available targets include:

* mapped classes
* unmapped superclasses of mapped or to-be-mapped classes
  (using the ``propagate=True`` flag)
* :class:`_orm.Mapper` objects
* the :class:`_orm.Mapper` class itself indicates listening for all
  mappers.

Mapper events provide hooks into critical sections of the
mapper, including those related to object instrumentation,
object loading, and object persistence. In particular, the
persistence methods :meth:`~.MapperEvents.before_insert`,
and :meth:`~.MapperEvents.before_update` are popular
places to augment the state being persisted - however, these
methods operate with several significant restrictions. The
user is encouraged to evaluate the
:meth:`.SessionEvents.before_flush` and
:meth:`.SessionEvents.after_flush` methods as more
flexible and user-friendly hooks in which to apply
additional database state during a flush.

When using :class:`.MapperEvents`, several modifiers are
available to the :func:`.event.listen` function.

:param propagate=False: When True, the event listener should
   be applied to all inheriting mappers and/or the mappers of
   inheriting classes, as well as any
   mapper which is the target of this listener.
:param raw=False: When True, the "target" argument passed
   to applicable event listener functions will be the
   instance's :class:`.InstanceState` management
   object, rather than the mapped instance itself.
:param retval=False: when True, the user-defined event function
   must have a return value, the purpose of which is either to
   control subsequent event propagation, or to otherwise alter
   the operation in progress by the mapper.   Possible return
   values are:

   * ``sqlalchemy.orm.interfaces.EXT_CONTINUE`` - continue event
     processing normally.
   * ``sqlalchemy.orm.interfaces.EXT_STOP`` - cancel all subsequent
     event handlers in the chain.
   * other values - the return value specified by specific listeners.

r   c                .    [         R                  X5        g rD   )_MapperEventsHoldr   )rI   rj   r   s      rL   _new_mapper_instance!MapperEvents._new_mapper_instance0  s     	""62rO   r   c                F   [         R                  R                  nXR                  L a'  [         R                  " SS5        [
        R                  $ [        U[        5      (       a<  [        U[
        R                  5      (       a  U$ [        U5      nUb  U$ [        U5      $ U$ r   )r$   r   r   r   r   r   r:   rE   rF   rR   r   r  )rI   rJ   rK   r   r   s        rL   rM   MapperEvents._accept_with8  s     nn  ZZ  G 	 ###%%&)"2"233(0%!M,V44MrO   c                0  ^^^^ UR                   UR                  UR                  spgmUS;   a)  U[        R                  La  [
        R                  " S5        T(       a  T(       dO  T(       d,  [        X5      n [        U5      S   R                  S5      S-
  mS	UUUU4S jjn	UR                  U	5      nU(       a7  UR                   H&  n
UR                  U
5      R                  " S
SS0UD6  M(     g UR                  " S
0 UD6  g ! [         a    S m N{f = f)N)before_configuredafter_configuredzf'before_configured' and 'after_configured' ORM events only invoke with the Mapper class as the target.r   rJ   r   c                    > T(       d$  Tb!  [        U 5      n U T   R                  5       U T'   T(       d  T" U 0 UD6  [        R                  $ T" U 0 UD6$ rD   )r   r   r   EXT_CONTINUE)rT   ro   rV   r   r   target_indexs     rL   r   "MapperEvents._listen.<locals>.wrapx  sT    |7s)C(+L(9(=(=(?C%NrN%222s>b>)rO   rW   TrT   r   ro   r   rc   r   rf   )rg   rK   rh   r   r:   r$   warnr]   r'   index
ValueErrorrl   self_and_descendantsrk   rm   )rI   rn   r   r   rW   ro   rJ   rK   methr   r   rV   r'  s     ``       @@rL   rp   MapperEvents._listenU  s    %%     	B CCi...II! &s/(.t4Q7==hG!K !* * "..t4I 55..v6BB "&( 6
 !!'B'+ " (#'L(s   9 D DDc                J   > [         TU ]  5         [        R                  5         g rD   )rs   rt   r  ru   s    rL   rt   MapperEvents._clear  s      "rO   c                    g)a  Receive a class when the mapper is first constructed,
before instrumentation is applied to the mapped class.

This event is the earliest phase of mapper construction.
Most attributes of the mapper are not yet initialized.   To
receive an event within initial mapper construction where basic
state is available such as the :attr:`_orm.Mapper.attrs` collection,
the :meth:`_orm.MapperEvents.after_mapper_constructed` event may
be a better choice.

This listener can either be applied to the :class:`_orm.Mapper`
class overall, or to any un-mapped class which serves as a base
for classes that will be mapped (using the ``propagate=True`` flag)::

    Base = declarative_base()


    @event.listens_for(Base, "instrument_class", propagate=True)
    def on_new_class(mapper, cls_):
        "..."

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param class\_: the mapped class.

.. seealso::

    :meth:`_orm.MapperEvents.after_mapper_constructed`

Nrf   rz   r   rj   s      rL   instrument_classMapperEvents.instrument_class  r}   rO   c                    g)a  Receive a class and mapper when the :class:`_orm.Mapper` has been
fully constructed.

This event is called after the initial constructor for
:class:`_orm.Mapper` completes.  This occurs after the
:meth:`_orm.MapperEvents.instrument_class` event and after the
:class:`_orm.Mapper` has done an initial pass of its arguments
to generate its collection of :class:`_orm.MapperProperty` objects,
which are accessible via the :meth:`_orm.Mapper.get_property`
method and the :attr:`_orm.Mapper.iterate_properties` attribute.

This event differs from the
:meth:`_orm.MapperEvents.before_mapper_configured` event in that it
is invoked within the constructor for :class:`_orm.Mapper`, rather
than within the :meth:`_orm.registry.configure` process.   Currently,
this event is the only one which is appropriate for handlers that
wish to create additional mapped classes in response to the
construction of this :class:`_orm.Mapper`, which will be part of the
same configure step when :meth:`_orm.registry.configure` next runs.

.. versionadded:: 2.0.2

.. seealso::

    :ref:`examples_versioning` - an example which illustrates the use
    of the :meth:`_orm.MapperEvents.before_mapper_configured`
    event to create new mappers to record change-audit histories on
    objects.

Nrf   r3  s      rL   after_mapper_constructed%MapperEvents.after_mapper_constructed  r}   rO   c                    g)a  Called right before a specific mapper is to be configured.

This event is intended to allow a specific mapper to be skipped during
the configure step, by returning the :attr:`.orm.interfaces.EXT_SKIP`
symbol which indicates to the :func:`.configure_mappers` call that this
particular mapper (or hierarchy of mappers, if ``propagate=True`` is
used) should be skipped in the current configuration run. When one or
more mappers are skipped, the "new mappers" flag will remain set,
meaning the :func:`.configure_mappers` function will continue to be
called when mappers are used, to continue to try to configure all
available mappers.

In comparison to the other configure-level events,
:meth:`.MapperEvents.before_configured`,
:meth:`.MapperEvents.after_configured`, and
:meth:`.MapperEvents.mapper_configured`, the
:meth:`.MapperEvents.before_mapper_configured` event provides for a
meaningful return value when it is registered with the ``retval=True``
parameter.

.. versionadded:: 1.3

e.g.::

    from sqlalchemy.orm import EXT_SKIP

    Base = declarative_base()

    DontConfigureBase = declarative_base()


    @event.listens_for(
        DontConfigureBase,
        "before_mapper_configured",
        retval=True,
        propagate=True,
    )
    def dont_configure(mapper, cls):
        return EXT_SKIP

.. seealso::

    :meth:`.MapperEvents.before_configured`

    :meth:`.MapperEvents.after_configured`

    :meth:`.MapperEvents.mapper_configured`

Nrf   r3  s      rL   before_mapper_configured%MapperEvents.before_mapper_configured  r}   rO   c                    g)a  Called when a specific mapper has completed its own configuration
within the scope of the :func:`.configure_mappers` call.

The :meth:`.MapperEvents.mapper_configured` event is invoked
for each mapper that is encountered when the
:func:`_orm.configure_mappers` function proceeds through the current
list of not-yet-configured mappers.
:func:`_orm.configure_mappers` is typically invoked
automatically as mappings are first used, as well as each time
new mappers have been made available and new mapper use is
detected.

When the event is called, the mapper should be in its final
state, but **not including backrefs** that may be invoked from
other mappers; they might still be pending within the
configuration operation.    Bidirectional relationships that
are instead configured via the
:paramref:`.orm.relationship.back_populates` argument
*will* be fully available, since this style of relationship does not
rely upon other possibly-not-configured mappers to know that they
exist.

For an event that is guaranteed to have **all** mappers ready
to go including backrefs that are defined only on other
mappings, use the :meth:`.MapperEvents.after_configured`
event; this event invokes only after all known mappings have been
fully configured.

The :meth:`.MapperEvents.mapper_configured` event, unlike
:meth:`.MapperEvents.before_configured` or
:meth:`.MapperEvents.after_configured`,
is called for each mapper/class individually, and the mapper is
passed to the event itself.  It also is called exactly once for
a particular mapper.  The event is therefore useful for
configurational steps that benefit from being invoked just once
on a specific mapper basis, which don't require that "backref"
configurations are necessarily ready yet.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param class\_: the mapped class.

.. seealso::

    :meth:`.MapperEvents.before_configured`

    :meth:`.MapperEvents.after_configured`

    :meth:`.MapperEvents.before_mapper_configured`

Nrf   r3  s      rL   mapper_configuredMapperEvents.mapper_configured  r}   rO   c                    g)a  Called before a series of mappers have been configured.

The :meth:`.MapperEvents.before_configured` event is invoked
each time the :func:`_orm.configure_mappers` function is
invoked, before the function has done any of its work.
:func:`_orm.configure_mappers` is typically invoked
automatically as mappings are first used, as well as each time
new mappers have been made available and new mapper use is
detected.

This event can **only** be applied to the :class:`_orm.Mapper` class,
and not to individual mappings or mapped classes. It is only invoked
for all mappings as a whole::

    from sqlalchemy.orm import Mapper


    @event.listens_for(Mapper, "before_configured")
    def go(): ...

Contrast this event to :meth:`.MapperEvents.after_configured`,
which is invoked after the series of mappers has been configured,
as well as :meth:`.MapperEvents.before_mapper_configured`
and :meth:`.MapperEvents.mapper_configured`, which are both invoked
on a per-mapper basis.

Theoretically this event is called once per
application, but is actually called any time new mappers
are to be affected by a :func:`_orm.configure_mappers`
call.   If new mappings are constructed after existing ones have
already been used, this event will likely be called again.  To ensure
that a particular event is only called once and no further, the
``once=True`` argument (new in 0.9.4) can be applied::

    from sqlalchemy.orm import mapper


    @event.listens_for(mapper, "before_configured", once=True)
    def go(): ...

.. seealso::

    :meth:`.MapperEvents.before_mapper_configured`

    :meth:`.MapperEvents.mapper_configured`

    :meth:`.MapperEvents.after_configured`

Nrf   rz   s    rL   r#  MapperEvents.before_configured>  r}   rO   c                    g)a  Called after a series of mappers have been configured.

The :meth:`.MapperEvents.after_configured` event is invoked
each time the :func:`_orm.configure_mappers` function is
invoked, after the function has completed its work.
:func:`_orm.configure_mappers` is typically invoked
automatically as mappings are first used, as well as each time
new mappers have been made available and new mapper use is
detected.

Contrast this event to the :meth:`.MapperEvents.mapper_configured`
event, which is called on a per-mapper basis while the configuration
operation proceeds; unlike that event, when this event is invoked,
all cross-configurations (e.g. backrefs) will also have been made
available for any mappers that were pending.
Also contrast to :meth:`.MapperEvents.before_configured`,
which is invoked before the series of mappers has been configured.

This event can **only** be applied to the :class:`_orm.Mapper` class,
and not to individual mappings or
mapped classes.  It is only invoked for all mappings as a whole::

    from sqlalchemy.orm import Mapper


    @event.listens_for(Mapper, "after_configured")
    def go(): ...

Theoretically this event is called once per
application, but is actually called any time new mappers
have been affected by a :func:`_orm.configure_mappers`
call.   If new mappings are constructed after existing ones have
already been used, this event will likely be called again.  To ensure
that a particular event is only called once and no further, the
``once=True`` argument (new in 0.9.4) can be applied::

    from sqlalchemy.orm import mapper


    @event.listens_for(mapper, "after_configured", once=True)
    def go(): ...

.. seealso::

    :meth:`.MapperEvents.before_mapper_configured`

    :meth:`.MapperEvents.mapper_configured`

    :meth:`.MapperEvents.before_configured`

Nrf   r@  s    rL   r$  MapperEvents.after_configuredq  r}   rO   c                    g)a  Receive an object instance before an INSERT statement
is emitted corresponding to that instance.

.. note:: this event **only** applies to the
   :ref:`session flush operation <session_flushing>`
   and does **not** apply to the ORM DML operations described at
   :ref:`orm_expression_update_delete`.  To intercept ORM
   DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.

This event is used to modify local, non-object related
attributes on the instance before an INSERT occurs, as well
as to emit additional SQL statements on the given
connection.

The event is often called for a batch of objects of the
same class before their INSERT statements are emitted at
once in a later step. In the extremely rare case that
this is not desirable, the :class:`_orm.Mapper` object can be
configured with ``batch=False``, which will cause
batches of instances to be broken up into individual
(and more poorly performing) event->persist->event
steps.

.. warning::

    Mapper-level flush events only allow **very limited operations**,
    on attributes local to the row being operated upon only,
    as well as allowing any SQL to be emitted on the given
    :class:`_engine.Connection`.  **Please read fully** the notes
    at :ref:`session_persistence_mapper` for guidelines on using
    these methods; generally, the :meth:`.SessionEvents.before_flush`
    method should be preferred for general on-flush changes.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param connection: the :class:`_engine.Connection` being used to
 emit INSERT statements for this instance.  This
 provides a handle into the current transaction on the
 target database specific to this instance.
:param target: the mapped instance being persisted.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:return: No return value is supported by this event.

.. seealso::

    :ref:`session_persistence_events`

Nrf   rz   r   
connectionrJ   s       rL   before_insertMapperEvents.before_insert  r}   rO   c                    g)a  Receive an object instance after an INSERT statement
is emitted corresponding to that instance.

.. note:: this event **only** applies to the
   :ref:`session flush operation <session_flushing>`
   and does **not** apply to the ORM DML operations described at
   :ref:`orm_expression_update_delete`.  To intercept ORM
   DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.

This event is used to modify in-Python-only
state on the instance after an INSERT occurs, as well
as to emit additional SQL statements on the given
connection.

The event is often called for a batch of objects of the
same class after their INSERT statements have been
emitted at once in a previous step. In the extremely
rare case that this is not desirable, the
:class:`_orm.Mapper` object can be configured with ``batch=False``,
which will cause batches of instances to be broken up
into individual (and more poorly performing)
event->persist->event steps.

.. warning::

    Mapper-level flush events only allow **very limited operations**,
    on attributes local to the row being operated upon only,
    as well as allowing any SQL to be emitted on the given
    :class:`_engine.Connection`.  **Please read fully** the notes
    at :ref:`session_persistence_mapper` for guidelines on using
    these methods; generally, the :meth:`.SessionEvents.before_flush`
    method should be preferred for general on-flush changes.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param connection: the :class:`_engine.Connection` being used to
 emit INSERT statements for this instance.  This
 provides a handle into the current transaction on the
 target database specific to this instance.
:param target: the mapped instance being persisted.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:return: No return value is supported by this event.

.. seealso::

    :ref:`session_persistence_events`

Nrf   rE  s       rL   after_insertMapperEvents.after_insert  r}   rO   c                    g)a3  Receive an object instance before an UPDATE statement
is emitted corresponding to that instance.

.. note:: this event **only** applies to the
   :ref:`session flush operation <session_flushing>`
   and does **not** apply to the ORM DML operations described at
   :ref:`orm_expression_update_delete`.  To intercept ORM
   DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.

This event is used to modify local, non-object related
attributes on the instance before an UPDATE occurs, as well
as to emit additional SQL statements on the given
connection.

This method is called for all instances that are
marked as "dirty", *even those which have no net changes
to their column-based attributes*. An object is marked
as dirty when any of its column-based attributes have a
"set attribute" operation called or when any of its
collections are modified. If, at update time, no
column-based attributes have any net changes, no UPDATE
statement will be issued. This means that an instance
being sent to :meth:`~.MapperEvents.before_update` is
*not* a guarantee that an UPDATE statement will be
issued, although you can affect the outcome here by
modifying attributes so that a net change in value does
exist.

To detect if the column-based attributes on the object have net
changes, and will therefore generate an UPDATE statement, use
``object_session(instance).is_modified(instance,
include_collections=False)``.

The event is often called for a batch of objects of the
same class before their UPDATE statements are emitted at
once in a later step. In the extremely rare case that
this is not desirable, the :class:`_orm.Mapper` can be
configured with ``batch=False``, which will cause
batches of instances to be broken up into individual
(and more poorly performing) event->persist->event
steps.

.. warning::

    Mapper-level flush events only allow **very limited operations**,
    on attributes local to the row being operated upon only,
    as well as allowing any SQL to be emitted on the given
    :class:`_engine.Connection`.  **Please read fully** the notes
    at :ref:`session_persistence_mapper` for guidelines on using
    these methods; generally, the :meth:`.SessionEvents.before_flush`
    method should be preferred for general on-flush changes.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param connection: the :class:`_engine.Connection` being used to
 emit UPDATE statements for this instance.  This
 provides a handle into the current transaction on the
 target database specific to this instance.
:param target: the mapped instance being persisted.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:return: No return value is supported by this event.

.. seealso::

    :ref:`session_persistence_events`

Nrf   rE  s       rL   before_updateMapperEvents.before_update  r}   rO   c                    g)a
  Receive an object instance after an UPDATE statement
is emitted corresponding to that instance.

.. note:: this event **only** applies to the
   :ref:`session flush operation <session_flushing>`
   and does **not** apply to the ORM DML operations described at
   :ref:`orm_expression_update_delete`.  To intercept ORM
   DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.

This event is used to modify in-Python-only
state on the instance after an UPDATE occurs, as well
as to emit additional SQL statements on the given
connection.

This method is called for all instances that are
marked as "dirty", *even those which have no net changes
to their column-based attributes*, and for which
no UPDATE statement has proceeded. An object is marked
as dirty when any of its column-based attributes have a
"set attribute" operation called or when any of its
collections are modified. If, at update time, no
column-based attributes have any net changes, no UPDATE
statement will be issued. This means that an instance
being sent to :meth:`~.MapperEvents.after_update` is
*not* a guarantee that an UPDATE statement has been
issued.

To detect if the column-based attributes on the object have net
changes, and therefore resulted in an UPDATE statement, use
``object_session(instance).is_modified(instance,
include_collections=False)``.

The event is often called for a batch of objects of the
same class after their UPDATE statements have been emitted at
once in a previous step. In the extremely rare case that
this is not desirable, the :class:`_orm.Mapper` can be
configured with ``batch=False``, which will cause
batches of instances to be broken up into individual
(and more poorly performing) event->persist->event
steps.

.. warning::

    Mapper-level flush events only allow **very limited operations**,
    on attributes local to the row being operated upon only,
    as well as allowing any SQL to be emitted on the given
    :class:`_engine.Connection`.  **Please read fully** the notes
    at :ref:`session_persistence_mapper` for guidelines on using
    these methods; generally, the :meth:`.SessionEvents.before_flush`
    method should be preferred for general on-flush changes.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param connection: the :class:`_engine.Connection` being used to
 emit UPDATE statements for this instance.  This
 provides a handle into the current transaction on the
 target database specific to this instance.
:param target: the mapped instance being persisted.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:return: No return value is supported by this event.

.. seealso::

    :ref:`session_persistence_events`

Nrf   rE  s       rL   after_updateMapperEvents.after_update[  r}   rO   c                    g)a  Receive an object instance before a DELETE statement
is emitted corresponding to that instance.

.. note:: this event **only** applies to the
   :ref:`session flush operation <session_flushing>`
   and does **not** apply to the ORM DML operations described at
   :ref:`orm_expression_update_delete`.  To intercept ORM
   DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.

This event is used to emit additional SQL statements on
the given connection as well as to perform application
specific bookkeeping related to a deletion event.

The event is often called for a batch of objects of the
same class before their DELETE statements are emitted at
once in a later step.

.. warning::

    Mapper-level flush events only allow **very limited operations**,
    on attributes local to the row being operated upon only,
    as well as allowing any SQL to be emitted on the given
    :class:`_engine.Connection`.  **Please read fully** the notes
    at :ref:`session_persistence_mapper` for guidelines on using
    these methods; generally, the :meth:`.SessionEvents.before_flush`
    method should be preferred for general on-flush changes.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param connection: the :class:`_engine.Connection` being used to
 emit DELETE statements for this instance.  This
 provides a handle into the current transaction on the
 target database specific to this instance.
:param target: the mapped instance being deleted.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:return: No return value is supported by this event.

.. seealso::

    :ref:`session_persistence_events`

Nrf   rE  s       rL   before_deleteMapperEvents.before_delete  r}   rO   c                    g)a  Receive an object instance after a DELETE statement
has been emitted corresponding to that instance.

.. note:: this event **only** applies to the
   :ref:`session flush operation <session_flushing>`
   and does **not** apply to the ORM DML operations described at
   :ref:`orm_expression_update_delete`.  To intercept ORM
   DML events, use :meth:`_orm.SessionEvents.do_orm_execute`.

This event is used to emit additional SQL statements on
the given connection as well as to perform application
specific bookkeeping related to a deletion event.

The event is often called for a batch of objects of the
same class after their DELETE statements have been emitted at
once in a previous step.

.. warning::

    Mapper-level flush events only allow **very limited operations**,
    on attributes local to the row being operated upon only,
    as well as allowing any SQL to be emitted on the given
    :class:`_engine.Connection`.  **Please read fully** the notes
    at :ref:`session_persistence_mapper` for guidelines on using
    these methods; generally, the :meth:`.SessionEvents.before_flush`
    method should be preferred for general on-flush changes.

:param mapper: the :class:`_orm.Mapper` which is the target
 of this event.
:param connection: the :class:`_engine.Connection` being used to
 emit DELETE statements for this instance.  This
 provides a handle into the current transaction on the
 target database specific to this instance.
:param target: the mapped instance being deleted.  If
 the event is configured with ``raw=True``, this will
 instead be the :class:`.InstanceState` state-management
 object associated with the instance.
:return: No return value is supported by this event.

.. seealso::

    :ref:`session_persistence_events`

Nrf   rE  s       rL   after_deleteMapperEvents.after_delete  r}   rO   rf   )rj   r   r   
Mapper[_O]rc   re   )rJ   z9Union[mapperlib.Mapper[Any], Type[mapperlib.Mapper[Any]]]rK   r   rc   zCOptional[Union[mapperlib.Mapper[Any], Type[mapperlib.Mapper[Any]]]]r   )rn   r  r   r   r   r   rW   r   ro   r   rc   re   r   )r   rX  rj   r   rc   re   )r   rX  rF  r2   rJ   r+   rc   re   )r   r   r   r   r   r   r   r:   r   r   r  r$   r   rM   rp   rt   r4  r7  r:  r=  r#  r$  rG  rJ  rM  rP  rS  rV  r   r   r   s   @rL   r  r    sE   @D $ ''3K3 3 
	3 3 	)*I  
M	 + 6  4(!4( 4( 	4(
 4( 4( 
4( 4(l # #@   *2 	 D3 3*23	3j3l1f3j4 4.84BD4	4l4 4.84BD4	4lG G.8GBDG	GRF F.8FBDF	FP. ..8.BD.	.`. ..8.BD.	. .rO   r  c                      \ rS rSr\R
                  " 5       r    SS jr " S S\R                  \
   \5      r\R                  " \5      rSrg)r  i  c                    [        U5      $ rD   r   r   s     rL   r  _MapperEventsHold.resolve  s     v&&rO   c                      \ rS rSrSrg)"_MapperEventsHold.HoldMapperEventsi  rf   Nr  rf   rO   rL   HoldMapperEventsr]    r  rO   r^  rf   N)rj   z(Union[Type[_T], _InternalEntityType[_T]]rc   zOptional[Mapper[_T]])r   r   r   r   ri   r  r   r  r   r	  r&   r  r^  r"   r   r^   r   rf   rO   rL   r  r    sQ    ))+I'>'	'
;11#6   01HrO   r  zSet[str]$_sessionevents_lifecycle_event_namesc                     \ rS rSrSrSr\r    S(S jr\	      S)S j5       r
\	SSS.         S*S jj5       rS+S	 jr      S,S
 jr      S,S jrS-S jrS-S jrS-S jr      S.S jr        S/S jr      S0S jr      S0S jr        S1S jr\S2S j5       r\S2S j5       r\R4                  " S/ SQS 5      S3S j5       r\R4                  " S/ SQS 5      S4S j5       r\S2S j5       r\S2S j5       r\S2S j5       r\S2S j5       r \S2S  j5       r!\S2S! j5       r"\S2S" j5       r#\S2S# j5       r$\S2S$ j5       r%\S2S% j5       r&S&r'g')5SessionEventsi  a  Define events specific to :class:`.Session` lifecycle.

e.g.::

    from sqlalchemy import event
    from sqlalchemy.orm import sessionmaker


    def my_before_commit(session):
        print("before commit!")


    Session = sessionmaker()

    event.listen(Session, "before_commit", my_before_commit)

The :func:`~.event.listen` function will accept
:class:`.Session` objects as well as the return result
of :class:`~.sessionmaker()` and :class:`~.scoped_session()`.

Additionally, it accepts the :class:`.Session` class which
will apply listeners to all :class:`.Session` instances
globally.

:param raw=False: When True, the "target" argument passed
   to applicable event listener functions that work on individual
   objects will be the instance's :class:`.InstanceState` management
   object, rather than the mapped instance itself.

   .. versionadded:: 1.3.14

:param restore_load_context=False: Applies to the
   :meth:`.SessionEvents.loaded_as_persistent` event.  Restores the loader
   context of the object when the event hook is complete, so that ongoing
   eager load operations continue to target the object appropriately.  A
   warning is emitted if the object is moved to a new loader context from
   within this event if this flag is not set.

   .. versionadded:: 1.3.14

SomeSessionClassOrObjectc                D    [         R                  U R                  5        U $ rD   )r_  addr   )rV   s    rL   _lifecycle_eventSessionEvents._lifecycle_eventD  s     	-00=	rO   c                p   [        U[        5      (       aa  UR                  n[        U[        5      (       d@  [        U[        5      (       a  [        U[        5      (       d  [        R                  " S5      e[        U[        5      (       a  UR                  $ [        U[        5      (       a3  [        U[        5      (       a  [        $ [        U[        5      (       a  U$ g [        U[        5      (       a  U$ [        US5      (       a  UR                  5         g [        R                  R                  X5      $ )NzrSession event listen on a scoped_session requires that its creation callable is associated with the Session class._no_async_engine_events)rE   r   session_factoryr    rF   rR   r   r#   ArgumentErrorrj   hasattrrh  r"   EventsrM   rH   s      rL   rM   SessionEvents._accept_withJ  s     fn--++Ffl33vt,,Jvw4O4O''<  fl++== %%&.11FG,, -((MV677**, <<,,V@@rO   F)r   r   c                  ^^^ UR                   [        ;   nU(       a?  T(       a  T(       a1  UR                  m          SUUU4S jjnUR                  U5      nUR                  " S0 UD6  g )Nc                   > T(       d  UR                  5       nUc  g OUnT(       a  UR                  n T" X/UQ70 UD6T(       a  WUl        $ $ ! T(       a  WUl        f f = frD   r   )	sessionr   rT   ro   rJ   r   rV   r   r   s	         rL   r   #SessionEvents._listen.<locals>.wrapy  sl     !&!> $( *
 "'+ %0!'>C>2>/*/EK 0/*/EK 0s   A A )
rp  r   r   r   rT   r   ro   r   rc   rd   rf   )rK   r_  rh   rl   rm   )rI   rn   r   r   ro   is_instance_eventr   rV   s     ``   @rL   rp   SessionEvents._listenh  s       $HH 	 .))0$0,0 0 	0
 #0 0, &2248	##rO   c                    g)a^  Intercept statement executions that occur on behalf of an
ORM :class:`.Session` object.

This event is invoked for all top-level SQL statements invoked from the
:meth:`_orm.Session.execute` method, as well as related methods such as
:meth:`_orm.Session.scalars` and :meth:`_orm.Session.scalar`. As of
SQLAlchemy 1.4, all ORM queries that run through the
:meth:`_orm.Session.execute` method as well as related methods
:meth:`_orm.Session.scalars`, :meth:`_orm.Session.scalar` etc.
will participate in this event.
This event hook does **not** apply to the queries that are
emitted internally within the ORM flush process, i.e. the
process described at :ref:`session_flushing`.

.. note::  The :meth:`_orm.SessionEvents.do_orm_execute` event hook
   is triggered **for ORM statement executions only**, meaning those
   invoked via the :meth:`_orm.Session.execute` and similar methods on
   the :class:`_orm.Session` object. It does **not** trigger for
   statements that are invoked by SQLAlchemy Core only, i.e. statements
   invoked directly using :meth:`_engine.Connection.execute` or
   otherwise originating from an :class:`_engine.Engine` object without
   any :class:`_orm.Session` involved. To intercept **all** SQL
   executions regardless of whether the Core or ORM APIs are in use,
   see the event hooks at :class:`.ConnectionEvents`, such as
   :meth:`.ConnectionEvents.before_execute` and
   :meth:`.ConnectionEvents.before_cursor_execute`.

   Also, this event hook does **not** apply to queries that are
   emitted internally within the ORM flush process,
   i.e. the process described at :ref:`session_flushing`; to
   intercept steps within the flush process, see the event
   hooks described at :ref:`session_persistence_events` as
   well as :ref:`session_persistence_mapper`.

This event is a ``do_`` event, meaning it has the capability to replace
the operation that the :meth:`_orm.Session.execute` method normally
performs.  The intended use for this includes sharding and
result-caching schemes which may seek to invoke the same statement
across  multiple database connections, returning a result that is
merged from each of them, or which don't invoke the statement at all,
instead returning data from a cache.

The hook intends to replace the use of the
``Query._execute_and_instances`` method that could be subclassed prior
to SQLAlchemy 1.4.

:param orm_execute_state: an instance of :class:`.ORMExecuteState`
 which contains all information about the current execution, as well
 as helper functions used to derive other commonly required
 information.   See that object for details.

.. seealso::

    :ref:`session_execute_events` - top level documentation on how
    to use :meth:`_orm.SessionEvents.do_orm_execute`

    :class:`.ORMExecuteState` - the object passed to the
    :meth:`_orm.SessionEvents.do_orm_execute` event which contains
    all information about the statement to be invoked.  It also
    provides an interface to extend the current statement, options,
    and parameters as well as an option that allows programmatic
    invocation of the statement at any point.

    :ref:`examples_session_orm_events` - includes examples of using
    :meth:`_orm.SessionEvents.do_orm_execute`

    :ref:`examples_caching` - an example of how to integrate
    Dogpile caching with the ORM :class:`_orm.Session` making use
    of the :meth:`_orm.SessionEvents.do_orm_execute` event hook.

    :ref:`examples_sharding` - the Horizontal Sharding example /
    extension relies upon the
    :meth:`_orm.SessionEvents.do_orm_execute` event hook to invoke a
    SQL statement on multiple backends and return a merged result.


.. versionadded:: 1.4

Nrf   )rz   orm_execute_states     rL   do_orm_executeSessionEvents.do_orm_execute  r}   rO   c                    g)a  Execute when a new :class:`.SessionTransaction` is created.

This event differs from :meth:`~.SessionEvents.after_begin`
in that it occurs for each :class:`.SessionTransaction`
overall, as opposed to when transactions are begun
on individual database connections.  It is also invoked
for nested transactions and subtransactions, and is always
matched by a corresponding
:meth:`~.SessionEvents.after_transaction_end` event
(assuming normal operation of the :class:`.Session`).

:param session: the target :class:`.Session`.
:param transaction: the target :class:`.SessionTransaction`.

 To detect if this is the outermost
 :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
 SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
 is ``None``::

        @event.listens_for(session, "after_transaction_create")
        def after_transaction_create(session, transaction):
            if transaction.parent is None:
                ...  # work with top-level transaction

 To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
 :attr:`.SessionTransaction.nested` attribute::

        @event.listens_for(session, "after_transaction_create")
        def after_transaction_create(session, transaction):
            if transaction.nested:
                ...  # work with SAVEPOINT transaction

.. seealso::

    :class:`.SessionTransaction`

    :meth:`~.SessionEvents.after_transaction_end`

Nrf   rz   rp  transactions      rL   after_transaction_create&SessionEvents.after_transaction_create  r}   rO   c                    g)a   Execute when the span of a :class:`.SessionTransaction` ends.

This event differs from :meth:`~.SessionEvents.after_commit`
in that it corresponds to all :class:`.SessionTransaction`
objects in use, including those for nested transactions
and subtransactions, and is always matched by a corresponding
:meth:`~.SessionEvents.after_transaction_create` event.

:param session: the target :class:`.Session`.
:param transaction: the target :class:`.SessionTransaction`.

 To detect if this is the outermost
 :class:`.SessionTransaction`, as opposed to a "subtransaction" or a
 SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute
 is ``None``::

        @event.listens_for(session, "after_transaction_create")
        def after_transaction_end(session, transaction):
            if transaction.parent is None:
                ...  # work with top-level transaction

 To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the
 :attr:`.SessionTransaction.nested` attribute::

        @event.listens_for(session, "after_transaction_create")
        def after_transaction_end(session, transaction):
            if transaction.nested:
                ...  # work with SAVEPOINT transaction

.. seealso::

    :class:`.SessionTransaction`

    :meth:`~.SessionEvents.after_transaction_create`

Nrf   ry  s      rL   after_transaction_end#SessionEvents.after_transaction_end  r}   rO   c                    g)a  Execute before commit is called.

.. note::

    The :meth:`~.SessionEvents.before_commit` hook is *not* per-flush,
    that is, the :class:`.Session` can emit SQL to the database
    many times within the scope of a transaction.
    For interception of these events, use the
    :meth:`~.SessionEvents.before_flush`,
    :meth:`~.SessionEvents.after_flush`, or
    :meth:`~.SessionEvents.after_flush_postexec`
    events.

:param session: The target :class:`.Session`.

.. seealso::

    :meth:`~.SessionEvents.after_commit`

    :meth:`~.SessionEvents.after_begin`

    :meth:`~.SessionEvents.after_transaction_create`

    :meth:`~.SessionEvents.after_transaction_end`

Nrf   rz   rp  s     rL   before_commitSessionEvents.before_commit7  r}   rO   c                    g)a  Execute after a commit has occurred.

.. note::

    The :meth:`~.SessionEvents.after_commit` hook is *not* per-flush,
    that is, the :class:`.Session` can emit SQL to the database
    many times within the scope of a transaction.
    For interception of these events, use the
    :meth:`~.SessionEvents.before_flush`,
    :meth:`~.SessionEvents.after_flush`, or
    :meth:`~.SessionEvents.after_flush_postexec`
    events.

.. note::

    The :class:`.Session` is not in an active transaction
    when the :meth:`~.SessionEvents.after_commit` event is invoked,
    and therefore can not emit SQL.  To emit SQL corresponding to
    every transaction, use the :meth:`~.SessionEvents.before_commit`
    event.

:param session: The target :class:`.Session`.

.. seealso::

    :meth:`~.SessionEvents.before_commit`

    :meth:`~.SessionEvents.after_begin`

    :meth:`~.SessionEvents.after_transaction_create`

    :meth:`~.SessionEvents.after_transaction_end`

Nrf   r  s     rL   after_commitSessionEvents.after_commitS  r}   rO   c                    g)a  Execute after a real DBAPI rollback has occurred.

Note that this event only fires when the *actual* rollback against
the database occurs - it does *not* fire each time the
:meth:`.Session.rollback` method is called, if the underlying
DBAPI transaction has already been rolled back.  In many
cases, the :class:`.Session` will not be in
an "active" state during this event, as the current
transaction is not valid.   To acquire a :class:`.Session`
which is active after the outermost rollback has proceeded,
use the :meth:`.SessionEvents.after_soft_rollback` event, checking the
:attr:`.Session.is_active` flag.

:param session: The target :class:`.Session`.

Nrf   r  s     rL   after_rollbackSessionEvents.after_rollbackw  r}   rO   c                    g)a  Execute after any rollback has occurred, including "soft"
rollbacks that don't actually emit at the DBAPI level.

This corresponds to both nested and outer rollbacks, i.e.
the innermost rollback that calls the DBAPI's
rollback() method, as well as the enclosing rollback
calls that only pop themselves from the transaction stack.

The given :class:`.Session` can be used to invoke SQL and
:meth:`.Session.query` operations after an outermost rollback
by first checking the :attr:`.Session.is_active` flag::

    @event.listens_for(Session, "after_soft_rollback")
    def do_something(session, previous_transaction):
        if session.is_active:
            session.execute(text("select * from some_table"))

:param session: The target :class:`.Session`.
:param previous_transaction: The :class:`.SessionTransaction`
 transactional marker object which was just closed.   The current
 :class:`.SessionTransaction` for the given :class:`.Session` is
 available via the :attr:`.Session.transaction` attribute.

Nrf   )rz   rp  previous_transactions      rL   after_soft_rollback!SessionEvents.after_soft_rollback  r}   rO   c                    g)a  Execute before flush process has started.

:param session: The target :class:`.Session`.
:param flush_context: Internal :class:`.UOWTransaction` object
 which handles the details of the flush.
:param instances: Usually ``None``, this is the collection of
 objects which can be passed to the :meth:`.Session.flush` method
 (note this usage is deprecated).

.. seealso::

    :meth:`~.SessionEvents.after_flush`

    :meth:`~.SessionEvents.after_flush_postexec`

    :ref:`session_persistence_events`

Nrf   )rz   rp  r   	instancess       rL   before_flushSessionEvents.before_flush  r}   rO   c                    g)a)  Execute after flush has completed, but before commit has been
called.

Note that the session's state is still in pre-flush, i.e. 'new',
'dirty', and 'deleted' lists still show pre-flush state as well
as the history settings on instance attributes.

.. warning:: This event runs after the :class:`.Session` has emitted
   SQL to modify the database, but **before** it has altered its
   internal state to reflect those changes, including that newly
   inserted objects are placed into the identity map.  ORM operations
   emitted within this event such as loads of related items
   may produce new identity map entries that will immediately
   be replaced, sometimes causing confusing results.  SQLAlchemy will
   emit a warning for this condition as of version 1.3.9.

:param session: The target :class:`.Session`.
:param flush_context: Internal :class:`.UOWTransaction` object
 which handles the details of the flush.

.. seealso::

    :meth:`~.SessionEvents.before_flush`

    :meth:`~.SessionEvents.after_flush_postexec`

    :ref:`session_persistence_events`

Nrf   rz   rp  r   s      rL   after_flushSessionEvents.after_flush  r}   rO   c                    g)a\  Execute after flush has completed, and after the post-exec
state occurs.

This will be when the 'new', 'dirty', and 'deleted' lists are in
their final state.  An actual commit() may or may not have
occurred, depending on whether or not the flush started its own
transaction or participated in a larger transaction.

:param session: The target :class:`.Session`.
:param flush_context: Internal :class:`.UOWTransaction` object
 which handles the details of the flush.


.. seealso::

    :meth:`~.SessionEvents.before_flush`

    :meth:`~.SessionEvents.after_flush`

    :ref:`session_persistence_events`

Nrf   r  s      rL   after_flush_postexec"SessionEvents.after_flush_postexec  r}   rO   c                    g)a  Execute after a transaction is begun on a connection.

.. note:: This event is called within the process of the
  :class:`_orm.Session` modifying its own internal state.
  To invoke SQL operations within this hook, use the
  :class:`_engine.Connection` provided to the event;
  do not run SQL operations using the :class:`_orm.Session`
  directly.

:param session: The target :class:`.Session`.
:param transaction: The :class:`.SessionTransaction`.
:param connection: The :class:`_engine.Connection` object
 which will be used for SQL statements.

.. seealso::

    :meth:`~.SessionEvents.before_commit`

    :meth:`~.SessionEvents.after_commit`

    :meth:`~.SessionEvents.after_transaction_create`

    :meth:`~.SessionEvents.after_transaction_end`

Nrf   )rz   rp  rz  rF  s       rL   after_beginSessionEvents.after_begin  r}   rO   c                    g)zExecute before an instance is attached to a session.

This is called before an add, delete or merge causes
the object to be part of the session.

.. seealso::

    :meth:`~.SessionEvents.after_attach`

    :ref:`session_lifecycle_events`

Nrf   rz   rp  instances      rL   before_attachSessionEvents.before_attach  r}   rO   c                    g)a=  Execute after an instance is attached to a session.

This is called after an add, delete or merge.

.. note::

   As of 0.8, this event fires off *after* the item
   has been fully associated with the session, which is
   different than previous releases.  For event
   handlers that require the object not yet
   be part of session state (such as handlers which
   may autoflush while the target object is not
   yet complete) consider the
   new :meth:`.before_attach` event.

.. seealso::

    :meth:`~.SessionEvents.before_attach`

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   after_attachSessionEvents.after_attach(  r}   rO   z0.9)rp  queryquery_contextresultc                J    U R                   U R                  S U R                  4$ rD   rp  r  r  )update_contexts    rL   <lambda>SessionEvents.<lambda>D  %    ""  !!	 
rO   c                    g)a  Event for after the legacy :meth:`_orm.Query.update` method
has been called.

.. legacy:: The :meth:`_orm.SessionEvents.after_bulk_update` method
   is a legacy event hook as of SQLAlchemy 2.0.   The event
   **does not participate** in :term:`2.0 style` invocations
   using :func:`_dml.update` documented at
   :ref:`orm_queryguide_update_delete_where`.  For 2.0 style use,
   the :meth:`_orm.SessionEvents.do_orm_execute` hook will intercept
   these calls.

:param update_context: an "update context" object which contains
 details about the update, including these attributes:

    * ``session`` - the :class:`.Session` involved
    * ``query`` -the :class:`_query.Query`
      object that this update operation
      was called upon.
    * ``values`` The "values" dictionary that was passed to
      :meth:`_query.Query.update`.
    * ``result`` the :class:`_engine.CursorResult`
      returned as a result of the
      bulk UPDATE operation.

.. versionchanged:: 1.4 the update_context no longer has a
   ``QueryContext`` object associated with it.

.. seealso::

    :meth:`.QueryEvents.before_compile_update`

    :meth:`.SessionEvents.after_bulk_delete`

Nrf   )rz   r  s     rL   after_bulk_updateSessionEvents.after_bulk_updateA  r}   rO   c                J    U R                   U R                  S U R                  4$ rD   r  )delete_contexts    rL   r  r  r  r  rO   c                    g)a-  Event for after the legacy :meth:`_orm.Query.delete` method
has been called.

.. legacy:: The :meth:`_orm.SessionEvents.after_bulk_delete` method
   is a legacy event hook as of SQLAlchemy 2.0.   The event
   **does not participate** in :term:`2.0 style` invocations
   using :func:`_dml.delete` documented at
   :ref:`orm_queryguide_update_delete_where`.  For 2.0 style use,
   the :meth:`_orm.SessionEvents.do_orm_execute` hook will intercept
   these calls.

:param delete_context: a "delete context" object which contains
 details about the update, including these attributes:

    * ``session`` - the :class:`.Session` involved
    * ``query`` -the :class:`_query.Query`
      object that this update operation
      was called upon.
    * ``result`` the :class:`_engine.CursorResult`
      returned as a result of the
      bulk DELETE operation.

.. versionchanged:: 1.4 the update_context no longer has a
   ``QueryContext`` object associated with it.

.. seealso::

    :meth:`.QueryEvents.before_compile_delete`

    :meth:`.SessionEvents.after_bulk_update`

Nrf   )rz   r  s     rL   after_bulk_deleteSessionEvents.after_bulk_deleteo  r}   rO   c                    g)a  Intercept the "transient to pending" transition for a specific
object.

This event is a specialization of the
:meth:`.SessionEvents.after_attach` event which is only invoked
for this specific transition.  It is invoked typically during the
:meth:`.Session.add` call.

:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   transient_to_pending"SessionEvents.transient_to_pending  r}   rO   c                    g)a  Intercept the "pending to transient" transition for a specific
object.

This less common transition occurs when an pending object that has
not been flushed is evicted from the session; this can occur
when the :meth:`.Session.rollback` method rolls back the transaction,
or when the :meth:`.Session.expunge` method is used.

:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   pending_to_transient"SessionEvents.pending_to_transient  r}   rO   c                    g)a  Intercept the "persistent to transient" transition for a specific
object.

This less common transition occurs when an pending object that has
has been flushed is evicted from the session; this can occur
when the :meth:`.Session.rollback` method rolls back the transaction.

:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   persistent_to_transient%SessionEvents.persistent_to_transient  r}   rO   c                    g)a  Intercept the "pending to persistent"" transition for a specific
object.

This event is invoked within the flush process, and is
similar to scanning the :attr:`.Session.new` collection within
the :meth:`.SessionEvents.after_flush` event.  However, in this
case the object has already been moved to the persistent state
when the event is called.

:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   pending_to_persistent#SessionEvents.pending_to_persistent  r}   rO   c                    g)a  Intercept the "detached to persistent" transition for a specific
object.

This event is a specialization of the
:meth:`.SessionEvents.after_attach` event which is only invoked
for this specific transition.  It is invoked typically during the
:meth:`.Session.add` call, as well as during the
:meth:`.Session.delete` call if the object was not previously
associated with the
:class:`.Session` (note that an object marked as "deleted" remains
in the "persistent" state until the flush proceeds).

.. note::

    If the object becomes persistent as part of a call to
    :meth:`.Session.delete`, the object is **not** yet marked as
    deleted when this event is called.  To detect deleted objects,
    check the ``deleted`` flag sent to the
    :meth:`.SessionEvents.persistent_to_detached` to event after the
    flush proceeds, or check the :attr:`.Session.deleted` collection
    within the :meth:`.SessionEvents.before_flush` event if deleted
    objects need to be intercepted before the flush.

:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   detached_to_persistent$SessionEvents.detached_to_persistent  r}   rO   c                    g)a  Intercept the "loaded as persistent" transition for a specific
object.

This event is invoked within the ORM loading process, and is invoked
very similarly to the :meth:`.InstanceEvents.load` event.  However,
the event here is linkable to a :class:`.Session` class or instance,
rather than to a mapper or class hierarchy, and integrates
with the other session lifecycle events smoothly.  The object
is guaranteed to be present in the session's identity map when
this event is called.

.. note:: This event is invoked within the loader process before
   eager loaders may have been completed, and the object's state may
   not be complete.  Additionally, invoking row-level refresh
   operations on the object will place the object into a new loader
   context, interfering with the existing load context.   See the note
   on :meth:`.InstanceEvents.load` for background on making use of the
   :paramref:`.SessionEvents.restore_load_context` parameter, which
   works in the same manner as that of
   :paramref:`.InstanceEvents.restore_load_context`, in  order to
   resolve this scenario.

:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   loaded_as_persistent"SessionEvents.loaded_as_persistent	  r}   rO   c                    g)a  Intercept the "persistent to deleted" transition for a specific
object.

This event is invoked when a persistent object's identity
is deleted from the database within a flush, however the object
still remains associated with the :class:`.Session` until the
transaction completes.

If the transaction is rolled back, the object moves again
to the persistent state, and the
:meth:`.SessionEvents.deleted_to_persistent` event is called.
If the transaction is committed, the object becomes detached,
which will emit the :meth:`.SessionEvents.deleted_to_detached`
event.

Note that while the :meth:`.Session.delete` method is the primary
public interface to mark an object as deleted, many objects
get deleted due to cascade rules, which are not always determined
until flush time.  Therefore, there's no way to catch
every object that will be deleted until the flush has proceeded.
the :meth:`.SessionEvents.persistent_to_deleted` event is therefore
invoked at the end of a flush.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   persistent_to_deleted#SessionEvents.persistent_to_deleted0	  r}   rO   c                    g)aE  Intercept the "deleted to persistent" transition for a specific
object.

This transition occurs only when an object that's been deleted
successfully in a flush is restored due to a call to
:meth:`.Session.rollback`.   The event is not called under
any other circumstances.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   deleted_to_persistent#SessionEvents.deleted_to_persistentO	  r}   rO   c                    g)a|  Intercept the "deleted to detached" transition for a specific
object.

This event is invoked when a deleted object is evicted
from the session.   The typical case when this occurs is when
the transaction for a :class:`.Session` in which the object
was deleted is committed; the object moves from the deleted
state to the detached state.

It is also invoked for objects that were deleted in a flush
when the :meth:`.Session.expunge_all` or :meth:`.Session.close`
events are called, as well as if the object is individually
expunged from its deleted state via :meth:`.Session.expunge`.

.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   deleted_to_detached!SessionEvents.deleted_to_detached_	  r}   rO   c                    g)a  Intercept the "persistent to detached" transition for a specific
object.

This event is invoked when a persistent object is evicted
from the session.  There are many conditions that cause this
to happen, including:

* using a method such as :meth:`.Session.expunge`
  or :meth:`.Session.close`

* Calling the :meth:`.Session.rollback` method, when the object
  was part of an INSERT statement for that session's transaction


:param session: target :class:`.Session`

:param instance: the ORM-mapped instance being operated upon.

:param deleted: boolean.  If True, indicates this object moved
 to the detached state because it was marked as deleted and flushed.


.. seealso::

    :ref:`session_lifecycle_events`

Nrf   r  s      rL   persistent_to_detached$SessionEvents.persistent_to_detachedu	  r}   rO   rf   N)rV   -Callable[[SessionEvents, Session, Any], None]rc   r  )rJ   r   rK   r   rc   zUnion[Session, type])
rn   r   r   r   r   r   ro   r   rc   re   )ru  r/   rc   re   )rp  r   rz  r0   rc   re   )rp  r   rc   re   )rp  r   r  r0   rc   re   )rp  r   r   r1   r  zOptional[Sequence[_O]]rc   re   )rp  r   r   r1   rc   re   )rp  r   rz  r0   rF  r2   rc   re   )rp  r   r  r+   rc   re   )r  r+   rc   re   )r  r+   rc   re   )(r   r   r   r   r   r   r   r   re  r   rM   rp   rv  r{  r~  r  r  r  r  r  r  r  r  r  r  r"   _legacy_signaturer  r  r  r  r  r  r  r  r  r  r  r  r   rf   rO   rL   ra  ra    s   (T 39	6 AA&)A	A A: 
 %*($($ 	($
 #($ ($ 
($ ($TOb))-?)	)V&&-?&	&P8"H$6H	8 & *	
 
2/=	B/=	4 ( 	
 
@    0 7	
	"	"H 7	
	 	 D  &  &  $  (    D  B  <    *  rO   ra  c                     \ rS rSrSrSr\r\      SS j5       r	\
      SS j5       r\
     S             SS jj5       r\S.         SS jjr\S.         SS	 jjrS
S.         SS jjr\S.         SS jjr          SS jr        SS jr        SS jr        SS jrSS jrSrg
) AttributeEventsi	  ao
  Define events for object attributes.

These are typically defined on the class-bound descriptor for the
target class.

For example, to register a listener that will receive the
:meth:`_orm.AttributeEvents.append` event::

    from sqlalchemy import event


    @event.listens_for(MyClass.collection, "append", propagate=True)
    def my_append_listener(target, value, initiator):
        print("received append event for target: %s" % target)

Listeners have the option to return a possibly modified version of the
value, when the :paramref:`.AttributeEvents.retval` flag is passed to
:func:`.event.listen` or :func:`.event.listens_for`, such as below,
illustrated using the :meth:`_orm.AttributeEvents.set` event::

    def validate_phone(target, value, oldvalue, initiator):
        "Strip non-numeric characters from a phone number"

        return re.sub(r"\D", "", value)


    # setup listener on UserContact.phone attribute, instructing
    # it to use the return value
    listen(UserContact.phone, "set", validate_phone, retval=True)

A validation function like the above can also raise an exception
such as :exc:`ValueError` to halt the operation.

The :paramref:`.AttributeEvents.propagate` flag is also important when
applying listeners to mapped classes that also have mapped subclasses,
as when using mapper inheritance patterns::


    @event.listens_for(MySuperClass.attr, "set", propagate=True)
    def receive_set(target, value, initiator):
        print("value set: %s" % target)

The full list of modifiers available to the :func:`.event.listen`
and :func:`.event.listens_for` functions are below.

:param active_history=False: When True, indicates that the
  "set" event would like to receive the "old" value being
  replaced unconditionally, even if this requires firing off
  database loads. Note that ``active_history`` can also be
  set directly via :func:`.column_property` and
  :func:`_orm.relationship`.

:param propagate=False: When True, the listener function will
  be established not just for the class attribute given, but
  for attributes of the same name on all current subclasses
  of that class, as well as all future subclasses of that
  class, using an additional listener that listens for
  instrumentation events.
:param raw=False: When True, the "target" argument to the
  event will be the :class:`.InstanceState` management
  object, rather than the mapped instance itself.
:param retval=False: when True, the user-defined event
  listening must return the "value" argument from the
  function.  This gives the listening function the opportunity
  to change the value that is ultimately used for a "set"
  or "append" event.

zSomeClass.some_attributec                R    [         R                  R                  X5      nSUl        U$ )NF)r"   rl  _set_dispatch_active_history)rI   dispatch_clsr^   s      rL   r  AttributeEvents._set_dispatch	  s%     <<--c@',$rO   c                    [        U[        R                  5      (       a*  [        UR                  R
                  UR                  5      $ U$ rD   )rE   r   MapperPropertyr]   parentrj   ra   rH   s      rL   rM   AttributeEvents._accept_with	  s7     fj77886==//<<MrO   c                  ^^^^ UR                   UR                  snmU(       a  SUR                  l        T(       a  T(       a  T(       d  SUUUU4S jjnUR	                  U5      nUR                  US9  U(       a  [        R                  " UR                  5      n	U	R                  S5       HS  n
UR                  XR                     5      R                  SS9  U(       d  M6  SXR                     R                  l        MU     g g )NTc                   > T(       d  U R                  5       n T(       d/  U(       a  US   nOS nT(       a  T" U /UQ70 UD6  U$ T" U /UQ76   U$ T(       a  T" U /UQ70 UD6$ T" U /UQ76 $ Nr   )r   )rJ   rT   ro   valuerV   include_keyr   r   s       rL   r   %AttributeEvents._listen.<locals>.wrap
  s}    #ZZ\F #A $"6.C.2. !L 6(C( L"!&535"55!&/3//rO   r   )rJ   r   rT   r   ro   r   rc   r   )rg   rh   r^   r  rl   rm   r   manager_of_classrj   r   rk   ra   )rI   rn   active_historyr   r   rW   r  rJ   r   r   r   rV   s      `` `    @rL   rp   AttributeEvents._listen	  s     ..	0D0D
.2FOO+&0 0& "..t4I	2%66v}}EG006..s::?KK" L  ">?CC

O,,< 7 rO   )ra   c                   g)aA  Receive a collection append event.

The append event is invoked for each element as it is appended
to the collection.  This occurs for single-item appends as well
as for a "bulk replace" operation.

:param target: the object instance receiving the event.
  If the listener is registered with ``raw=True``, this will
  be the :class:`.InstanceState` object.
:param value: the value being appended.  If this listener
  is registered with ``retval=True``, the listener
  function must return this value, or a new value which
  replaces it.
:param initiator: An instance of :class:`.attributes.Event`
  representing the initiation of the event.  May be modified
  from its original value by backref handlers in order to control
  chained event propagation, as well as be inspected for information
  about the source of the event.
:param key: When the event is established using the
 :paramref:`.AttributeEvents.include_key` parameter set to
 True, this will be the key used in the operation, such as
 ``collection[some_key_or_index] = value``.
 The parameter is not passed
 to the event at all if the the
 :paramref:`.AttributeEvents.include_key`
 was not used to set up the event; this is to allow backwards
 compatibility with existing event handlers that don't include the
 ``key`` parameter.

 .. versionadded:: 2.0

:return: if the event was registered with ``retval=True``,
 the given value, or a new effective value, should be returned.

.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

    :meth:`.AttributeEvents.bulk_replace`

Nrf   rz   rJ   r  	initiatorra   s        rL   appendAttributeEvents.append#
  r}   rO   c                   g)af  Receive a collection append event where the collection was not
actually mutated.

This event differs from :meth:`_orm.AttributeEvents.append` in that
it is fired off for de-duplicating collections such as sets and
dictionaries, when the object already exists in the target collection.
The event does not have a return value and the identity of the
given object cannot be changed.

The event is used for cascading objects into a :class:`_orm.Session`
when the collection has already been mutated via a backref event.

:param target: the object instance receiving the event.
  If the listener is registered with ``raw=True``, this will
  be the :class:`.InstanceState` object.
:param value: the value that would be appended if the object did not
  already exist in the collection.
:param initiator: An instance of :class:`.attributes.Event`
  representing the initiation of the event.  May be modified
  from its original value by backref handlers in order to control
  chained event propagation, as well as be inspected for information
  about the source of the event.
:param key: When the event is established using the
 :paramref:`.AttributeEvents.include_key` parameter set to
 True, this will be the key used in the operation, such as
 ``collection[some_key_or_index] = value``.
 The parameter is not passed
 to the event at all if the the
 :paramref:`.AttributeEvents.include_key`
 was not used to set up the event; this is to allow backwards
 compatibility with existing event handlers that don't include the
 ``key`` parameter.

 .. versionadded:: 2.0

:return: No return value is defined for this event.

.. versionadded:: 1.4.15

Nrf   r  s        rL   append_wo_mutation"AttributeEvents.append_wo_mutationV
  r}   rO   N)keysc                   g)a	  Receive a collection 'bulk replace' event.

This event is invoked for a sequence of values as they are incoming
to a bulk collection set operation, which can be
modified in place before the values are treated as ORM objects.
This is an "early hook" that runs before the bulk replace routine
attempts to reconcile which objects are already present in the
collection and which are being removed by the net replace operation.

It is typical that this method be combined with use of the
:meth:`.AttributeEvents.append` event.    When using both of these
events, note that a bulk replace operation will invoke
the :meth:`.AttributeEvents.append` event for all new items,
even after :meth:`.AttributeEvents.bulk_replace` has been invoked
for the collection as a whole.  In order to determine if an
:meth:`.AttributeEvents.append` event is part of a bulk replace,
use the symbol :attr:`~.attributes.OP_BULK_REPLACE` to test the
incoming initiator::

    from sqlalchemy.orm.attributes import OP_BULK_REPLACE


    @event.listens_for(SomeObject.collection, "bulk_replace")
    def process_collection(target, values, initiator):
        values[:] = [_make_value(value) for value in values]


    @event.listens_for(SomeObject.collection, "append", retval=True)
    def process_collection(target, value, initiator):
        # make sure bulk_replace didn't already do it
        if initiator is None or initiator.op is not OP_BULK_REPLACE:
            return _make_value(value)
        else:
            return value

.. versionadded:: 1.2

:param target: the object instance receiving the event.
  If the listener is registered with ``raw=True``, this will
  be the :class:`.InstanceState` object.
:param value: a sequence (e.g. a list) of the values being set.  The
  handler can modify this list in place.
:param initiator: An instance of :class:`.attributes.Event`
  representing the initiation of the event.
:param keys: When the event is established using the
 :paramref:`.AttributeEvents.include_key` parameter set to
 True, this will be the sequence of keys used in the operation,
 typically only for a dictionary update.  The parameter is not passed
 to the event at all if the the
 :paramref:`.AttributeEvents.include_key`
 was not used to set up the event; this is to allow backwards
 compatibility with existing event handlers that don't include the
 ``key`` parameter.

 .. versionadded:: 2.0

.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.


Nrf   )rz   rJ   r  r  r  s        rL   bulk_replaceAttributeEvents.bulk_replace
  r}   rO   c                   g)aT  Receive a collection remove event.

:param target: the object instance receiving the event.
  If the listener is registered with ``raw=True``, this will
  be the :class:`.InstanceState` object.
:param value: the value being removed.
:param initiator: An instance of :class:`.attributes.Event`
  representing the initiation of the event.  May be modified
  from its original value by backref handlers in order to control
  chained event propagation.

:param key: When the event is established using the
 :paramref:`.AttributeEvents.include_key` parameter set to
 True, this will be the key used in the operation, such as
 ``del collection[some_key_or_index]``.  The parameter is not passed
 to the event at all if the the
 :paramref:`.AttributeEvents.include_key`
 was not used to set up the event; this is to allow backwards
 compatibility with existing event handlers that don't include the
 ``key`` parameter.

 .. versionadded:: 2.0

:return: No return value is defined for this event.


.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

Nrf   r  s        rL   r_   AttributeEvents.remove
  r}   rO   c                    g)ag  Receive a scalar set event.

:param target: the object instance receiving the event.
  If the listener is registered with ``raw=True``, this will
  be the :class:`.InstanceState` object.
:param value: the value being set.  If this listener
  is registered with ``retval=True``, the listener
  function must return this value, or a new value which
  replaces it.
:param oldvalue: the previous value being replaced.  This
  may also be the symbol ``NEVER_SET`` or ``NO_VALUE``.
  If the listener is registered with ``active_history=True``,
  the previous value of the attribute will be loaded from
  the database if the existing value is currently unloaded
  or expired.
:param initiator: An instance of :class:`.attributes.Event`
  representing the initiation of the event.  May be modified
  from its original value by backref handlers in order to control
  chained event propagation.

:return: if the event was registered with ``retval=True``,
 the given value, or a new effective value, should be returned.

.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

Nrf   )rz   rJ   r  oldvaluer  s        rL   setAttributeEvents.set
  r}   rO   c                    g)a  Receive a scalar "init" event.

This event is invoked when an uninitialized, unpersisted scalar
attribute is accessed, e.g. read::


    x = my_object.some_attribute

The ORM's default behavior when this occurs for an un-initialized
attribute is to return the value ``None``; note this differs from
Python's usual behavior of raising ``AttributeError``.    The
event here can be used to customize what value is actually returned,
with the assumption that the event listener would be mirroring
a default generator that is configured on the Core
:class:`_schema.Column`
object as well.

Since a default generator on a :class:`_schema.Column`
might also produce
a changing value such as a timestamp, the
:meth:`.AttributeEvents.init_scalar`
event handler can also be used to **set** the newly returned value, so
that a Core-level default generation function effectively fires off
only once, but at the moment the attribute is accessed on the
non-persisted object.   Normally, no change to the object's state
is made when an uninitialized attribute is accessed (much older
SQLAlchemy versions did in fact change the object's state).

If a default generator on a column returned a particular constant,
a handler might be used as follows::

    SOME_CONSTANT = 3.1415926


    class MyClass(Base):
        # ...

        some_attribute = Column(Numeric, default=SOME_CONSTANT)


    @event.listens_for(
        MyClass.some_attribute, "init_scalar", retval=True, propagate=True
    )
    def _init_some_attribute(target, dict_, value):
        dict_["some_attribute"] = SOME_CONSTANT
        return SOME_CONSTANT

Above, we initialize the attribute ``MyClass.some_attribute`` to the
value of ``SOME_CONSTANT``.   The above code includes the following
features:

* By setting the value ``SOME_CONSTANT`` in the given ``dict_``,
  we indicate that this value is to be persisted to the database.
  This supersedes the use of ``SOME_CONSTANT`` in the default generator
  for the :class:`_schema.Column`.  The ``active_column_defaults.py``
  example given at :ref:`examples_instrumentation` illustrates using
  the same approach for a changing default, e.g. a timestamp
  generator.    In this particular example, it is not strictly
  necessary to do this since ``SOME_CONSTANT`` would be part of the
  INSERT statement in either case.

* By establishing the ``retval=True`` flag, the value we return
  from the function will be returned by the attribute getter.
  Without this flag, the event is assumed to be a passive observer
  and the return value of our function is ignored.

* The ``propagate=True`` flag is significant if the mapped class
  includes inheriting subclasses, which would also make use of this
  event listener.  Without this flag, an inheriting subclass will
  not use our event handler.

In the above example, the attribute set event
:meth:`.AttributeEvents.set` as well as the related validation feature
provided by :obj:`_orm.validates` is **not** invoked when we apply our
value to the given ``dict_``.  To have these events to invoke in
response to our newly generated value, apply the value to the given
object as a normal attribute set operation::

    SOME_CONSTANT = 3.1415926


    @event.listens_for(
        MyClass.some_attribute, "init_scalar", retval=True, propagate=True
    )
    def _init_some_attribute(target, dict_, value):
        # will also fire off attribute set events
        target.some_attribute = SOME_CONSTANT
        return SOME_CONSTANT

When multiple listeners are set up, the generation of the value
is "chained" from one listener to the next by passing the value
returned by the previous listener that specifies ``retval=True``
as the ``value`` argument of the next listener.

:param target: the object instance receiving the event.
 If the listener is registered with ``raw=True``, this will
 be the :class:`.InstanceState` object.
:param value: the value that is to be returned before this event
 listener were invoked.  This value begins as the value ``None``,
 however will be the return value of the previous event handler
 function if multiple listeners are present.
:param dict\_: the attribute dictionary of this mapped object.
 This is normally the ``__dict__`` of the object, but in all cases
 represents the destination that the attribute system uses to get
 at the actual value of this attribute.  Placing the value in this
 dictionary has the effect that the value will be used in the
 INSERT statement generated by the unit of work.


.. seealso::

    :meth:`.AttributeEvents.init_collection` - collection version
    of this event

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

    :ref:`examples_instrumentation` - see the
    ``active_column_defaults.py`` example.

Nrf   )rz   rJ   r  dict_s       rL   init_scalarAttributeEvents.init_scalar  r}   rO   c                    g)a  Receive a 'collection init' event.

This event is triggered for a collection-based attribute, when
the initial "empty collection" is first generated for a blank
attribute, as well as for when the collection is replaced with
a new one, such as via a set event.

E.g., given that ``User.addresses`` is a relationship-based
collection, the event is triggered here::

    u1 = User()
    u1.addresses.append(a1)  #  <- new collection

and also during replace operations::

    u1.addresses = [a2, a3]  #  <- new collection

:param target: the object instance receiving the event.
 If the listener is registered with ``raw=True``, this will
 be the :class:`.InstanceState` object.
:param collection: the new collection.  This will always be generated
 from what was specified as
 :paramref:`_orm.relationship.collection_class`, and will always
 be empty.
:param collection_adapter: the :class:`.CollectionAdapter` that will
 mediate internal access to the collection.

.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

    :meth:`.AttributeEvents.init_scalar` - "scalar" version of this
    event.

Nrf   rz   rJ   r  collection_adapters       rL   init_collectionAttributeEvents.init_collection  r}   rO   c                    g)ac  Receive a 'collection dispose' event.

This event is triggered for a collection-based attribute when
a collection is replaced, that is::

    u1.addresses.append(a1)

    u1.addresses = [a2, a3]  # <- old collection is disposed

The old collection received will contain its previous contents.

.. versionchanged:: 1.2 The collection passed to
   :meth:`.AttributeEvents.dispose_collection` will now have its
   contents before the dispose intact; previously, the collection
   would be empty.

.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

Nrf   r   s       rL   dispose_collection"AttributeEvents.dispose_collection  r}   rO   c                    g)aV  Receive a 'modified' event.

This event is triggered when the :func:`.attributes.flag_modified`
function is used to trigger a modify event on an attribute without
any specific value being set.

.. versionadded:: 1.2

:param target: the object instance receiving the event.
  If the listener is registered with ``raw=True``, this will
  be the :class:`.InstanceState` object.

:param initiator: An instance of :class:`.attributes.Event`
  representing the initiation of the event.

.. seealso::

    :class:`.AttributeEvents` - background on listener options such
    as propagation to subclasses.

Nrf   )rz   rJ   r  s      rL   modifiedAttributeEvents.modified  r}   rO   rf   )rI   zType[_HasEventsDispatch[Any]]r  zType[_Dispatch[Any]]rc   z_Dispatch[Any])rJ   =Union[QueryableAttribute[Any], Type[QueryableAttribute[Any]]]rK   r   rc   r
  )FFFFF)rn   z"_EventKey[QueryableAttribute[Any]]r  r   r   r   r   r   rW   r   r  r   rc   re   )
rJ   r+   r  r,   r  r-   ra   r.   rc   zOptional[_T])
rJ   r+   r  r,   r  r-   ra   r.   rc   re   )
rJ   r+   r  zIterable[_T]r  r-   r  z"Optional[Iterable[EventConstants]]rc   re   )
rJ   r+   r  r,   r  r,   r  r-   rc   re   )rJ   r+   r  r,   r  zDict[Any, Any]rc   re   )rJ   r+   r  zType[Collection[Any]]r  r6   rc   re   )rJ   r+   r  zCollection[Any]r  r6   rc   re   )rJ   r+   r  r-   rc   re   )r   r   r   r   r   r   r   r   staticmethodr  r   rM   rp   r   r  r  r  r_   r  r  r  r  r  r   rf   rO   rL   r  r  	  s   CJ 3)*:N	  	M	 	 
G		 	   %!/D5/D /D 	/D
 /D /D /D 
/D /Dn %11 1 	1 1 
1r %// / 	/ / 
/n 48FF F 	F 1F 
F\ %'' ' 	' ' 
'R!#/1>C	B{{!#{,:{	{z)) *) .	)
 
)V $ .	
 
:rO   r  c                      \ rS rSrSrSr\rS
S jr      SS jr	      SS jr
\  S         SS jj5       rSrg	)QueryEventsi  a  Represent events within the construction of a :class:`_query.Query`
object.

.. legacy:: The :class:`_orm.QueryEvents` event methods are legacy
    as of SQLAlchemy 2.0, and only apply to direct use of the
    :class:`_orm.Query` object. They are not used for :term:`2.0 style`
    statements. For events to intercept and modify 2.0 style ORM use,
    use the :meth:`_orm.SessionEvents.do_orm_execute` hook.


The :class:`_orm.QueryEvents` hooks are now superseded by the
:meth:`_orm.SessionEvents.do_orm_execute` event hook.

	SomeQueryc                    g)a	  Receive the :class:`_query.Query`
object before it is composed into a
core :class:`_expression.Select` object.

.. deprecated:: 1.4  The :meth:`_orm.QueryEvents.before_compile` event
   is superseded by the much more capable
   :meth:`_orm.SessionEvents.do_orm_execute` hook.   In version 1.4,
   the :meth:`_orm.QueryEvents.before_compile` event is **no longer
   used** for ORM-level attribute loads, such as loads of deferred
   or expired attributes as well as relationship loaders.   See the
   new examples in :ref:`examples_session_orm_events` which
   illustrate new ways of intercepting and modifying ORM queries
   for the most common purpose of adding arbitrary filter criteria.


This event is intended to allow changes to the query given::

    @event.listens_for(Query, "before_compile", retval=True)
    def no_deleted(query):
        for desc in query.column_descriptions:
            if desc["type"] is User:
                entity = desc["entity"]
                query = query.filter(entity.deleted == False)
        return query

The event should normally be listened with the ``retval=True``
parameter set, so that the modified query may be returned.

The :meth:`.QueryEvents.before_compile` event by default
will disallow "baked" queries from caching a query, if the event
hook returns a new :class:`_query.Query` object.
This affects both direct
use of the baked query extension as well as its operation within
lazy loaders and eager loaders for relationships.  In order to
re-establish the query being cached, apply the event adding the
``bake_ok`` flag::

    @event.listens_for(Query, "before_compile", retval=True, bake_ok=True)
    def my_event(query):
        for desc in query.column_descriptions:
            if desc["type"] is User:
                entity = desc["entity"]
                query = query.filter(entity.deleted == False)
        return query

When ``bake_ok`` is set to True, the event hook will only be invoked
once, and not called for subsequent invocations of a particular query
that is being cached.

.. versionadded:: 1.3.11  - added the "bake_ok" flag to the
   :meth:`.QueryEvents.before_compile` event and disallowed caching via
   the "baked" extension from occurring for event handlers that
   return  a new :class:`_query.Query` object if this flag is not set.

.. seealso::

    :meth:`.QueryEvents.before_compile_update`

    :meth:`.QueryEvents.before_compile_delete`

    :ref:`baked_with_before_compile`

Nrf   )rz   r  s     rL   before_compileQueryEvents.before_compile	  r}   rO   c                    g)a  Allow modifications to the :class:`_query.Query` object within
:meth:`_query.Query.update`.

.. deprecated:: 1.4  The :meth:`_orm.QueryEvents.before_compile_update`
   event is superseded by the much more capable
   :meth:`_orm.SessionEvents.do_orm_execute` hook.

Like the :meth:`.QueryEvents.before_compile` event, if the event
is to be used to alter the :class:`_query.Query` object, it should
be configured with ``retval=True``, and the modified
:class:`_query.Query` object returned, as in ::

    @event.listens_for(Query, "before_compile_update", retval=True)
    def no_deleted(query, update_context):
        for desc in query.column_descriptions:
            if desc["type"] is User:
                entity = desc["entity"]
                query = query.filter(entity.deleted == False)

                update_context.values["timestamp"] = datetime.datetime.now(
                    datetime.UTC
                )
        return query

The ``.values`` dictionary of the "update context" object can also
be modified in place as illustrated above.

:param query: a :class:`_query.Query` instance; this is also
 the ``.query`` attribute of the given "update context"
 object.

:param update_context: an "update context" object which is
 the same kind of object as described in
 :paramref:`.QueryEvents.after_bulk_update.update_context`.
 The object has a ``.values`` attribute in an UPDATE context which is
 the dictionary of parameters passed to :meth:`_query.Query.update`.
 This
 dictionary can be modified to alter the VALUES clause of the
 resulting UPDATE statement.

.. versionadded:: 1.2.17

.. seealso::

    :meth:`.QueryEvents.before_compile`

    :meth:`.QueryEvents.before_compile_delete`


Nrf   )rz   r  r  s      rL   before_compile_update!QueryEvents.before_compile_updateJ  r}   rO   c                    g)a  Allow modifications to the :class:`_query.Query` object within
:meth:`_query.Query.delete`.

.. deprecated:: 1.4  The :meth:`_orm.QueryEvents.before_compile_delete`
   event is superseded by the much more capable
   :meth:`_orm.SessionEvents.do_orm_execute` hook.

Like the :meth:`.QueryEvents.before_compile` event, this event
should be configured with ``retval=True``, and the modified
:class:`_query.Query` object returned, as in ::

    @event.listens_for(Query, "before_compile_delete", retval=True)
    def no_deleted(query, delete_context):
        for desc in query.column_descriptions:
            if desc["type"] is User:
                entity = desc["entity"]
                query = query.filter(entity.deleted == False)
        return query

:param query: a :class:`_query.Query` instance; this is also
 the ``.query`` attribute of the given "delete context"
 object.

:param delete_context: a "delete context" object which is
 the same kind of object as described in
 :paramref:`.QueryEvents.after_bulk_delete.delete_context`.

.. versionadded:: 1.2.17

.. seealso::

    :meth:`.QueryEvents.before_compile`

    :meth:`.QueryEvents.before_compile_update`


Nrf   )rz   r  r  s      rL   before_compile_delete!QueryEvents.before_compile_delete  r}   rO   c                   ^^ UR                   mT(       d  SUU4S jjnUR                  U5      nOSU4S jjnUR                  U5      nX5l        UR                  " S0 UD6  g )Nc                 @   > T(       d  U S   nT" U 0 UD6  U$ T" U 0 UD6$ r  rf   )rT   ro   r  rV   r   s      rL   r   !QueryEvents._listen.<locals>.wrap  s-    FENrN Ls>b>)rO   c                    > T" U 0 UD6$ rD   rf   )rT   ro   rV   s     rL   r   r    s    3~"~%rO   r)  rf   )rh   rl   _bake_okrm   )rI   rn   r   bake_okro   r   rV   s     `   @rL   rp   QueryEvents._listen  s\     !!* * "..t4I& "..t4I##rO   rf   N)r  
Query[Any]rc   re   )r  r  r  r   rc   re   )r  r  r  r   rc   re   )FF)
rn   r  r   r   r  r   ro   r   rc   re   )r   r   r   r   r   r   r   r   r  r  r  r   rp   r   rf   rO   rL   r  r    s     $?B441;4	4l''1;'	'R  	$!$ $ 	$
 $ 
$ $rO   r  )\r   
__future__r   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   ri    r   r   r   
attributesr   baser   r   r   r   r  r   r   r   scopingr   rp  r   r    r"   r#   r$   r%   event.registryr&   util.compatr'   r(   _typingr)   r*   r+   r,   r-   r.   r/   r0   
unitofworkr1   enginer2   
event.baser3   r4   r5   orm.collectionsr6   orm.contextr7   orm.decl_apir8   r9   
orm.mapperr:   	orm.stater;   r<   r>   rl  r@   rG   r   RefCollectionr   r   r  r  r  r_  r  ra  r  r  rf   rO   rL   <module>r2     s   #                   * !  ) 3    #  !       0%&,!$(+*#&/*3*<.#)e3v[)p8ELL)?@ p8f	7 	7oU\\,s"34 od\%%%c* \~4+c* 4W5<<	 0 0 56 Wt2C( 2 25 $h 6|ELL) |~_	ell#5c#:; _	DQ$%,,uSz* Q$rO   