Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
events.cpython-313.pyc712 linesDownload Raw Back to __pycache__
1�

2��jݕ����SSKJr SSKrSSKJr SSKJr SSKJr SSKJr SSKJr SSKJr S	S3K	J4r5 S	SK	Jr S	SKJ
r
 S	S
KJr S	SKJr S	SKJr SSKJr SSKJr SSKJr \R,(aHS	SKJr S	SKJr S	SKJr S	SKJr S	SKJr S	SKJr S	SKJr S	SKJr S	SKJ r  SSK!J"r" SSK#J$r$ SSK%J&r& "S S!\RN\
5r("S"S#\RN\5r)g)$�)�annotationsN)�Any)�Dict)�Optional)�Tuple)�Type)�Union�)�6Connection)�Engine)�ConnectionEventsTarget)�DBAPIConnection)�DBAPICursor)�Dialect�)�event)�exc)�Literal)�_CoreMultiExecuteParams)�_CoreSingleExecuteParams)�_DBAPIAnyExecuteParams)�_DBAPIMultiExecuteParams)�_DBAPISingleExecuteParams)�_ExecuteOptions)�ExceptionContext)�ExecutionContext)�Result)�ConnectionPoolEntry)�7Executable)�
BindParameterc�^�\rSrSrSrSr\r\S%U4Sjj5r	\SS.S&Sjj5r8\R"S/S	QS95S'Sj5r
\R"S/S
QS5S(Sj5rS)SjrS*Sjr\R"SSS/SS9S+Sj5rS,SjrS-SjrS.SjrS+SjrS+SjrS+SjrS/SjrS0SjrS0SjrS1S jrS1S!jrS2S"jrS2S#jrS$rU=r $)3�ConnectionEvents�,a10
Available events for11:class:`_engine.Connection` and :class:`_engine.Engine`.12 13The methods here define the name of an event as well as the names of14members that are passed to listener functions.15 16An event listener can be associated with any17:class:`_engine.Connection` or :class:`_engine.Engine`18class or instance, such as an :class:`_engine.Engine`, e.g.::19 20    from sqlalchemy import event, create_engine21 22 23    def before_cursor_execute(24        conn, cursor, statement, parameters, context, executemany25    ):26        log.info("Received statement: %s", statement)27 28 29    engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")30    event.listen(engine, "before_cursor_execute", before_cursor_execute)31 32or with a specific :class:`_engine.Connection`::33 34    with engine.begin() as conn:35 36        @event.listens_for(conn, "before_cursor_execute")37        def before_cursor_execute(38            conn, cursor, statement, parameters, context, executemany39        ):40            log.info("Received statement: %s", statement)41 42When the methods are called with a `statement` parameter, such as in43:meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`,44the statement is the exact SQL string that was prepared for transmission45to the DBAPI ``cursor`` in the connection's :class:`.Dialect`.46 47The :meth:`.before_execute` and :meth:`.before_cursor_execute`48events can also be established with the ``retval=True`` flag, which49allows modification of the statement and parameters to be sent50to the database.  The :meth:`.before_cursor_execute` event is51particularly useful here to add ad-hoc string transformations, such52as comments, to all executions::53 54    from sqlalchemy.engine import Engine55    from sqlalchemy import event56 57 58    @event.listens_for(Engine, "before_cursor_execute", retval=True)59    def comment_sql_calls(60        conn, cursor, statement, parameters, context, executemany61    ):62        statement = statement + " -- some comment"63        return statement, parameters64 65.. note:: :class:`_events.ConnectionEvents` can be established on any66   combination of :class:`_engine.Engine`, :class:`_engine.Connection`,67   as well68   as instances of each of those classes.  Events across all69   four scopes will fire off for a given instance of70   :class:`_engine.Connection`.  However, for performance reasons, the71   :class:`_engine.Connection` object determines at instantiation time72   whether or not its parent :class:`_engine.Engine` has event listeners73   established.   Event listeners added to the :class:`_engine.Engine`74   class or to an instance of :class:`_engine.Engine`75   *after* the instantiation76   of a dependent :class:`_engine.Connection` instance will usually77   *not* be available on that :class:`_engine.Connection` instance.78   The newly79   added listeners will instead take effect for80   :class:`_engine.Connection`81   instances created subsequent to those event listeners being82   established on the parent :class:`_engine.Engine` class or instance.83 84:param retval=False: Applies to the :meth:`.before_execute` and85  :meth:`.before_cursor_execute` events only.  When True, the86  user-defined event function must have a return value, which87  is a tuple of parameters that replace the given statement88  and parameters.  See those methods for a description of89  specific return arguments.90 91�92SomeEnginec�n>�[TU]X5nUc![US5(aUR5 U$)N�_no_async_engine_events)�super�_accept_with�hasattrr&)�cls�target�93identifier�default_dispatch�	__class__s    ��^D:\code\apps\devtools\python\user_packages\Python313\site-packages\sqlalchemy/engine/events.pyr(�ConnectionEvents._accept_with�sA���!�7�/��C���#���-�)94�)95�
�*�*�,���F��retvalc�0^	�URURURpenSUlU(d"US:XaUm	U	4SjnUnO4US:Xa96Um	U	4SjnUnO#U(aUS;a[R97"S5eUR
U5R5 g)NT�before_executec�$>�T"UUUUU5 XU4$�N�)�conn�
clauseelement�multiparams�params�execution_options�orig_fns     �r/�wrap_before_execute�5ConnectionEvents._listen.<locals>.wrap_before_execute�s)�����%�#��)��)�v�=�=r1�before_cursor_executec�$>�T"UUUUUU5 X#4$r7r8)r9�cursor�	statement�98parameters�context�executemanyr>s      �r/�wrap_before_cursor_execute�<ConnectionEvents._listen.<locals>.wrap_before_cursor_execute�s*������!�"��#�
�%�0�0r1)r5rAzOnly the 'before_execute', 'before_cursor_execute' and 'handle_error' engine event listeners accept the 'retval=True' argument.)�dispatch_targetr,�99_listen_fn�_has_eventsr�
ArgumentError�with_wrapper�base_listen)100r*�	event_keyr3�kwr+r,�fnr?rHr>s101         @r/�_listen�ConnectionEvents._listen�s����
�%�%�� � �� � ���102"�����-�-���103>�)���6�6���1�0���
�104�+105�106��#�#���
�	���r�"�.�.�0r1z1.4)r9r:r;r<c��UUUU4$r7r8)r9r:r;r<r=s     r/�<lambda>�ConnectionEvents.<lambda>�s������	M107r1r9c��g)a�Intercept high level execute() events, receiving uncompiled108SQL constructs and other objects prior to rendering into SQL.109 110This event is good for debugging SQL compilation issues as well111as early manipulation of the parameters being sent to the database,112as the parameter lists will be in a consistent format here.113 114This event can be optionally established with the ``retval=True``115flag.  The ``clauseelement``, ``multiparams``, and ``params``116arguments should be returned as a three-tuple in this case::117 118    @event.listens_for(Engine, "before_execute", retval=True)119    def before_execute(conn, clauseelement, multiparams, params):120        # do something with clauseelement, multiparams, params121        return clauseelement, multiparams, params122 123:param conn: :class:`_engine.Connection` object124:param clauseelement: SQL expression construct, :class:`.Compiled`125 instance, or string statement passed to126 :meth:`_engine.Connection.execute`.127:param multiparams: Multiple parameter sets, a list of dictionaries.128:param params: Single parameter set, a single dictionary.129:param execution_options: dictionary of execution130 options passed along with the statement, if any.  This is a merge131 of all options that will be used, including those of the statement,132 the connection, and those passed in to the method itself for133 the 2.0 style of execution.134 135 .. versionadded: 1.4136 137.. seealso::138 139    :meth:`.before_cursor_execute`140 141Nr8)�selfr9r:r;r<r=s      r/r5�ConnectionEvents.before_execute���r1)r9r:r;r<�resultc��UUUUU4$r7r8)r9r:r;r<r=r\s      r/rVrW	s�������U142r1c��g)a�Intercept high level execute() events after execute.143 144 145:param conn: :class:`_engine.Connection` object146:param clauseelement: SQL expression construct, :class:`.Compiled`147 instance, or string statement passed to148 :meth:`_engine.Connection.execute`.149:param multiparams: Multiple parameter sets, a list of dictionaries.150:param params: Single parameter set, a single dictionary.151:param execution_options: dictionary of execution152 options passed along with the statement, if any.  This is a merge153 of all options that will be used, including those of the statement,154 the connection, and those passed in to the method itself for155 the 2.0 style of execution.156 157 .. versionadded: 1.4158 159:param result: :class:`_engine.CursorResult` generated by the160 execution.161 162Nr8)rYr9r:r;r<r=r\s       r/�
after_execute�ConnectionEvents.after_executer[r1c��g)a�Intercept low-level cursor execute() events before execution,163receiving the string SQL statement and DBAPI-specific parameter list to164be invoked against a cursor.165 166This event is a good choice for logging as well as late modifications167to the SQL string.  It's less ideal for parameter modifications except168for those which are specific to a target backend.169 170This event can be optionally established with the ``retval=True``171flag.  The ``statement`` and ``parameters`` arguments should be172returned as a two-tuple in this case::173 174    @event.listens_for(Engine, "before_cursor_execute", retval=True)175    def before_cursor_execute(176        conn, cursor, statement, parameters, context, executemany177    ):178        # do something with statement, parameters179        return statement, parameters180 181See the example at :class:`_events.ConnectionEvents`.182 183:param conn: :class:`_engine.Connection` object184:param cursor: DBAPI cursor object185:param statement: string SQL statement, as to be passed to the DBAPI186:param parameters: Dictionary, tuple, or list of parameters being187 passed to the ``execute()`` or ``executemany()`` method of the188 DBAPI ``cursor``.  In some cases may be ``None``.189:param context: :class:`.ExecutionContext` object in use.  May190 be ``None``.191:param executemany: boolean, if ``True``, this is an ``executemany()``192 call, if ``False``, this is an ``execute()`` call.193 194.. seealso::195 196    :meth:`.before_execute`197 198    :meth:`.after_cursor_execute`199 200Nr8�rYr9rCrDrErFrGs       r/rA�&ConnectionEvents.before_cursor_execute0r[r1c��g)a�Intercept low-level cursor execute() events after execution.201 202:param conn: :class:`_engine.Connection` object203:param cursor: DBAPI cursor object.  Will have results pending204 if the statement was a SELECT, but these should not be consumed205 as they will be needed by the :class:`_engine.CursorResult`.206:param statement: string SQL statement, as passed to the DBAPI207:param parameters: Dictionary, tuple, or list of parameters being208 passed to the ``execute()`` or ``executemany()`` method of the209 DBAPI ``cursor``.  In some cases may be ``None``.210:param context: :class:`.ExecutionContext` object in use.  May211 be ``None``.212:param executemany: boolean, if ``True``, this is an ``executemany()``213 call, if ``False``, this is an ``execute()`` call.214 215Nr8rbs       r/�after_cursor_execute�%ConnectionEvents.after_cursor_executear[r1z2.0�branchc�216�US4$)NFr8)r9s r/rVrW|s��4��-r1)�	converterc��g)a�Intercept the creation of a new :class:`_engine.Connection`.217 218This event is called typically as the direct result of calling219the :meth:`_engine.Engine.connect` method.220 221It differs from the :meth:`_events.PoolEvents.connect` method, which222refers to the actual connection to a database at the DBAPI level;223a DBAPI connection may be pooled and reused for many operations.224In contrast, this event refers only to the production of a higher level225:class:`_engine.Connection` wrapper around such a DBAPI connection.226 227It also differs from the :meth:`_events.PoolEvents.checkout` event228in that it is specific to the :class:`_engine.Connection` object,229not the230DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with,231although232this DBAPI connection is available here via the233:attr:`_engine.Connection.connection` attribute.234But note there can in fact235be multiple :meth:`_events.PoolEvents.checkout`236events within the lifespan237of a single :class:`_engine.Connection` object, if that238:class:`_engine.Connection`239is invalidated and re-established.240 241:param conn: :class:`_engine.Connection` object.242 243.. seealso::244 245    :meth:`_events.PoolEvents.checkout`246    the lower-level pool checkout event247    for an individual DBAPI connection248 249Nr8�rYr9s  r/�engine_connect�ConnectionEvents.engine_connect{r[r1c��g)a8Intercept when the :meth:`_engine.Connection.execution_options`250method is called.251 252This method is called after the new :class:`_engine.Connection`253has been254produced, with the newly updated execution options collection, but255before the :class:`.Dialect` has acted upon any of those new options.256 257Note that this method is not called when a new258:class:`_engine.Connection`259is produced which is inheriting execution options from its parent260:class:`_engine.Engine`; to intercept this condition, use the261:meth:`_events.ConnectionEvents.engine_connect` event.262 263:param conn: The newly copied :class:`_engine.Connection` object264 265:param opts: dictionary of options that were passed to the266 :meth:`_engine.Connection.execution_options` method.267 This dictionary may be modified in place to affect the ultimate268 options which take effect.269 270 .. versionadded:: 2.0 the ``opts`` dictionary may be modified271    in place.272 273 274.. seealso::275 276    :meth:`_events.ConnectionEvents.set_engine_execution_options`277    - event278    which is called when :meth:`_engine.Engine.execution_options`279    is called.280 281 282Nr8)rYr9�optss   r/� set_connection_execution_options�1ConnectionEvents.set_connection_execution_options�r[r1c��g)aIntercept when the :meth:`_engine.Engine.execution_options`283method is called.284 285The :meth:`_engine.Engine.execution_options` method produces a shallow286copy of the :class:`_engine.Engine` which stores the new options.287That new288:class:`_engine.Engine` is passed here.289A particular application of this290method is to add a :meth:`_events.ConnectionEvents.engine_connect`291event292handler to the given :class:`_engine.Engine`293which will perform some per-294:class:`_engine.Connection` task specific to these execution options.295 296:param conn: The newly copied :class:`_engine.Engine` object297 298:param opts: dictionary of options that were passed to the299 :meth:`_engine.Connection.execution_options` method.300 This dictionary may be modified in place to affect the ultimate301 options which take effect.302 303 .. versionadded:: 2.0 the ``opts`` dictionary may be modified304    in place.305 306.. seealso::307 308    :meth:`_events.ConnectionEvents.set_connection_execution_options`309    - event310    which is called when :meth:`_engine.Connection.execution_options`311    is312    called.313 314Nr8)rY�engineros   r/�set_engine_execution_options�-ConnectionEvents.set_engine_execution_options�r[r1c��g)a�Intercept when the :meth:`_engine.Engine.dispose` method is called.315 316The :meth:`_engine.Engine.dispose` method instructs the engine to317"dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and318replaces it with a new one.  Disposing of the old pool has the319effect that existing checked-in connections are closed.  The new320pool does not establish any new connections until it is first used.321 322This event can be used to indicate that resources related to the323:class:`_engine.Engine` should also be cleaned up,324keeping in mind that the325:class:`_engine.Engine`326can still be used for new requests in which case327it re-acquires connection resources.328 329Nr8)rYrss  r/�engine_disposed� ConnectionEvents.engine_disposed�r[r1c��g)zLIntercept begin() events.330 331:param conn: :class:`_engine.Connection` object332 333Nr8rks  r/�begin�ConnectionEvents.begin�r[r1c��g)a�Intercept rollback() events, as initiated by a334:class:`.Transaction`.335 336Note that the :class:`_pool.Pool` also "auto-rolls back"337a DBAPI connection upon checkin, if the ``reset_on_return``338flag is set to its default value of ``'rollback'``.339To intercept this340rollback, use the :meth:`_events.PoolEvents.reset` hook.341 342:param conn: :class:`_engine.Connection` object343 344.. seealso::345 346    :meth:`_events.PoolEvents.reset`347 348Nr8rks  r/�rollback�ConnectionEvents.rollbackr[r1c��g)a\Intercept commit() events, as initiated by a349:class:`.Transaction`.350 351Note that the :class:`_pool.Pool` may also "auto-commit"352a DBAPI connection upon checkin, if the ``reset_on_return``353flag is set to the value ``'commit'``.  To intercept this354commit, use the :meth:`_events.PoolEvents.reset` hook.355 356:param conn: :class:`_engine.Connection` object357Nr8rks  r/�commit�ConnectionEvents.commitr[r1c��g)z�Intercept savepoint() events.358 359:param conn: :class:`_engine.Connection` object360:param name: specified name used for the savepoint.361 362Nr8)rYr9�names   r/�	savepoint�ConnectionEvents.savepoint$r[r1c��g)z�Intercept rollback_savepoint() events.363 364:param conn: :class:`_engine.Connection` object365:param name: specified name used for the savepoint.366:param context: not used367 368Nr8�rYr9r�rFs    r/�rollback_savepoint�#ConnectionEvents.rollback_savepoint,r[r1c��g)z�Intercept release_savepoint() events.369 370:param conn: :class:`_engine.Connection` object371:param name: specified name used for the savepoint.372:param context: not used373 374Nr8r�s    r/�release_savepoint�"ConnectionEvents.release_savepoint8r[r1c��g)zzIntercept begin_twophase() events.375 376:param conn: :class:`_engine.Connection` object377:param xid: two-phase XID identifier378 379Nr8�rYr9�xids   r/�begin_twophase�ConnectionEvents.begin_twophaseDr[r1c��g)z{Intercept prepare_twophase() events.380 381:param conn: :class:`_engine.Connection` object382:param xid: two-phase XID identifier383Nr8r�s   r/�prepare_twophase�!ConnectionEvents.prepare_twophaseLr[r1c��g)z�Intercept rollback_twophase() events.384 385:param conn: :class:`_engine.Connection` object386:param xid: two-phase XID identifier387:param is_prepared: boolean, indicates if388 :meth:`.TwoPhaseTransaction.prepare` was called.389 390Nr8�rYr9r��is_prepareds    r/�rollback_twophase�"ConnectionEvents.rollback_twophaseSr[r1c��g)z�Intercept commit_twophase() events.391 392:param conn: :class:`_engine.Connection` object393:param xid: two-phase XID identifier394:param is_prepared: boolean, indicates if395 :meth:`.TwoPhaseTransaction.prepare` was called.396 397Nr8r�s    r/�commit_twophase� ConnectionEvents.commit_twophase_r[r1r8)r+z;Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]r,�str�returnzEOptional[Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]])rPz'event._EventKey[ConnectionEventsTarget]r3�boolrQrr��None)r9rr:rr;rr<rr=rr�zNOptional[Tuple[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams]])r9rr:rr;rr<rr=rr\zResult[Any]r�r�)r9rrCrrDr�rErrF�Optional[ExecutionContext]rGr�r�z,Optional[Tuple[str, _DBAPIAnyExecuteParams]])r9rrCrrDr�rErrFr�rGr�r�r�)r9rr�r�)r9rro�Dict[str, Any]r�r�)rsrror�r�r�)rsrr�r�)r9rr�r�r�r�)r9rr�r�rFr�r�r�)r9rr�rr�r�)r9rr�rr�r�r�r�)!�__name__�398__module__�__qualname__�__firstlineno__�__doc__�_target_class_docr
�_dispatch_target�classmethodr(rSr�_legacy_signaturer5r_rArerlrprtrwrzr}r�r�r�r�r�r�r�r��__static_attributes__�
__classcell__)r.s@r/r"r",s���Q�f%��-��� �K� �� �399O�	 �� ��400�	:1�:�:1��	:1�401�:1�402�
:1��:1�x���
�:�	403�	�,��,�"�,�-�	,�404)�,�+�
,�405�,�	�,�\���
�D�	406�407����"��-�	�408)��+�
���409��410��>/��/��/��	/�411+�/�,�
/��/�4126�/�b������	�413+��,�
���414��4���
���!�-G��"��"�H$��$�&4�$�	
�$�L#��#�$2�#�	
�#�J�$��$415��	��	�&)�	�48�	�	
�	�	��	�&)�	�48�	�	
�	���416��417�%(�418�7;�419�	
�420�421��422�%(�423�7;�424�	
�425�426r1r"c��\rSrSrSrSr\r\SS.SSjj5r	\SSj5r427SSjrSS	jrSS428jr
SSjrSSjrSS
jrSrg)�
DialectEventsilaevent interface for execution-replacement functions.429 430These events allow direct instrumentation and replacement431of key dialect functions which interact with the DBAPI.432 433.. note::434 435    :class:`.DialectEvents` hooks should be considered **semi-public**436    and experimental.437    These hooks are not for general use and are only for those situations438    where intricate re-statement of DBAPI mechanics must be injected onto439    an existing dialect.  For general-use statement-interception events,440    please use the :class:`_events.ConnectionEvents` interface.441 442.. seealso::443 444    :meth:`_events.ConnectionEvents.before_cursor_execute`445 446    :meth:`_events.ConnectionEvents.before_execute`447 448    :meth:`_events.ConnectionEvents.after_cursor_execute`449 450    :meth:`_events.ConnectionEvents.after_execute`451 452r$Fr2c�J�URnSUlUR5 g)NT)rJrLrO)r*rPr3rQr+s     r/rS�DialectEvents._listen�s#���*�*��!������r1c��[U[5(a3[U[5(a[$[U[5(aU$g[U[5(aUR453$[U[5(aU$[U[5(aUS:Xa[R"S5e[US5(aUR5 gg)N�handle_errorz�The handle_error() event hook as of SQLAlchemy 2.0 is established on the Dialect, and may only be applied to the Engine as a whole or to a specific Dialect as a whole, not on a per-Connection basis.r&)�454isinstance�type�455issubclassrr�dialectrr�InvalidRequestErrorr)r&)r*r+r,s   r/r(�DialectEvents._accept_with�s����f�d�#�#��&�&�)�)����F�G�,�,��
�-�
���
'�
'��>�>�!�
���
(�
(��M�
��456�
+�
+�457�n�0L��)�)�1��
��V�6�
7�
7��*�*�,�r1c��g)aIntercept all exceptions processed by the458:class:`_engine.Dialect`, typically but not limited to those459emitted within the scope of a :class:`_engine.Connection`.460 461.. versionchanged:: 2.0 the :meth:`.DialectEvents.handle_error` event462   is moved to the :class:`.DialectEvents` class, moved from the463   :class:`.ConnectionEvents` class, so that it may also participate in464   the "pre ping" operation configured with the465   :paramref:`_sa.create_engine.pool_pre_ping` parameter. The event466   remains registered by using the :class:`_engine.Engine` as the event467   target, however note that using the :class:`_engine.Connection` as468   an event target for :meth:`.DialectEvents.handle_error` is no longer469   supported.470 471This includes all exceptions emitted by the DBAPI as well as472within SQLAlchemy's statement invocation process, including473encoding errors and other statement validation errors.  Other areas474in which the event is invoked include transaction begin and end,475result row fetching, cursor creation.476 477Note that :meth:`.handle_error` may support new kinds of exceptions478and new calling scenarios at *any time*.  Code which uses this479event must expect new calling patterns to be present in minor480releases.481 482To support the wide variety of members that correspond to an exception,483as well as to allow extensibility of the event without backwards484incompatibility, the sole argument received is an instance of485:class:`.ExceptionContext`.   This object contains data members486representing detail about the exception.487 488Use cases supported by this hook include:489 490* read-only, low-level exception handling for logging and491  debugging purposes492* Establishing whether a DBAPI connection error message indicates493  that the database connection needs to be reconnected, including494  for the "pre_ping" handler used by **some** dialects495* Establishing or disabling whether a connection or the owning496  connection pool is invalidated or expired in response to a497  specific exception498* exception re-writing499 500The hook is called while the cursor from the failed operation501(if any) is still open and accessible.   Special cleanup operations502can be called on this cursor; SQLAlchemy will attempt to close503this cursor subsequent to this hook being invoked.504 505As of SQLAlchemy 2.0, the "pre_ping" handler enabled using the506:paramref:`_sa.create_engine.pool_pre_ping` parameter will also507participate in the :meth:`.handle_error` process, **for those dialects508that rely upon disconnect codes to detect database liveness**. Note509that some dialects such as psycopg, psycopg2, and most MySQL dialects510make use of a native ``ping()`` method supplied by the DBAPI which does511not make use of disconnect codes.512 513.. versionchanged:: 2.0.0 The :meth:`.DialectEvents.handle_error`514   event hook participates in connection pool "pre-ping" operations.515   Within this usage, the :attr:`.ExceptionContext.engine` attribute516   will be ``None``, however the :class:`.Dialect` in use is always517   available via the :attr:`.ExceptionContext.dialect` attribute.518 519.. versionchanged:: 2.0.5 Added :attr:`.ExceptionContext.is_pre_ping`520   attribute which will be set to ``True`` when the521   :meth:`.DialectEvents.handle_error` event hook is triggered within522   a connection pool pre-ping operation.523 524.. versionchanged:: 2.0.5 An issue was repaired that allows for the525   PostgreSQL ``psycopg`` and ``psycopg2`` drivers, as well as all526   MySQL drivers, to properly participate in the527   :meth:`.DialectEvents.handle_error` event hook during528   connection pool "pre-ping" operations; previously, the529   implementation was non-working for these drivers.530 531 532A handler function has two options for replacing533the SQLAlchemy-constructed exception into one that is user534defined.   It can either raise this new exception directly, in535which case all further event listeners are bypassed and the536exception will be raised, after appropriate cleanup as taken537place::538 539    @event.listens_for(Engine, "handle_error")540    def handle_exception(context):541        if isinstance(542            context.original_exception, psycopg2.OperationalError543        ) and "failed" in str(context.original_exception):544            raise MySpecialException("failed operation")545 546.. warning::  Because the547   :meth:`_events.DialectEvents.handle_error`548   event specifically provides for exceptions to be re-thrown as549   the ultimate exception raised by the failed statement,550   **stack traces will be misleading** if the user-defined event551   handler itself fails and throws an unexpected exception;552   the stack trace may not illustrate the actual code line that553   failed!  It is advised to code carefully here and use554   logging and/or inline debugging if unexpected exceptions are555   occurring.556 557Alternatively, a "chained" style of event handling can be558used, by configuring the handler with the ``retval=True``559modifier and returning the new exception instance from the560function.  In this case, event handling will continue onto the561next handler.   The "chained" exception is available using562:attr:`.ExceptionContext.chained_exception`::563 564    @event.listens_for(Engine, "handle_error", retval=True)565    def handle_exception(context):566        if (567            context.chained_exception is not None568            and "special" in context.chained_exception.message569        ):570            return MySpecialException(571                "failed", cause=context.chained_exception572            )573 574Handlers that return ``None`` may be used within the chain; when575a handler returns ``None``, the previous exception instance,576if any, is maintained as the current exception that is passed onto the577next handler.578 579When a custom exception is raised or returned, SQLAlchemy raises580this new exception as-is, it is not wrapped by any SQLAlchemy581object.  If the exception is not a subclass of582:class:`sqlalchemy.exc.StatementError`,583certain features may not be available; currently this includes584the ORM's feature of adding a detail hint about "autoflush" to585exceptions raised within the autoflush process.586 587:param context: an :class:`.ExceptionContext` object.  See this588 class for details on all available members.589 590 591.. seealso::592 593    :ref:`pool_new_disconnect_codes`594 595Nr8)rY�exception_contexts  r/r��DialectEvents.handle_error�r[r1c��g)a�Receive connection arguments before a connection is made.596 597This event is useful in that it allows the handler to manipulate the598cargs and/or cparams collections that control how the DBAPI599``connect()`` function will be called. ``cargs`` will always be a600Python list that can be mutated in-place, and ``cparams`` a Python601dictionary that may also be mutated::602 603    e = create_engine("postgresql+psycopg2://user@host/dbname")604 605 606    @event.listens_for(e, "do_connect")607    def receive_do_connect(dialect, conn_rec, cargs, cparams):608        cparams["password"] = "some_password"609 610The event hook may also be used to override the call to ``connect()``611entirely, by returning a non-``None`` DBAPI connection object::612 613    e = create_engine("postgresql+psycopg2://user@host/dbname")614 615 616    @event.listens_for(e, "do_connect")617    def receive_do_connect(dialect, conn_rec, cargs, cparams):618        return psycopg2.connect(*cargs, **cparams)619 620.. seealso::621 622    :ref:`custom_dbapi_args`623 624Nr8)rYr��conn_rec�cargs�cparamss     r/�625do_connect�DialectEvents.do_connectAr[r1c��g)z�Receive a cursor to have executemany() called.626 627Return the value True to halt further events from invoking,628and to indicate that the cursor execution has already taken629place within the event handler.630 631Nr8�rYrCrDrErFs     r/�do_executemany�DialectEvents.do_executemanygr[r1c��g)z�Receive a cursor to have execute() with no parameters called.632 633Return the value True to halt further events from invoking,634and to indicate that the cursor execution has already taken635place within the event handler.636 637Nr8)rYrCrDrFs    r/�do_execute_no_params�"DialectEvents.do_execute_no_paramsvr[r1c��g)z�Receive a cursor to have execute() called.638 639Return the value True to halt further events from invoking,640and to indicate that the cursor execution has already taken641place within the event handler.642 643Nr8r�s     r/�644do_execute�DialectEvents.do_execute�r[r1c��g)a�Receive the setinputsizes dictionary for possible modification.645 646This event is emitted in the case where the dialect makes use of the647DBAPI ``cursor.setinputsizes()`` method which passes information about648parameter binding for a particular statement.   The given649``inputsizes`` dictionary will contain :class:`.BindParameter` objects650as keys, linked to DBAPI-specific type objects as values; for651parameters that are not bound, they are added to the dictionary with652``None`` as the value, which means the parameter will not be included653in the ultimate setinputsizes call.   The event may be used to inspect654and/or log the datatypes that are being bound, as well as to modify the655dictionary in place.  Parameters can be added, modified, or removed656from this dictionary.   Callers will typically want to inspect the657:attr:`.BindParameter.type` attribute of the given bind objects in658order to make decisions about the DBAPI object.659 660After the event, the ``inputsizes`` dictionary is converted into661an appropriate datastructure to be passed to ``cursor.setinputsizes``;662either a list for a positional bound parameter execution style,663or a dictionary of string parameter keys to DBAPI type objects for664a named bound parameter execution style.665 666The setinputsizes hook overall is only used for dialects which include667the flag ``use_setinputsizes=True``.  Dialects which use this668include python-oracledb, cx_Oracle, pg8000, asyncpg, and pyodbc669dialects.670 671.. note::672 673    For use with pyodbc, the ``use_setinputsizes`` flag674    must be passed to the dialect, e.g.::675 676        create_engine("mssql+pyodbc://...", use_setinputsizes=True)677 678    .. seealso::679 680          :ref:`mssql_pyodbc_setinputsizes`681 682.. versionadded:: 1.2.9683 684.. seealso::685 686    :ref:`cx_oracle_setinputsizes`687 688Nr8)rY�689inputsizesrCrDrErFs      r/�do_setinputsizes�DialectEvents.do_setinputsizes�s��j	
r1r8N)rPzevent._EventKey[Dialect]r3r�rQrr�r�)r+z3Union[Engine, Type[Engine], Dialect, Type[Dialect]]r,r�r�z'Optional[Union[Dialect, Type[Dialect]]])r�rr�zOptional[BaseException])690r�rr�rr�zTuple[Any, ...]r�r�r�zOptional[DBAPIConnection])691rCrrDr�rErrFrr��Optional[Literal[True]])rCrrDr�rFrr�r�)692rCrrDr�rErrFrr�r�)r�zDict[BindParameter[Any], Any]rCrrDr�rErrFrr�r�)r�r�r�r�r�r�rr�r�rSr(r�r�r�r�r�r�r�r8r1r/r�r�ls����4%�����693�	694 �+�695 ��	696 �697�698 �699�
700 ��701 ���C����7021�	���4M�!1�M�	 �M�^$��$�&�$��	$�703 �$�704#�
$�L
��
��
�-�	
�705"�
�706!�

�	�!�	�.1�	�<L�	�	 �	�
��
��
�.�	
�707"�
�708!�

�5
�1�5
��5
��	5
�709+�5
�"�
5
�710�5
r1r�)*�711__future__r�typingrrrrrr	�baserr�712interfacesr
rrr�rr�util.typingr�
TYPE_CHECKINGrrrrrrrrr\r�poolr�sqlr�sql.elementsr �Eventsr"r�r8r1r/�<module>r�s���#�
���������.�'�#����!�	���3�4�2�4�5�+�,�,��*� �,�}�u�|�|�$:�;�}�@Y
�E�L�L��)�Y
r1
codekingpro/portable-devtools · Team Ai