summaryrefslogtreecommitdiffstats
path: root/lib/sqlalchemy/pool/events.py
blob: 2829a58ae30681bc34b638d94b3065bef94a1a98 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# sqlalchemy/pool/events.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php

from .base import Pool
from .. import event
from ..engine.base import Engine


class PoolEvents(event.Events):
    """Available events for :class:`_pool.Pool`.

    The methods here define the name of an event as well
    as the names of members that are passed to listener
    functions.

    e.g.::

        from sqlalchemy import event

        def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
            "handle an on checkout event"

        event.listen(Pool, 'checkout', my_on_checkout)

    In addition to accepting the :class:`_pool.Pool` class and
    :class:`_pool.Pool` instances, :class:`_events.PoolEvents` also accepts
    :class:`_engine.Engine` objects and the :class:`_engine.Engine` class as
    targets, which will be resolved to the ``.pool`` attribute of the
    given engine or the :class:`_pool.Pool` class::

        engine = create_engine("postgresql://scott:tiger@localhost/test")

        # will associate with engine.pool
        event.listen(engine, 'checkout', my_on_checkout)

    """

    _target_class_doc = "SomeEngineOrPool"
    _dispatch_target = Pool

    @classmethod
    def _accept_with(cls, target):
        if isinstance(target, type):
            if issubclass(target, Engine):
                return Pool
            elif issubclass(target, Pool):
                return target
        elif isinstance(target, Engine):
            return target.pool
        elif isinstance(target, Pool):
            return target
        elif hasattr(target, "dispatch") and hasattr(
            target.dispatch._events, "_no_async_engine_events"
        ):
            target.dispatch._events._no_async_engine_events()
        else:
            return None

    @classmethod
    def _listen(cls, event_key, **kw):
        target = event_key.dispatch_target

        kw.setdefault("asyncio", target._is_asyncio)

        event_key.base_listen(**kw)

    def connect(self, dbapi_connection, connection_record):
        """Called at the moment a particular DBAPI connection is first
        created for a given :class:`_pool.Pool`.

        This event allows one to capture the point directly after which
        the DBAPI module-level ``.connect()`` method has been used in order
        to produce a new DBAPI connection.

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        """

    def first_connect(self, dbapi_connection, connection_record):
        """Called exactly once for the first time a DBAPI connection is
        checked out from a particular :class:`_pool.Pool`.

        The rationale for :meth:`_events.PoolEvents.first_connect`
        is to determine
        information about a particular series of database connections based
        on the settings used for all connections.  Since a particular
        :class:`_pool.Pool`
        refers to a single "creator" function (which in terms
        of a :class:`_engine.Engine`
        refers to the URL and connection options used),
        it is typically valid to make observations about a single connection
        that can be safely assumed to be valid about all subsequent
        connections, such as the database version, the server and client
        encoding settings, collation settings, and many others.

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        """

    def checkout(self, dbapi_connection, connection_record, connection_proxy):
        """Called when a connection is retrieved from the Pool.

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        :param connection_proxy: the :class:`._ConnectionFairy` object which
          will proxy the public interface of the DBAPI connection for the
          lifespan of the checkout.

        If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current
        connection will be disposed and a fresh connection retrieved.
        Processing of all checkout listeners will abort and restart
        using the new connection.

        .. seealso:: :meth:`_events.ConnectionEvents.engine_connect`
           - a similar event
           which occurs upon creation of a new :class:`_engine.Connection`.

        """

    def checkin(self, dbapi_connection, connection_record):
        """Called when a connection returns to the pool.

        Note that the connection may be closed, and may be None if the
        connection has been invalidated.  ``checkin`` will not be called
        for detached connections.  (They do not return to the pool.)

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        """

    def reset(self, dbapi_connection, connection_record):
        """Called before the "reset" action occurs for a pooled connection.

        This event represents
        when the ``rollback()`` method is called on the DBAPI connection
        before it is returned to the pool.  The behavior of "reset" can
        be controlled, including disabled, using the ``reset_on_return``
        pool argument.


        The :meth:`_events.PoolEvents.reset` event is usually followed by the
        :meth:`_events.PoolEvents.checkin` event is called, except in those
        cases where the connection is discarded immediately after reset.

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        .. seealso::

            :meth:`_events.ConnectionEvents.rollback`

            :meth:`_events.ConnectionEvents.commit`

        """

    def invalidate(self, dbapi_connection, connection_record, exception):
        """Called when a DBAPI connection is to be "invalidated".

        This event is called any time the :meth:`._ConnectionRecord.invalidate`
        method is invoked, either from API usage or via "auto-invalidation",
        without the ``soft`` flag.

        The event occurs before a final attempt to call ``.close()`` on the
        connection occurs.

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        :param exception: the exception object corresponding to the reason
         for this invalidation, if any.  May be ``None``.

        .. versionadded:: 0.9.2 Added support for connection invalidation
           listening.

        .. seealso::

            :ref:`pool_connection_invalidation`

        """

    def soft_invalidate(self, dbapi_connection, connection_record, exception):
        """Called when a DBAPI connection is to be "soft invalidated".

        This event is called any time the :meth:`._ConnectionRecord.invalidate`
        method is invoked with the ``soft`` flag.

        Soft invalidation refers to when the connection record that tracks
        this connection will force a reconnect after the current connection
        is checked in.   It does not actively close the dbapi_connection
        at the point at which it is called.

        .. versionadded:: 1.0.3

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        :param exception: the exception object corresponding to the reason
         for this invalidation, if any.  May be ``None``.

        """

    def close(self, dbapi_connection, connection_record):
        """Called when a DBAPI connection is closed.

        The event is emitted before the close occurs.

        The close of a connection can fail; typically this is because
        the connection is already closed.  If the close operation fails,
        the connection is discarded.

        The :meth:`.close` event corresponds to a connection that's still
        associated with the pool. To intercept close events for detached
        connections use :meth:`.close_detached`.

        .. versionadded:: 1.1

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        """

    def detach(self, dbapi_connection, connection_record):
        """Called when a DBAPI connection is "detached" from a pool.

        This event is emitted after the detach occurs.  The connection
        is no longer associated with the given connection record.

        .. versionadded:: 1.1

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        :param connection_record: the :class:`._ConnectionRecord` managing the
         DBAPI connection.

        """

    def close_detached(self, dbapi_connection):
        """Called when a detached DBAPI connection is closed.

        The event is emitted before the close occurs.

        The close of a connection can fail; typically this is because
        the connection is already closed.  If the close operation fails,
        the connection is discarded.

        .. versionadded:: 1.1

        :param dbapi_connection: a DBAPI connection.
         The :attr:`._ConnectionRecord.dbapi_connection` attribute.

        """