events.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. # engine/events.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. from __future__ import annotations
  8. import typing
  9. from typing import Any
  10. from typing import Dict
  11. from typing import Optional
  12. from typing import Tuple
  13. from typing import Type
  14. from typing import Union
  15. from .base import Connection
  16. from .base import Engine
  17. from .interfaces import ConnectionEventsTarget
  18. from .interfaces import DBAPIConnection
  19. from .interfaces import DBAPICursor
  20. from .interfaces import Dialect
  21. from .. import event
  22. from .. import exc
  23. from ..util.typing import Literal
  24. if typing.TYPE_CHECKING:
  25. from .interfaces import _CoreMultiExecuteParams
  26. from .interfaces import _CoreSingleExecuteParams
  27. from .interfaces import _DBAPIAnyExecuteParams
  28. from .interfaces import _DBAPIMultiExecuteParams
  29. from .interfaces import _DBAPISingleExecuteParams
  30. from .interfaces import _ExecuteOptions
  31. from .interfaces import ExceptionContext
  32. from .interfaces import ExecutionContext
  33. from .result import Result
  34. from ..pool import ConnectionPoolEntry
  35. from ..sql import Executable
  36. from ..sql.elements import BindParameter
  37. class ConnectionEvents(event.Events[ConnectionEventsTarget]):
  38. """Available events for
  39. :class:`_engine.Connection` and :class:`_engine.Engine`.
  40. The methods here define the name of an event as well as the names of
  41. members that are passed to listener functions.
  42. An event listener can be associated with any
  43. :class:`_engine.Connection` or :class:`_engine.Engine`
  44. class or instance, such as an :class:`_engine.Engine`, e.g.::
  45. from sqlalchemy import event, create_engine
  46. def before_cursor_execute(
  47. conn, cursor, statement, parameters, context, executemany
  48. ):
  49. log.info("Received statement: %s", statement)
  50. engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
  51. event.listen(engine, "before_cursor_execute", before_cursor_execute)
  52. or with a specific :class:`_engine.Connection`::
  53. with engine.begin() as conn:
  54. @event.listens_for(conn, "before_cursor_execute")
  55. def before_cursor_execute(
  56. conn, cursor, statement, parameters, context, executemany
  57. ):
  58. log.info("Received statement: %s", statement)
  59. When the methods are called with a `statement` parameter, such as in
  60. :meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`,
  61. the statement is the exact SQL string that was prepared for transmission
  62. to the DBAPI ``cursor`` in the connection's :class:`.Dialect`.
  63. The :meth:`.before_execute` and :meth:`.before_cursor_execute`
  64. events can also be established with the ``retval=True`` flag, which
  65. allows modification of the statement and parameters to be sent
  66. to the database. The :meth:`.before_cursor_execute` event is
  67. particularly useful here to add ad-hoc string transformations, such
  68. as comments, to all executions::
  69. from sqlalchemy.engine import Engine
  70. from sqlalchemy import event
  71. @event.listens_for(Engine, "before_cursor_execute", retval=True)
  72. def comment_sql_calls(
  73. conn, cursor, statement, parameters, context, executemany
  74. ):
  75. statement = statement + " -- some comment"
  76. return statement, parameters
  77. .. note:: :class:`_events.ConnectionEvents` can be established on any
  78. combination of :class:`_engine.Engine`, :class:`_engine.Connection`,
  79. as well
  80. as instances of each of those classes. Events across all
  81. four scopes will fire off for a given instance of
  82. :class:`_engine.Connection`. However, for performance reasons, the
  83. :class:`_engine.Connection` object determines at instantiation time
  84. whether or not its parent :class:`_engine.Engine` has event listeners
  85. established. Event listeners added to the :class:`_engine.Engine`
  86. class or to an instance of :class:`_engine.Engine`
  87. *after* the instantiation
  88. of a dependent :class:`_engine.Connection` instance will usually
  89. *not* be available on that :class:`_engine.Connection` instance.
  90. The newly
  91. added listeners will instead take effect for
  92. :class:`_engine.Connection`
  93. instances created subsequent to those event listeners being
  94. established on the parent :class:`_engine.Engine` class or instance.
  95. :param retval=False: Applies to the :meth:`.before_execute` and
  96. :meth:`.before_cursor_execute` events only. When True, the
  97. user-defined event function must have a return value, which
  98. is a tuple of parameters that replace the given statement
  99. and parameters. See those methods for a description of
  100. specific return arguments.
  101. """ # noqa
  102. _target_class_doc = "SomeEngine"
  103. _dispatch_target = ConnectionEventsTarget
  104. @classmethod
  105. def _accept_with(
  106. cls,
  107. target: Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]],
  108. identifier: str,
  109. ) -> Optional[Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]]:
  110. default_dispatch = super()._accept_with(target, identifier)
  111. if default_dispatch is None and hasattr(
  112. target, "_no_async_engine_events"
  113. ):
  114. target._no_async_engine_events()
  115. return default_dispatch
  116. @classmethod
  117. def _listen(
  118. cls,
  119. event_key: event._EventKey[ConnectionEventsTarget],
  120. *,
  121. retval: bool = False,
  122. **kw: Any,
  123. ) -> None:
  124. target, identifier, fn = (
  125. event_key.dispatch_target,
  126. event_key.identifier,
  127. event_key._listen_fn,
  128. )
  129. target._has_events = True
  130. if not retval:
  131. if identifier == "before_execute":
  132. orig_fn = fn
  133. def wrap_before_execute( # type: ignore
  134. conn, clauseelement, multiparams, params, execution_options
  135. ):
  136. orig_fn(
  137. conn,
  138. clauseelement,
  139. multiparams,
  140. params,
  141. execution_options,
  142. )
  143. return clauseelement, multiparams, params
  144. fn = wrap_before_execute
  145. elif identifier == "before_cursor_execute":
  146. orig_fn = fn
  147. def wrap_before_cursor_execute( # type: ignore
  148. conn, cursor, statement, parameters, context, executemany
  149. ):
  150. orig_fn(
  151. conn,
  152. cursor,
  153. statement,
  154. parameters,
  155. context,
  156. executemany,
  157. )
  158. return statement, parameters
  159. fn = wrap_before_cursor_execute
  160. elif retval and identifier not in (
  161. "before_execute",
  162. "before_cursor_execute",
  163. ):
  164. raise exc.ArgumentError(
  165. "Only the 'before_execute', "
  166. "'before_cursor_execute' and 'handle_error' engine "
  167. "event listeners accept the 'retval=True' "
  168. "argument."
  169. )
  170. event_key.with_wrapper(fn).base_listen()
  171. @event._legacy_signature(
  172. "1.4",
  173. ["conn", "clauseelement", "multiparams", "params"],
  174. lambda conn, clauseelement, multiparams, params, execution_options: (
  175. conn,
  176. clauseelement,
  177. multiparams,
  178. params,
  179. ),
  180. )
  181. def before_execute(
  182. self,
  183. conn: Connection,
  184. clauseelement: Executable,
  185. multiparams: _CoreMultiExecuteParams,
  186. params: _CoreSingleExecuteParams,
  187. execution_options: _ExecuteOptions,
  188. ) -> Optional[
  189. Tuple[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams]
  190. ]:
  191. """Intercept high level execute() events, receiving uncompiled
  192. SQL constructs and other objects prior to rendering into SQL.
  193. This event is good for debugging SQL compilation issues as well
  194. as early manipulation of the parameters being sent to the database,
  195. as the parameter lists will be in a consistent format here.
  196. This event can be optionally established with the ``retval=True``
  197. flag. The ``clauseelement``, ``multiparams``, and ``params``
  198. arguments should be returned as a three-tuple in this case::
  199. @event.listens_for(Engine, "before_execute", retval=True)
  200. def before_execute(conn, clauseelement, multiparams, params):
  201. # do something with clauseelement, multiparams, params
  202. return clauseelement, multiparams, params
  203. :param conn: :class:`_engine.Connection` object
  204. :param clauseelement: SQL expression construct, :class:`.Compiled`
  205. instance, or string statement passed to
  206. :meth:`_engine.Connection.execute`.
  207. :param multiparams: Multiple parameter sets, a list of dictionaries.
  208. :param params: Single parameter set, a single dictionary.
  209. :param execution_options: dictionary of execution
  210. options passed along with the statement, if any. This is a merge
  211. of all options that will be used, including those of the statement,
  212. the connection, and those passed in to the method itself for
  213. the 2.0 style of execution.
  214. .. versionadded: 1.4
  215. .. seealso::
  216. :meth:`.before_cursor_execute`
  217. """
  218. @event._legacy_signature(
  219. "1.4",
  220. ["conn", "clauseelement", "multiparams", "params", "result"],
  221. lambda conn, clauseelement, multiparams, params, execution_options, result: ( # noqa
  222. conn,
  223. clauseelement,
  224. multiparams,
  225. params,
  226. result,
  227. ),
  228. )
  229. def after_execute(
  230. self,
  231. conn: Connection,
  232. clauseelement: Executable,
  233. multiparams: _CoreMultiExecuteParams,
  234. params: _CoreSingleExecuteParams,
  235. execution_options: _ExecuteOptions,
  236. result: Result[Any],
  237. ) -> None:
  238. """Intercept high level execute() events after execute.
  239. :param conn: :class:`_engine.Connection` object
  240. :param clauseelement: SQL expression construct, :class:`.Compiled`
  241. instance, or string statement passed to
  242. :meth:`_engine.Connection.execute`.
  243. :param multiparams: Multiple parameter sets, a list of dictionaries.
  244. :param params: Single parameter set, a single dictionary.
  245. :param execution_options: dictionary of execution
  246. options passed along with the statement, if any. This is a merge
  247. of all options that will be used, including those of the statement,
  248. the connection, and those passed in to the method itself for
  249. the 2.0 style of execution.
  250. .. versionadded: 1.4
  251. :param result: :class:`_engine.CursorResult` generated by the
  252. execution.
  253. """
  254. def before_cursor_execute(
  255. self,
  256. conn: Connection,
  257. cursor: DBAPICursor,
  258. statement: str,
  259. parameters: _DBAPIAnyExecuteParams,
  260. context: Optional[ExecutionContext],
  261. executemany: bool,
  262. ) -> Optional[Tuple[str, _DBAPIAnyExecuteParams]]:
  263. """Intercept low-level cursor execute() events before execution,
  264. receiving the string SQL statement and DBAPI-specific parameter list to
  265. be invoked against a cursor.
  266. This event is a good choice for logging as well as late modifications
  267. to the SQL string. It's less ideal for parameter modifications except
  268. for those which are specific to a target backend.
  269. This event can be optionally established with the ``retval=True``
  270. flag. The ``statement`` and ``parameters`` arguments should be
  271. returned as a two-tuple in this case::
  272. @event.listens_for(Engine, "before_cursor_execute", retval=True)
  273. def before_cursor_execute(
  274. conn, cursor, statement, parameters, context, executemany
  275. ):
  276. # do something with statement, parameters
  277. return statement, parameters
  278. See the example at :class:`_events.ConnectionEvents`.
  279. :param conn: :class:`_engine.Connection` object
  280. :param cursor: DBAPI cursor object
  281. :param statement: string SQL statement, as to be passed to the DBAPI
  282. :param parameters: Dictionary, tuple, or list of parameters being
  283. passed to the ``execute()`` or ``executemany()`` method of the
  284. DBAPI ``cursor``. In some cases may be ``None``.
  285. :param context: :class:`.ExecutionContext` object in use. May
  286. be ``None``.
  287. :param executemany: boolean, if ``True``, this is an ``executemany()``
  288. call, if ``False``, this is an ``execute()`` call.
  289. .. seealso::
  290. :meth:`.before_execute`
  291. :meth:`.after_cursor_execute`
  292. """
  293. def after_cursor_execute(
  294. self,
  295. conn: Connection,
  296. cursor: DBAPICursor,
  297. statement: str,
  298. parameters: _DBAPIAnyExecuteParams,
  299. context: Optional[ExecutionContext],
  300. executemany: bool,
  301. ) -> None:
  302. """Intercept low-level cursor execute() events after execution.
  303. :param conn: :class:`_engine.Connection` object
  304. :param cursor: DBAPI cursor object. Will have results pending
  305. if the statement was a SELECT, but these should not be consumed
  306. as they will be needed by the :class:`_engine.CursorResult`.
  307. :param statement: string SQL statement, as passed to the DBAPI
  308. :param parameters: Dictionary, tuple, or list of parameters being
  309. passed to the ``execute()`` or ``executemany()`` method of the
  310. DBAPI ``cursor``. In some cases may be ``None``.
  311. :param context: :class:`.ExecutionContext` object in use. May
  312. be ``None``.
  313. :param executemany: boolean, if ``True``, this is an ``executemany()``
  314. call, if ``False``, this is an ``execute()`` call.
  315. """
  316. @event._legacy_signature(
  317. "2.0", ["conn", "branch"], converter=lambda conn: (conn, False)
  318. )
  319. def engine_connect(self, conn: Connection) -> None:
  320. """Intercept the creation of a new :class:`_engine.Connection`.
  321. This event is called typically as the direct result of calling
  322. the :meth:`_engine.Engine.connect` method.
  323. It differs from the :meth:`_events.PoolEvents.connect` method, which
  324. refers to the actual connection to a database at the DBAPI level;
  325. a DBAPI connection may be pooled and reused for many operations.
  326. In contrast, this event refers only to the production of a higher level
  327. :class:`_engine.Connection` wrapper around such a DBAPI connection.
  328. It also differs from the :meth:`_events.PoolEvents.checkout` event
  329. in that it is specific to the :class:`_engine.Connection` object,
  330. not the
  331. DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with,
  332. although
  333. this DBAPI connection is available here via the
  334. :attr:`_engine.Connection.connection` attribute.
  335. But note there can in fact
  336. be multiple :meth:`_events.PoolEvents.checkout`
  337. events within the lifespan
  338. of a single :class:`_engine.Connection` object, if that
  339. :class:`_engine.Connection`
  340. is invalidated and re-established.
  341. :param conn: :class:`_engine.Connection` object.
  342. .. seealso::
  343. :meth:`_events.PoolEvents.checkout`
  344. the lower-level pool checkout event
  345. for an individual DBAPI connection
  346. """
  347. def set_connection_execution_options(
  348. self, conn: Connection, opts: Dict[str, Any]
  349. ) -> None:
  350. """Intercept when the :meth:`_engine.Connection.execution_options`
  351. method is called.
  352. This method is called after the new :class:`_engine.Connection`
  353. has been
  354. produced, with the newly updated execution options collection, but
  355. before the :class:`.Dialect` has acted upon any of those new options.
  356. Note that this method is not called when a new
  357. :class:`_engine.Connection`
  358. is produced which is inheriting execution options from its parent
  359. :class:`_engine.Engine`; to intercept this condition, use the
  360. :meth:`_events.ConnectionEvents.engine_connect` event.
  361. :param conn: The newly copied :class:`_engine.Connection` object
  362. :param opts: dictionary of options that were passed to the
  363. :meth:`_engine.Connection.execution_options` method.
  364. This dictionary may be modified in place to affect the ultimate
  365. options which take effect.
  366. .. versionadded:: 2.0 the ``opts`` dictionary may be modified
  367. in place.
  368. .. seealso::
  369. :meth:`_events.ConnectionEvents.set_engine_execution_options`
  370. - event
  371. which is called when :meth:`_engine.Engine.execution_options`
  372. is called.
  373. """
  374. def set_engine_execution_options(
  375. self, engine: Engine, opts: Dict[str, Any]
  376. ) -> None:
  377. """Intercept when the :meth:`_engine.Engine.execution_options`
  378. method is called.
  379. The :meth:`_engine.Engine.execution_options` method produces a shallow
  380. copy of the :class:`_engine.Engine` which stores the new options.
  381. That new
  382. :class:`_engine.Engine` is passed here.
  383. A particular application of this
  384. method is to add a :meth:`_events.ConnectionEvents.engine_connect`
  385. event
  386. handler to the given :class:`_engine.Engine`
  387. which will perform some per-
  388. :class:`_engine.Connection` task specific to these execution options.
  389. :param conn: The newly copied :class:`_engine.Engine` object
  390. :param opts: dictionary of options that were passed to the
  391. :meth:`_engine.Connection.execution_options` method.
  392. This dictionary may be modified in place to affect the ultimate
  393. options which take effect.
  394. .. versionadded:: 2.0 the ``opts`` dictionary may be modified
  395. in place.
  396. .. seealso::
  397. :meth:`_events.ConnectionEvents.set_connection_execution_options`
  398. - event
  399. which is called when :meth:`_engine.Connection.execution_options`
  400. is
  401. called.
  402. """
  403. def engine_disposed(self, engine: Engine) -> None:
  404. """Intercept when the :meth:`_engine.Engine.dispose` method is called.
  405. The :meth:`_engine.Engine.dispose` method instructs the engine to
  406. "dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and
  407. replaces it with a new one. Disposing of the old pool has the
  408. effect that existing checked-in connections are closed. The new
  409. pool does not establish any new connections until it is first used.
  410. This event can be used to indicate that resources related to the
  411. :class:`_engine.Engine` should also be cleaned up,
  412. keeping in mind that the
  413. :class:`_engine.Engine`
  414. can still be used for new requests in which case
  415. it re-acquires connection resources.
  416. """
  417. def begin(self, conn: Connection) -> None:
  418. """Intercept begin() events.
  419. :param conn: :class:`_engine.Connection` object
  420. """
  421. def rollback(self, conn: Connection) -> None:
  422. """Intercept rollback() events, as initiated by a
  423. :class:`.Transaction`.
  424. Note that the :class:`_pool.Pool` also "auto-rolls back"
  425. a DBAPI connection upon checkin, if the ``reset_on_return``
  426. flag is set to its default value of ``'rollback'``.
  427. To intercept this
  428. rollback, use the :meth:`_events.PoolEvents.reset` hook.
  429. :param conn: :class:`_engine.Connection` object
  430. .. seealso::
  431. :meth:`_events.PoolEvents.reset`
  432. """
  433. def commit(self, conn: Connection) -> None:
  434. """Intercept commit() events, as initiated by a
  435. :class:`.Transaction`.
  436. Note that the :class:`_pool.Pool` may also "auto-commit"
  437. a DBAPI connection upon checkin, if the ``reset_on_return``
  438. flag is set to the value ``'commit'``. To intercept this
  439. commit, use the :meth:`_events.PoolEvents.reset` hook.
  440. :param conn: :class:`_engine.Connection` object
  441. """
  442. def savepoint(self, conn: Connection, name: str) -> None:
  443. """Intercept savepoint() events.
  444. :param conn: :class:`_engine.Connection` object
  445. :param name: specified name used for the savepoint.
  446. """
  447. def rollback_savepoint(
  448. self, conn: Connection, name: str, context: None
  449. ) -> None:
  450. """Intercept rollback_savepoint() events.
  451. :param conn: :class:`_engine.Connection` object
  452. :param name: specified name used for the savepoint.
  453. :param context: not used
  454. """
  455. # TODO: deprecate "context"
  456. def release_savepoint(
  457. self, conn: Connection, name: str, context: None
  458. ) -> None:
  459. """Intercept release_savepoint() events.
  460. :param conn: :class:`_engine.Connection` object
  461. :param name: specified name used for the savepoint.
  462. :param context: not used
  463. """
  464. # TODO: deprecate "context"
  465. def begin_twophase(self, conn: Connection, xid: Any) -> None:
  466. """Intercept begin_twophase() events.
  467. :param conn: :class:`_engine.Connection` object
  468. :param xid: two-phase XID identifier
  469. """
  470. def prepare_twophase(self, conn: Connection, xid: Any) -> None:
  471. """Intercept prepare_twophase() events.
  472. :param conn: :class:`_engine.Connection` object
  473. :param xid: two-phase XID identifier
  474. """
  475. def rollback_twophase(
  476. self, conn: Connection, xid: Any, is_prepared: bool
  477. ) -> None:
  478. """Intercept rollback_twophase() events.
  479. :param conn: :class:`_engine.Connection` object
  480. :param xid: two-phase XID identifier
  481. :param is_prepared: boolean, indicates if
  482. :meth:`.TwoPhaseTransaction.prepare` was called.
  483. """
  484. def commit_twophase(
  485. self, conn: Connection, xid: Any, is_prepared: bool
  486. ) -> None:
  487. """Intercept commit_twophase() events.
  488. :param conn: :class:`_engine.Connection` object
  489. :param xid: two-phase XID identifier
  490. :param is_prepared: boolean, indicates if
  491. :meth:`.TwoPhaseTransaction.prepare` was called.
  492. """
  493. class DialectEvents(event.Events[Dialect]):
  494. """event interface for execution-replacement functions.
  495. These events allow direct instrumentation and replacement
  496. of key dialect functions which interact with the DBAPI.
  497. .. note::
  498. :class:`.DialectEvents` hooks should be considered **semi-public**
  499. and experimental.
  500. These hooks are not for general use and are only for those situations
  501. where intricate re-statement of DBAPI mechanics must be injected onto
  502. an existing dialect. For general-use statement-interception events,
  503. please use the :class:`_events.ConnectionEvents` interface.
  504. .. seealso::
  505. :meth:`_events.ConnectionEvents.before_cursor_execute`
  506. :meth:`_events.ConnectionEvents.before_execute`
  507. :meth:`_events.ConnectionEvents.after_cursor_execute`
  508. :meth:`_events.ConnectionEvents.after_execute`
  509. """
  510. _target_class_doc = "SomeEngine"
  511. _dispatch_target = Dialect
  512. @classmethod
  513. def _listen(
  514. cls,
  515. event_key: event._EventKey[Dialect],
  516. *,
  517. retval: bool = False,
  518. **kw: Any,
  519. ) -> None:
  520. target = event_key.dispatch_target
  521. target._has_events = True
  522. event_key.base_listen()
  523. @classmethod
  524. def _accept_with(
  525. cls,
  526. target: Union[Engine, Type[Engine], Dialect, Type[Dialect]],
  527. identifier: str,
  528. ) -> Optional[Union[Dialect, Type[Dialect]]]:
  529. if isinstance(target, type):
  530. if issubclass(target, Engine):
  531. return Dialect
  532. elif issubclass(target, Dialect):
  533. return target
  534. elif isinstance(target, Engine):
  535. return target.dialect
  536. elif isinstance(target, Dialect):
  537. return target
  538. elif isinstance(target, Connection) and identifier == "handle_error":
  539. raise exc.InvalidRequestError(
  540. "The handle_error() event hook as of SQLAlchemy 2.0 is "
  541. "established on the Dialect, and may only be applied to the "
  542. "Engine as a whole or to a specific Dialect as a whole, "
  543. "not on a per-Connection basis."
  544. )
  545. elif hasattr(target, "_no_async_engine_events"):
  546. target._no_async_engine_events()
  547. else:
  548. return None
  549. def handle_error(
  550. self, exception_context: ExceptionContext
  551. ) -> Optional[BaseException]:
  552. r"""Intercept all exceptions processed by the
  553. :class:`_engine.Dialect`, typically but not limited to those
  554. emitted within the scope of a :class:`_engine.Connection`.
  555. .. versionchanged:: 2.0 the :meth:`.DialectEvents.handle_error` event
  556. is moved to the :class:`.DialectEvents` class, moved from the
  557. :class:`.ConnectionEvents` class, so that it may also participate in
  558. the "pre ping" operation configured with the
  559. :paramref:`_sa.create_engine.pool_pre_ping` parameter. The event
  560. remains registered by using the :class:`_engine.Engine` as the event
  561. target, however note that using the :class:`_engine.Connection` as
  562. an event target for :meth:`.DialectEvents.handle_error` is no longer
  563. supported.
  564. This includes all exceptions emitted by the DBAPI as well as
  565. within SQLAlchemy's statement invocation process, including
  566. encoding errors and other statement validation errors. Other areas
  567. in which the event is invoked include transaction begin and end,
  568. result row fetching, cursor creation.
  569. Note that :meth:`.handle_error` may support new kinds of exceptions
  570. and new calling scenarios at *any time*. Code which uses this
  571. event must expect new calling patterns to be present in minor
  572. releases.
  573. To support the wide variety of members that correspond to an exception,
  574. as well as to allow extensibility of the event without backwards
  575. incompatibility, the sole argument received is an instance of
  576. :class:`.ExceptionContext`. This object contains data members
  577. representing detail about the exception.
  578. Use cases supported by this hook include:
  579. * read-only, low-level exception handling for logging and
  580. debugging purposes
  581. * Establishing whether a DBAPI connection error message indicates
  582. that the database connection needs to be reconnected, including
  583. for the "pre_ping" handler used by **some** dialects
  584. * Establishing or disabling whether a connection or the owning
  585. connection pool is invalidated or expired in response to a
  586. specific exception
  587. * exception re-writing
  588. The hook is called while the cursor from the failed operation
  589. (if any) is still open and accessible. Special cleanup operations
  590. can be called on this cursor; SQLAlchemy will attempt to close
  591. this cursor subsequent to this hook being invoked.
  592. As of SQLAlchemy 2.0, the "pre_ping" handler enabled using the
  593. :paramref:`_sa.create_engine.pool_pre_ping` parameter will also
  594. participate in the :meth:`.handle_error` process, **for those dialects
  595. that rely upon disconnect codes to detect database liveness**. Note
  596. that some dialects such as psycopg, psycopg2, and most MySQL dialects
  597. make use of a native ``ping()`` method supplied by the DBAPI which does
  598. not make use of disconnect codes.
  599. .. versionchanged:: 2.0.0 The :meth:`.DialectEvents.handle_error`
  600. event hook participates in connection pool "pre-ping" operations.
  601. Within this usage, the :attr:`.ExceptionContext.engine` attribute
  602. will be ``None``, however the :class:`.Dialect` in use is always
  603. available via the :attr:`.ExceptionContext.dialect` attribute.
  604. .. versionchanged:: 2.0.5 Added :attr:`.ExceptionContext.is_pre_ping`
  605. attribute which will be set to ``True`` when the
  606. :meth:`.DialectEvents.handle_error` event hook is triggered within
  607. a connection pool pre-ping operation.
  608. .. versionchanged:: 2.0.5 An issue was repaired that allows for the
  609. PostgreSQL ``psycopg`` and ``psycopg2`` drivers, as well as all
  610. MySQL drivers, to properly participate in the
  611. :meth:`.DialectEvents.handle_error` event hook during
  612. connection pool "pre-ping" operations; previously, the
  613. implementation was non-working for these drivers.
  614. A handler function has two options for replacing
  615. the SQLAlchemy-constructed exception into one that is user
  616. defined. It can either raise this new exception directly, in
  617. which case all further event listeners are bypassed and the
  618. exception will be raised, after appropriate cleanup as taken
  619. place::
  620. @event.listens_for(Engine, "handle_error")
  621. def handle_exception(context):
  622. if isinstance(
  623. context.original_exception, psycopg2.OperationalError
  624. ) and "failed" in str(context.original_exception):
  625. raise MySpecialException("failed operation")
  626. .. warning:: Because the
  627. :meth:`_events.DialectEvents.handle_error`
  628. event specifically provides for exceptions to be re-thrown as
  629. the ultimate exception raised by the failed statement,
  630. **stack traces will be misleading** if the user-defined event
  631. handler itself fails and throws an unexpected exception;
  632. the stack trace may not illustrate the actual code line that
  633. failed! It is advised to code carefully here and use
  634. logging and/or inline debugging if unexpected exceptions are
  635. occurring.
  636. Alternatively, a "chained" style of event handling can be
  637. used, by configuring the handler with the ``retval=True``
  638. modifier and returning the new exception instance from the
  639. function. In this case, event handling will continue onto the
  640. next handler. The "chained" exception is available using
  641. :attr:`.ExceptionContext.chained_exception`::
  642. @event.listens_for(Engine, "handle_error", retval=True)
  643. def handle_exception(context):
  644. if (
  645. context.chained_exception is not None
  646. and "special" in context.chained_exception.message
  647. ):
  648. return MySpecialException(
  649. "failed", cause=context.chained_exception
  650. )
  651. Handlers that return ``None`` may be used within the chain; when
  652. a handler returns ``None``, the previous exception instance,
  653. if any, is maintained as the current exception that is passed onto the
  654. next handler.
  655. When a custom exception is raised or returned, SQLAlchemy raises
  656. this new exception as-is, it is not wrapped by any SQLAlchemy
  657. object. If the exception is not a subclass of
  658. :class:`sqlalchemy.exc.StatementError`,
  659. certain features may not be available; currently this includes
  660. the ORM's feature of adding a detail hint about "autoflush" to
  661. exceptions raised within the autoflush process.
  662. :param context: an :class:`.ExceptionContext` object. See this
  663. class for details on all available members.
  664. .. seealso::
  665. :ref:`pool_new_disconnect_codes`
  666. """
  667. def do_connect(
  668. self,
  669. dialect: Dialect,
  670. conn_rec: ConnectionPoolEntry,
  671. cargs: Tuple[Any, ...],
  672. cparams: Dict[str, Any],
  673. ) -> Optional[DBAPIConnection]:
  674. """Receive connection arguments before a connection is made.
  675. This event is useful in that it allows the handler to manipulate the
  676. cargs and/or cparams collections that control how the DBAPI
  677. ``connect()`` function will be called. ``cargs`` will always be a
  678. Python list that can be mutated in-place, and ``cparams`` a Python
  679. dictionary that may also be mutated::
  680. e = create_engine("postgresql+psycopg2://user@host/dbname")
  681. @event.listens_for(e, "do_connect")
  682. def receive_do_connect(dialect, conn_rec, cargs, cparams):
  683. cparams["password"] = "some_password"
  684. The event hook may also be used to override the call to ``connect()``
  685. entirely, by returning a non-``None`` DBAPI connection object::
  686. e = create_engine("postgresql+psycopg2://user@host/dbname")
  687. @event.listens_for(e, "do_connect")
  688. def receive_do_connect(dialect, conn_rec, cargs, cparams):
  689. return psycopg2.connect(*cargs, **cparams)
  690. .. seealso::
  691. :ref:`custom_dbapi_args`
  692. """
  693. def do_executemany(
  694. self,
  695. cursor: DBAPICursor,
  696. statement: str,
  697. parameters: _DBAPIMultiExecuteParams,
  698. context: ExecutionContext,
  699. ) -> Optional[Literal[True]]:
  700. """Receive a cursor to have executemany() called.
  701. Return the value True to halt further events from invoking,
  702. and to indicate that the cursor execution has already taken
  703. place within the event handler.
  704. """
  705. def do_execute_no_params(
  706. self, cursor: DBAPICursor, statement: str, context: ExecutionContext
  707. ) -> Optional[Literal[True]]:
  708. """Receive a cursor to have execute() with no parameters called.
  709. Return the value True to halt further events from invoking,
  710. and to indicate that the cursor execution has already taken
  711. place within the event handler.
  712. """
  713. def do_execute(
  714. self,
  715. cursor: DBAPICursor,
  716. statement: str,
  717. parameters: _DBAPISingleExecuteParams,
  718. context: ExecutionContext,
  719. ) -> Optional[Literal[True]]:
  720. """Receive a cursor to have execute() called.
  721. Return the value True to halt further events from invoking,
  722. and to indicate that the cursor execution has already taken
  723. place within the event handler.
  724. """
  725. def do_setinputsizes(
  726. self,
  727. inputsizes: Dict[BindParameter[Any], Any],
  728. cursor: DBAPICursor,
  729. statement: str,
  730. parameters: _DBAPIAnyExecuteParams,
  731. context: ExecutionContext,
  732. ) -> None:
  733. """Receive the setinputsizes dictionary for possible modification.
  734. This event is emitted in the case where the dialect makes use of the
  735. DBAPI ``cursor.setinputsizes()`` method which passes information about
  736. parameter binding for a particular statement. The given
  737. ``inputsizes`` dictionary will contain :class:`.BindParameter` objects
  738. as keys, linked to DBAPI-specific type objects as values; for
  739. parameters that are not bound, they are added to the dictionary with
  740. ``None`` as the value, which means the parameter will not be included
  741. in the ultimate setinputsizes call. The event may be used to inspect
  742. and/or log the datatypes that are being bound, as well as to modify the
  743. dictionary in place. Parameters can be added, modified, or removed
  744. from this dictionary. Callers will typically want to inspect the
  745. :attr:`.BindParameter.type` attribute of the given bind objects in
  746. order to make decisions about the DBAPI object.
  747. After the event, the ``inputsizes`` dictionary is converted into
  748. an appropriate datastructure to be passed to ``cursor.setinputsizes``;
  749. either a list for a positional bound parameter execution style,
  750. or a dictionary of string parameter keys to DBAPI type objects for
  751. a named bound parameter execution style.
  752. The setinputsizes hook overall is only used for dialects which include
  753. the flag ``use_setinputsizes=True``. Dialects which use this
  754. include python-oracledb, cx_Oracle, pg8000, asyncpg, and pyodbc
  755. dialects.
  756. .. note::
  757. For use with pyodbc, the ``use_setinputsizes`` flag
  758. must be passed to the dialect, e.g.::
  759. create_engine("mssql+pyodbc://...", use_setinputsizes=True)
  760. .. seealso::
  761. :ref:`mssql_pyodbc_setinputsizes`
  762. .. versionadded:: 1.2.9
  763. .. seealso::
  764. :ref:`cx_oracle_setinputsizes`
  765. """
  766. pass