PageRenderTime 83ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/sqlalchemy/interfaces.py

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