Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

adbapi.py 16KB

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