adbapi.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. # -*- test-case-name: twisted.test.test_adbapi -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An asynchronous mapping to U{DB-API
  6. 2.0<http://www.python.org/topics/database/DatabaseAPI-2.0.html>}.
  7. """
  8. import sys
  9. from twisted.internet import threads
  10. from twisted.python import reflect, log, compat
  11. class ConnectionLost(Exception):
  12. """
  13. This exception means that a db connection has been lost. Client code may
  14. try again.
  15. """
  16. class Connection(object):
  17. """
  18. A wrapper for a DB-API connection instance.
  19. The wrapper passes almost everything to the wrapped connection and so has
  20. the same API. However, the L{Connection} knows about its pool and also
  21. handle reconnecting should when the real connection dies.
  22. """
  23. def __init__(self, pool):
  24. self._pool = pool
  25. self._connection = None
  26. self.reconnect()
  27. def close(self):
  28. # The way adbapi works right now means that closing a connection is
  29. # a really bad thing as it leaves a dead connection associated with
  30. # a thread in the thread pool.
  31. # Really, I think closing a pooled connection should return it to the
  32. # pool but that's handled by the runWithConnection method already so,
  33. # rather than upsetting anyone by raising an exception, let's ignore
  34. # the request
  35. pass
  36. def rollback(self):
  37. if not self._pool.reconnect:
  38. self._connection.rollback()
  39. return
  40. try:
  41. self._connection.rollback()
  42. curs = self._connection.cursor()
  43. curs.execute(self._pool.good_sql)
  44. curs.close()
  45. self._connection.commit()
  46. return
  47. except:
  48. log.err(None, "Rollback failed")
  49. self._pool.disconnect(self._connection)
  50. if self._pool.noisy:
  51. log.msg("Connection lost.")
  52. raise ConnectionLost()
  53. def reconnect(self):
  54. if self._connection is not None:
  55. self._pool.disconnect(self._connection)
  56. self._connection = self._pool.connect()
  57. def __getattr__(self, name):
  58. return getattr(self._connection, name)
  59. class Transaction:
  60. """
  61. A lightweight wrapper for a DB-API 'cursor' object.
  62. Relays attribute access to the DB cursor. That is, you can call
  63. C{execute()}, C{fetchall()}, etc., and they will be called on the
  64. underlying DB-API cursor object. Attributes will also be retrieved from
  65. there.
  66. """
  67. _cursor = None
  68. def __init__(self, pool, connection):
  69. self._pool = pool
  70. self._connection = connection
  71. self.reopen()
  72. def close(self):
  73. _cursor = self._cursor
  74. self._cursor = None
  75. _cursor.close()
  76. def reopen(self):
  77. if self._cursor is not None:
  78. self.close()
  79. try:
  80. self._cursor = self._connection.cursor()
  81. return
  82. except:
  83. if not self._pool.reconnect:
  84. raise
  85. else:
  86. log.err(None, "Cursor creation failed")
  87. if self._pool.noisy:
  88. log.msg('Connection lost, reconnecting')
  89. self.reconnect()
  90. self._cursor = self._connection.cursor()
  91. def reconnect(self):
  92. self._connection.reconnect()
  93. self._cursor = None
  94. def __getattr__(self, name):
  95. return getattr(self._cursor, name)
  96. class ConnectionPool:
  97. """
  98. Represent a pool of connections to a DB-API 2.0 compliant database.
  99. @ivar connectionFactory: factory for connections, default to L{Connection}.
  100. @type connectionFactory: any callable.
  101. @ivar transactionFactory: factory for transactions, default to
  102. L{Transaction}.
  103. @type transactionFactory: any callable
  104. @ivar shutdownID: L{None} or a handle on the shutdown event trigger which
  105. will be used to stop the connection pool workers when the reactor
  106. stops.
  107. @ivar _reactor: The reactor which will be used to schedule startup and
  108. shutdown events.
  109. @type _reactor: L{IReactorCore} provider
  110. """
  111. CP_ARGS = "min max name noisy openfun reconnect good_sql".split()
  112. noisy = False # If true, generate informational log messages
  113. min = 3 # Minimum number of connections in pool
  114. max = 5 # Maximum number of connections in pool
  115. name = None # Name to assign to thread pool for debugging
  116. openfun = None # A function to call on new connections
  117. reconnect = False # Reconnect when connections fail
  118. good_sql = 'select 1' # A query which should always succeed
  119. running = False # True when the pool is operating
  120. connectionFactory = Connection
  121. transactionFactory = Transaction
  122. # Initialize this to None so it's available in close() even if start()
  123. # never runs.
  124. shutdownID = None
  125. def __init__(self, dbapiName, *connargs, **connkw):
  126. """
  127. Create a new L{ConnectionPool}.
  128. Any positional or keyword arguments other than those documented here
  129. are passed to the DB-API object when connecting. Use these arguments to
  130. pass database names, usernames, passwords, etc.
  131. @param dbapiName: an import string to use to obtain a DB-API compatible
  132. module (e.g. C{'pyPgSQL.PgSQL'})
  133. @param cp_min: the minimum number of connections in pool (default 3)
  134. @param cp_max: the maximum number of connections in pool (default 5)
  135. @param cp_noisy: generate informational log messages during operation
  136. (default C{False})
  137. @param cp_openfun: a callback invoked after every C{connect()} on the
  138. underlying DB-API object. The callback is passed a new DB-API
  139. connection object. This callback can setup per-connection state
  140. such as charset, timezone, etc.
  141. @param cp_reconnect: detect connections which have failed and reconnect
  142. (default C{False}). Failed connections may result in
  143. L{ConnectionLost} exceptions, which indicate the query may need to
  144. be re-sent.
  145. @param cp_good_sql: an sql query which should always succeed and change
  146. no state (default C{'select 1'})
  147. @param cp_reactor: use this reactor instead of the global reactor
  148. (added in Twisted 10.2).
  149. @type cp_reactor: L{IReactorCore} provider
  150. """
  151. self.dbapiName = dbapiName
  152. self.dbapi = reflect.namedModule(dbapiName)
  153. if getattr(self.dbapi, 'apilevel', None) != '2.0':
  154. log.msg('DB API module not DB API 2.0 compliant.')
  155. if getattr(self.dbapi, 'threadsafety', 0) < 1:
  156. log.msg('DB API module not sufficiently thread-safe.')
  157. reactor = connkw.pop('cp_reactor', None)
  158. if reactor is None:
  159. from twisted.internet import reactor
  160. self._reactor = reactor
  161. self.connargs = connargs
  162. self.connkw = connkw
  163. for arg in self.CP_ARGS:
  164. cpArg = 'cp_%s' % (arg,)
  165. if cpArg in connkw:
  166. setattr(self, arg, connkw[cpArg])
  167. del connkw[cpArg]
  168. self.min = min(self.min, self.max)
  169. self.max = max(self.min, self.max)
  170. # All connections, hashed on thread id
  171. self.connections = {}
  172. # These are optional so import them here
  173. from twisted.python import threadpool
  174. from twisted.python import threadable
  175. self.threadID = threadable.getThreadID
  176. self.threadpool = threadpool.ThreadPool(self.min, self.max)
  177. self.startID = self._reactor.callWhenRunning(self._start)
  178. def _start(self):
  179. self.startID = None
  180. return self.start()
  181. def start(self):
  182. """
  183. Start the connection pool.
  184. If you are using the reactor normally, this function does *not*
  185. need to be called.
  186. """
  187. if not self.running:
  188. self.threadpool.start()
  189. self.shutdownID = self._reactor.addSystemEventTrigger(
  190. 'during', 'shutdown', self.finalClose)
  191. self.running = True
  192. def runWithConnection(self, func, *args, **kw):
  193. """
  194. Execute a function with a database connection and return the result.
  195. @param func: A callable object of one argument which will be executed
  196. in a thread with a connection from the pool. It will be passed as
  197. its first argument a L{Connection} instance (whose interface is
  198. mostly identical to that of a connection object for your DB-API
  199. module of choice), and its results will be returned as a
  200. L{Deferred}. If the method raises an exception the transaction will
  201. be rolled back. Otherwise, the transaction will be committed.
  202. B{Note} that this function is B{not} run in the main thread: it
  203. must be threadsafe.
  204. @param *args: positional arguments to be passed to func
  205. @param **kw: keyword arguments to be passed to func
  206. @return: a L{Deferred} which will fire the return value of
  207. C{func(Transaction(...), *args, **kw)}, or a
  208. L{twisted.python.failure.Failure}.
  209. """
  210. return threads.deferToThreadPool(self._reactor, self.threadpool,
  211. self._runWithConnection,
  212. func, *args, **kw)
  213. def _runWithConnection(self, func, *args, **kw):
  214. conn = self.connectionFactory(self)
  215. try:
  216. result = func(conn, *args, **kw)
  217. conn.commit()
  218. return result
  219. except:
  220. excType, excValue, excTraceback = sys.exc_info()
  221. try:
  222. conn.rollback()
  223. except:
  224. log.err(None, "Rollback failed")
  225. compat.reraise(excValue, excTraceback)
  226. def runInteraction(self, interaction, *args, **kw):
  227. """
  228. Interact with the database and return the result.
  229. The 'interaction' is a callable object which will be executed in a
  230. thread using a pooled connection. It will be passed an L{Transaction}
  231. object as an argument (whose interface is identical to that of the
  232. database cursor for your DB-API module of choice), and its results will
  233. be returned as a L{Deferred}. If running the method raises an
  234. exception, the transaction will be rolled back. If the method returns a
  235. value, the transaction will be committed.
  236. NOTE that the function you pass is *not* run in the main thread: you
  237. may have to worry about thread-safety in the function you pass to this
  238. if it tries to use non-local objects.
  239. @param interaction: a callable object whose first argument is an
  240. L{adbapi.Transaction}.
  241. @param *args: additional positional arguments to be passed to
  242. interaction
  243. @param **kw: keyword arguments to be passed to interaction
  244. @return: a Deferred which will fire the return value of
  245. C{interaction(Transaction(...), *args, **kw)}, or a
  246. L{twisted.python.failure.Failure}.
  247. """
  248. return threads.deferToThreadPool(self._reactor, self.threadpool,
  249. self._runInteraction,
  250. interaction, *args, **kw)
  251. def runQuery(self, *args, **kw):
  252. """
  253. Execute an SQL query and return the result.
  254. A DB-API cursor which will be invoked with C{cursor.execute(*args,
  255. **kw)}. The exact nature of the arguments will depend on the specific
  256. flavor of DB-API being used, but the first argument in C{*args} be an
  257. SQL statement. The result of a subsequent C{cursor.fetchall()} will be
  258. fired to the L{Deferred} which is returned. If either the 'execute' or
  259. 'fetchall' methods raise an exception, the transaction will be rolled
  260. back and a L{twisted.python.failure.Failure} returned.
  261. The C{*args} and C{**kw} arguments will be passed to the DB-API
  262. cursor's 'execute' method.
  263. @return: a L{Deferred} which will fire the return value of a DB-API
  264. cursor's 'fetchall' method, or a L{twisted.python.failure.Failure}.
  265. """
  266. return self.runInteraction(self._runQuery, *args, **kw)
  267. def runOperation(self, *args, **kw):
  268. """
  269. Execute an SQL query and return L{None}.
  270. A DB-API cursor which will be invoked with C{cursor.execute(*args,
  271. **kw)}. The exact nature of the arguments will depend on the specific
  272. flavor of DB-API being used, but the first argument in C{*args} will be
  273. an SQL statement. This method will not attempt to fetch any results
  274. from the query and is thus suitable for C{INSERT}, C{DELETE}, and other
  275. SQL statements which do not return values. If the 'execute' method
  276. raises an exception, the transaction will be rolled back and a
  277. L{Failure} returned.
  278. The C{*args} and C{*kw} arguments will be passed to the DB-API cursor's
  279. 'execute' method.
  280. @return: a L{Deferred} which will fire with L{None} or a
  281. L{twisted.python.failure.Failure}.
  282. """
  283. return self.runInteraction(self._runOperation, *args, **kw)
  284. def close(self):
  285. """
  286. Close all pool connections and shutdown the pool.
  287. """
  288. if self.shutdownID:
  289. self._reactor.removeSystemEventTrigger(self.shutdownID)
  290. self.shutdownID = None
  291. if self.startID:
  292. self._reactor.removeSystemEventTrigger(self.startID)
  293. self.startID = None
  294. self.finalClose()
  295. def finalClose(self):
  296. """
  297. This should only be called by the shutdown trigger.
  298. """
  299. self.shutdownID = None
  300. self.threadpool.stop()
  301. self.running = False
  302. for conn in self.connections.values():
  303. self._close(conn)
  304. self.connections.clear()
  305. def connect(self):
  306. """
  307. Return a database connection when one becomes available.
  308. This method blocks and should be run in a thread from the internal
  309. threadpool. Don't call this method directly from non-threaded code.
  310. Using this method outside the external threadpool may exceed the
  311. maximum number of connections in the pool.
  312. @return: a database connection from the pool.
  313. """
  314. tid = self.threadID()
  315. conn = self.connections.get(tid)
  316. if conn is None:
  317. if self.noisy:
  318. log.msg('adbapi connecting: %s' % (self.dbapiName,))
  319. conn = self.dbapi.connect(*self.connargs, **self.connkw)
  320. if self.openfun is not None:
  321. self.openfun(conn)
  322. self.connections[tid] = conn
  323. return conn
  324. def disconnect(self, conn):
  325. """
  326. Disconnect a database connection associated with this pool.
  327. Note: This function should only be used by the same thread which called
  328. L{ConnectionPool.connect}. As with C{connect}, this function is not
  329. used in normal non-threaded Twisted code.
  330. """
  331. tid = self.threadID()
  332. if conn is not self.connections.get(tid):
  333. raise Exception("wrong connection for thread")
  334. if conn is not None:
  335. self._close(conn)
  336. del self.connections[tid]
  337. def _close(self, conn):
  338. if self.noisy:
  339. log.msg('adbapi closing: %s' % (self.dbapiName,))
  340. try:
  341. conn.close()
  342. except:
  343. log.err(None, "Connection close failed")
  344. def _runInteraction(self, interaction, *args, **kw):
  345. conn = self.connectionFactory(self)
  346. trans = self.transactionFactory(self, conn)
  347. try:
  348. result = interaction(trans, *args, **kw)
  349. trans.close()
  350. conn.commit()
  351. return result
  352. except:
  353. excType, excValue, excTraceback = sys.exc_info()
  354. try:
  355. conn.rollback()
  356. except:
  357. log.err(None, "Rollback failed")
  358. compat.reraise(excValue, excTraceback)
  359. def _runQuery(self, trans, *args, **kw):
  360. trans.execute(*args, **kw)
  361. return trans.fetchall()
  362. def _runOperation(self, trans, *args, **kw):
  363. trans.execute(*args, **kw)
  364. def __getstate__(self):
  365. return {'dbapiName': self.dbapiName,
  366. 'min': self.min,
  367. 'max': self.max,
  368. 'noisy': self.noisy,
  369. 'reconnect': self.reconnect,
  370. 'good_sql': self.good_sql,
  371. 'connargs': self.connargs,
  372. 'connkw': self.connkw}
  373. def __setstate__(self, state):
  374. self.__dict__ = state
  375. self.__init__(self.dbapiName, *self.connargs, **self.connkw)
  376. __all__ = ['Transaction', 'ConnectionPool']