interfaces.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. # sqlalchemy/interfaces.py
  2. # Copyright (C) 2007-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. # Copyright (C) 2007 Jason Kirtland jek@discorporate.us
  5. #
  6. # This module is part of SQLAlchemy and is released under
  7. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  8. """Deprecated core event interfaces.
  9. This module is **deprecated** and is superseded by the
  10. event system.
  11. """
  12. from . import event, util
  13. class PoolListener(object):
  14. """Hooks into the lifecycle of connections in a :class:`.Pool`.
  15. .. note::
  16. :class:`.PoolListener` is deprecated. Please
  17. refer to :class:`.PoolEvents`.
  18. Usage::
  19. class MyListener(PoolListener):
  20. def connect(self, dbapi_con, con_record):
  21. '''perform connect operations'''
  22. # etc.
  23. # create a new pool with a listener
  24. p = QueuePool(..., listeners=[MyListener()])
  25. # add a listener after the fact
  26. p.add_listener(MyListener())
  27. # usage with create_engine()
  28. e = create_engine("url://", listeners=[MyListener()])
  29. All of the standard connection :class:`~sqlalchemy.pool.Pool` types can
  30. accept event listeners for key connection lifecycle events:
  31. creation, pool check-out and check-in. There are no events fired
  32. when a connection closes.
  33. For any given DB-API connection, there will be one ``connect``
  34. event, `n` number of ``checkout`` events, and either `n` or `n - 1`
  35. ``checkin`` events. (If a ``Connection`` is detached from its
  36. pool via the ``detach()`` method, it won't be checked back in.)
  37. These are low-level events for low-level objects: raw Python
  38. DB-API connections, without the conveniences of the SQLAlchemy
  39. ``Connection`` wrapper, ``Dialect`` services or ``ClauseElement``
  40. execution. If you execute SQL through the connection, explicitly
  41. closing all cursors and other resources is recommended.
  42. Events also receive a ``_ConnectionRecord``, a long-lived internal
  43. ``Pool`` object that basically represents a "slot" in the
  44. connection pool. ``_ConnectionRecord`` objects have one public
  45. attribute of note: ``info``, a dictionary whose contents are
  46. scoped to the lifetime of the DB-API connection managed by the
  47. record. You can use this shared storage area however you like.
  48. There is no need to subclass ``PoolListener`` to handle events.
  49. Any class that implements one or more of these methods can be used
  50. as a pool listener. The ``Pool`` will inspect the methods
  51. provided by a listener object and add the listener to one or more
  52. internal event queues based on its capabilities. In terms of
  53. efficiency and function call overhead, you're much better off only
  54. providing implementations for the hooks you'll be using.
  55. """
  56. @classmethod
  57. def _adapt_listener(cls, self, listener):
  58. """Adapt a :class:`.PoolListener` to individual
  59. :class:`event.Dispatch` events.
  60. """
  61. listener = util.as_interface(listener,
  62. methods=('connect', 'first_connect',
  63. 'checkout', 'checkin'))
  64. if hasattr(listener, 'connect'):
  65. event.listen(self, 'connect', listener.connect)
  66. if hasattr(listener, 'first_connect'):
  67. event.listen(self, 'first_connect', listener.first_connect)
  68. if hasattr(listener, 'checkout'):
  69. event.listen(self, 'checkout', listener.checkout)
  70. if hasattr(listener, 'checkin'):
  71. event.listen(self, 'checkin', listener.checkin)
  72. def connect(self, dbapi_con, con_record):
  73. """Called once for each new DB-API connection or Pool's ``creator()``.
  74. dbapi_con
  75. A newly connected raw DB-API connection (not a SQLAlchemy
  76. ``Connection`` wrapper).
  77. con_record
  78. The ``_ConnectionRecord`` that persistently manages the connection
  79. """
  80. def first_connect(self, dbapi_con, con_record):
  81. """Called exactly once for the first DB-API connection.
  82. dbapi_con
  83. A newly connected raw DB-API connection (not a SQLAlchemy
  84. ``Connection`` wrapper).
  85. con_record
  86. The ``_ConnectionRecord`` that persistently manages the connection
  87. """
  88. def checkout(self, dbapi_con, con_record, con_proxy):
  89. """Called when a connection is retrieved from the Pool.
  90. dbapi_con
  91. A raw DB-API connection
  92. con_record
  93. The ``_ConnectionRecord`` that persistently manages the connection
  94. con_proxy
  95. The ``_ConnectionFairy`` which manages the connection for the span of
  96. the current checkout.
  97. If you raise an ``exc.DisconnectionError``, the current
  98. connection will be disposed and a fresh connection retrieved.
  99. Processing of all checkout listeners will abort and restart
  100. using the new connection.
  101. """
  102. def checkin(self, dbapi_con, con_record):
  103. """Called when a connection returns to the pool.
  104. Note that the connection may be closed, and may be None if the
  105. connection has been invalidated. ``checkin`` will not be called
  106. for detached connections. (They do not return to the pool.)
  107. dbapi_con
  108. A raw DB-API connection
  109. con_record
  110. The ``_ConnectionRecord`` that persistently manages the connection
  111. """
  112. class ConnectionProxy(object):
  113. """Allows interception of statement execution by Connections.
  114. .. note::
  115. :class:`.ConnectionProxy` is deprecated. Please
  116. refer to :class:`.ConnectionEvents`.
  117. Either or both of the ``execute()`` and ``cursor_execute()``
  118. may be implemented to intercept compiled statement and
  119. cursor level executions, e.g.::
  120. class MyProxy(ConnectionProxy):
  121. def execute(self, conn, execute, clauseelement,
  122. *multiparams, **params):
  123. print "compiled statement:", clauseelement
  124. return execute(clauseelement, *multiparams, **params)
  125. def cursor_execute(self, execute, cursor, statement,
  126. parameters, context, executemany):
  127. print "raw statement:", statement
  128. return execute(cursor, statement, parameters, context)
  129. The ``execute`` argument is a function that will fulfill the default
  130. execution behavior for the operation. The signature illustrated
  131. in the example should be used.
  132. The proxy is installed into an :class:`~sqlalchemy.engine.Engine` via
  133. the ``proxy`` argument::
  134. e = create_engine('someurl://', proxy=MyProxy())
  135. """
  136. @classmethod
  137. def _adapt_listener(cls, self, listener):
  138. def adapt_execute(conn, clauseelement, multiparams, params):
  139. def execute_wrapper(clauseelement, *multiparams, **params):
  140. return clauseelement, multiparams, params
  141. return listener.execute(conn, execute_wrapper,
  142. clauseelement, *multiparams,
  143. **params)
  144. event.listen(self, 'before_execute', adapt_execute)
  145. def adapt_cursor_execute(conn, cursor, statement,
  146. parameters, context, executemany):
  147. def execute_wrapper(
  148. cursor,
  149. statement,
  150. parameters,
  151. context,
  152. ):
  153. return statement, parameters
  154. return listener.cursor_execute(
  155. execute_wrapper,
  156. cursor,
  157. statement,
  158. parameters,
  159. context,
  160. executemany,
  161. )
  162. event.listen(self, 'before_cursor_execute', adapt_cursor_execute)
  163. def do_nothing_callback(*arg, **kw):
  164. pass
  165. def adapt_listener(fn):
  166. def go(conn, *arg, **kw):
  167. fn(conn, do_nothing_callback, *arg, **kw)
  168. return util.update_wrapper(go, fn)
  169. event.listen(self, 'begin', adapt_listener(listener.begin))
  170. event.listen(self, 'rollback',
  171. adapt_listener(listener.rollback))
  172. event.listen(self, 'commit', adapt_listener(listener.commit))
  173. event.listen(self, 'savepoint',
  174. adapt_listener(listener.savepoint))
  175. event.listen(self, 'rollback_savepoint',
  176. adapt_listener(listener.rollback_savepoint))
  177. event.listen(self, 'release_savepoint',
  178. adapt_listener(listener.release_savepoint))
  179. event.listen(self, 'begin_twophase',
  180. adapt_listener(listener.begin_twophase))
  181. event.listen(self, 'prepare_twophase',
  182. adapt_listener(listener.prepare_twophase))
  183. event.listen(self, 'rollback_twophase',
  184. adapt_listener(listener.rollback_twophase))
  185. event.listen(self, 'commit_twophase',
  186. adapt_listener(listener.commit_twophase))
  187. def execute(self, conn, execute, clauseelement, *multiparams, **params):
  188. """Intercept high level execute() events."""
  189. return execute(clauseelement, *multiparams, **params)
  190. def cursor_execute(self, execute, cursor, statement, parameters,
  191. context, executemany):
  192. """Intercept low-level cursor execute() events."""
  193. return execute(cursor, statement, parameters, context)
  194. def begin(self, conn, begin):
  195. """Intercept begin() events."""
  196. return begin()
  197. def rollback(self, conn, rollback):
  198. """Intercept rollback() events."""
  199. return rollback()
  200. def commit(self, conn, commit):
  201. """Intercept commit() events."""
  202. return commit()
  203. def savepoint(self, conn, savepoint, name=None):
  204. """Intercept savepoint() events."""
  205. return savepoint(name=name)
  206. def rollback_savepoint(self, conn, rollback_savepoint, name, context):
  207. """Intercept rollback_savepoint() events."""
  208. return rollback_savepoint(name, context)
  209. def release_savepoint(self, conn, release_savepoint, name, context):
  210. """Intercept release_savepoint() events."""
  211. return release_savepoint(name, context)
  212. def begin_twophase(self, conn, begin_twophase, xid):
  213. """Intercept begin_twophase() events."""
  214. return begin_twophase(xid)
  215. def prepare_twophase(self, conn, prepare_twophase, xid):
  216. """Intercept prepare_twophase() events."""
  217. return prepare_twophase(xid)
  218. def rollback_twophase(self, conn, rollback_twophase, xid, is_prepared):
  219. """Intercept rollback_twophase() events."""
  220. return rollback_twophase(xid, is_prepared)
  221. def commit_twophase(self, conn, commit_twophase, xid, is_prepared):
  222. """Intercept commit_twophase() events."""
  223. return commit_twophase(xid, is_prepared)