events.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. # sqlalchemy/pool/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 Pool
  8. from .. import event
  9. from ..engine.base import Engine
  10. class PoolEvents(event.Events):
  11. """Available events for :class:`_pool.Pool`.
  12. The methods here define the name of an event as well
  13. as the names of members that are passed to listener
  14. functions.
  15. e.g.::
  16. from sqlalchemy import event
  17. def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
  18. "handle an on checkout event"
  19. event.listen(Pool, 'checkout', my_on_checkout)
  20. In addition to accepting the :class:`_pool.Pool` class and
  21. :class:`_pool.Pool` instances, :class:`_events.PoolEvents` also accepts
  22. :class:`_engine.Engine` objects and the :class:`_engine.Engine` class as
  23. targets, which will be resolved to the ``.pool`` attribute of the
  24. given engine or the :class:`_pool.Pool` class::
  25. engine = create_engine("postgresql://scott:tiger@localhost/test")
  26. # will associate with engine.pool
  27. event.listen(engine, 'checkout', my_on_checkout)
  28. """
  29. _target_class_doc = "SomeEngineOrPool"
  30. _dispatch_target = Pool
  31. @classmethod
  32. def _accept_with(cls, target):
  33. if isinstance(target, type):
  34. if issubclass(target, Engine):
  35. return Pool
  36. elif issubclass(target, Pool):
  37. return target
  38. elif isinstance(target, Engine):
  39. return target.pool
  40. else:
  41. return target
  42. @classmethod
  43. def _listen(cls, event_key, **kw):
  44. target = event_key.dispatch_target
  45. kw.setdefault("asyncio", target._is_asyncio)
  46. event_key.base_listen(**kw)
  47. def connect(self, dbapi_connection, connection_record):
  48. """Called at the moment a particular DBAPI connection is first
  49. created for a given :class:`_pool.Pool`.
  50. This event allows one to capture the point directly after which
  51. the DBAPI module-level ``.connect()`` method has been used in order
  52. to produce a new DBAPI connection.
  53. :param dbapi_connection: a DBAPI connection.
  54. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  55. :param connection_record: the :class:`._ConnectionRecord` managing the
  56. DBAPI connection.
  57. """
  58. def first_connect(self, dbapi_connection, connection_record):
  59. """Called exactly once for the first time a DBAPI connection is
  60. checked out from a particular :class:`_pool.Pool`.
  61. The rationale for :meth:`_events.PoolEvents.first_connect`
  62. is to determine
  63. information about a particular series of database connections based
  64. on the settings used for all connections. Since a particular
  65. :class:`_pool.Pool`
  66. refers to a single "creator" function (which in terms
  67. of a :class:`_engine.Engine`
  68. refers to the URL and connection options used),
  69. it is typically valid to make observations about a single connection
  70. that can be safely assumed to be valid about all subsequent
  71. connections, such as the database version, the server and client
  72. encoding settings, collation settings, and many others.
  73. :param dbapi_connection: a DBAPI connection.
  74. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  75. :param connection_record: the :class:`._ConnectionRecord` managing the
  76. DBAPI connection.
  77. """
  78. def checkout(self, dbapi_connection, connection_record, connection_proxy):
  79. """Called when a connection is retrieved from the Pool.
  80. :param dbapi_connection: a DBAPI connection.
  81. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  82. :param connection_record: the :class:`._ConnectionRecord` managing the
  83. DBAPI connection.
  84. :param connection_proxy: the :class:`._ConnectionFairy` object which
  85. will proxy the public interface of the DBAPI connection for the
  86. lifespan of the checkout.
  87. If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current
  88. connection will be disposed and a fresh connection retrieved.
  89. Processing of all checkout listeners will abort and restart
  90. using the new connection.
  91. .. seealso:: :meth:`_events.ConnectionEvents.engine_connect`
  92. - a similar event
  93. which occurs upon creation of a new :class:`_engine.Connection`.
  94. """
  95. def checkin(self, dbapi_connection, connection_record):
  96. """Called when a connection returns to the pool.
  97. Note that the connection may be closed, and may be None if the
  98. connection has been invalidated. ``checkin`` will not be called
  99. for detached connections. (They do not return to the pool.)
  100. :param dbapi_connection: a DBAPI connection.
  101. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  102. :param connection_record: the :class:`._ConnectionRecord` managing the
  103. DBAPI connection.
  104. """
  105. def reset(self, dbapi_connection, connection_record):
  106. """Called before the "reset" action occurs for a pooled connection.
  107. This event represents
  108. when the ``rollback()`` method is called on the DBAPI connection
  109. before it is returned to the pool. The behavior of "reset" can
  110. be controlled, including disabled, using the ``reset_on_return``
  111. pool argument.
  112. The :meth:`_events.PoolEvents.reset` event is usually followed by the
  113. :meth:`_events.PoolEvents.checkin` event is called, except in those
  114. cases where the connection is discarded immediately after reset.
  115. :param dbapi_connection: a DBAPI connection.
  116. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  117. :param connection_record: the :class:`._ConnectionRecord` managing the
  118. DBAPI connection.
  119. .. seealso::
  120. :meth:`_events.ConnectionEvents.rollback`
  121. :meth:`_events.ConnectionEvents.commit`
  122. """
  123. def invalidate(self, dbapi_connection, connection_record, exception):
  124. """Called when a DBAPI connection is to be "invalidated".
  125. This event is called any time the :meth:`._ConnectionRecord.invalidate`
  126. method is invoked, either from API usage or via "auto-invalidation",
  127. without the ``soft`` flag.
  128. The event occurs before a final attempt to call ``.close()`` on the
  129. connection occurs.
  130. :param dbapi_connection: a DBAPI connection.
  131. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  132. :param connection_record: the :class:`._ConnectionRecord` managing the
  133. DBAPI connection.
  134. :param exception: the exception object corresponding to the reason
  135. for this invalidation, if any. May be ``None``.
  136. .. versionadded:: 0.9.2 Added support for connection invalidation
  137. listening.
  138. .. seealso::
  139. :ref:`pool_connection_invalidation`
  140. """
  141. def soft_invalidate(self, dbapi_connection, connection_record, exception):
  142. """Called when a DBAPI connection is to be "soft invalidated".
  143. This event is called any time the :meth:`._ConnectionRecord.invalidate`
  144. method is invoked with the ``soft`` flag.
  145. Soft invalidation refers to when the connection record that tracks
  146. this connection will force a reconnect after the current connection
  147. is checked in. It does not actively close the dbapi_connection
  148. at the point at which it is called.
  149. .. versionadded:: 1.0.3
  150. :param dbapi_connection: a DBAPI connection.
  151. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  152. :param connection_record: the :class:`._ConnectionRecord` managing the
  153. DBAPI connection.
  154. :param exception: the exception object corresponding to the reason
  155. for this invalidation, if any. May be ``None``.
  156. """
  157. def close(self, dbapi_connection, connection_record):
  158. """Called when a DBAPI connection is closed.
  159. The event is emitted before the close occurs.
  160. The close of a connection can fail; typically this is because
  161. the connection is already closed. If the close operation fails,
  162. the connection is discarded.
  163. The :meth:`.close` event corresponds to a connection that's still
  164. associated with the pool. To intercept close events for detached
  165. connections use :meth:`.close_detached`.
  166. .. versionadded:: 1.1
  167. :param dbapi_connection: a DBAPI connection.
  168. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  169. :param connection_record: the :class:`._ConnectionRecord` managing the
  170. DBAPI connection.
  171. """
  172. def detach(self, dbapi_connection, connection_record):
  173. """Called when a DBAPI connection is "detached" from a pool.
  174. This event is emitted after the detach occurs. The connection
  175. is no longer associated with the given connection record.
  176. .. versionadded:: 1.1
  177. :param dbapi_connection: a DBAPI connection.
  178. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  179. :param connection_record: the :class:`._ConnectionRecord` managing the
  180. DBAPI connection.
  181. """
  182. def close_detached(self, dbapi_connection):
  183. """Called when a detached DBAPI connection is closed.
  184. The event is emitted before the close occurs.
  185. The close of a connection can fail; typically this is because
  186. the connection is already closed. If the close operation fails,
  187. the connection is discarded.
  188. .. versionadded:: 1.1
  189. :param dbapi_connection: a DBAPI connection.
  190. The :attr:`._ConnectionRecord.dbapi_connection` attribute.
  191. """