events.py 33 KB

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