pool.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. # sqlalchemy/pool.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  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. """Connection pooling for DB-API connections.
  8. Provides a number of connection pool implementations for a variety of
  9. usage scenarios and thread behavior requirements imposed by the
  10. application, DB-API or database itself.
  11. Also provides a DB-API 2.0 connection proxying mechanism allowing
  12. regular DB-API connect() methods to be transparently managed by a
  13. SQLAlchemy connection pool.
  14. """
  15. import time
  16. import traceback
  17. import weakref
  18. from . import exc, log, event, interfaces, util
  19. from .util import queue as sqla_queue
  20. from .util import threading, memoized_property, \
  21. chop_traceback
  22. from collections import deque
  23. proxies = {}
  24. def manage(module, **params):
  25. r"""Return a proxy for a DB-API module that automatically
  26. pools connections.
  27. Given a DB-API 2.0 module and pool management parameters, returns
  28. a proxy for the module that will automatically pool connections,
  29. creating new connection pools for each distinct set of connection
  30. arguments sent to the decorated module's connect() function.
  31. :param module: a DB-API 2.0 database module
  32. :param poolclass: the class used by the pool module to provide
  33. pooling. Defaults to :class:`.QueuePool`.
  34. :param \**params: will be passed through to *poolclass*
  35. """
  36. try:
  37. return proxies[module]
  38. except KeyError:
  39. return proxies.setdefault(module, _DBProxy(module, **params))
  40. def clear_managers():
  41. """Remove all current DB-API 2.0 managers.
  42. All pools and connections are disposed.
  43. """
  44. for manager in proxies.values():
  45. manager.close()
  46. proxies.clear()
  47. reset_rollback = util.symbol('reset_rollback')
  48. reset_commit = util.symbol('reset_commit')
  49. reset_none = util.symbol('reset_none')
  50. class _ConnDialect(object):
  51. """partial implementation of :class:`.Dialect`
  52. which provides DBAPI connection methods.
  53. When a :class:`.Pool` is combined with an :class:`.Engine`,
  54. the :class:`.Engine` replaces this with its own
  55. :class:`.Dialect`.
  56. """
  57. def do_rollback(self, dbapi_connection):
  58. dbapi_connection.rollback()
  59. def do_commit(self, dbapi_connection):
  60. dbapi_connection.commit()
  61. def do_close(self, dbapi_connection):
  62. dbapi_connection.close()
  63. class Pool(log.Identified):
  64. """Abstract base class for connection pools."""
  65. _dialect = _ConnDialect()
  66. def __init__(self,
  67. creator, recycle=-1, echo=None,
  68. use_threadlocal=False,
  69. logging_name=None,
  70. reset_on_return=True,
  71. listeners=None,
  72. events=None,
  73. dialect=None,
  74. _dispatch=None):
  75. """
  76. Construct a Pool.
  77. :param creator: a callable function that returns a DB-API
  78. connection object. The function will be called with
  79. parameters.
  80. :param recycle: If set to non -1, number of seconds between
  81. connection recycling, which means upon checkout, if this
  82. timeout is surpassed the connection will be closed and
  83. replaced with a newly opened connection. Defaults to -1.
  84. :param logging_name: String identifier which will be used within
  85. the "name" field of logging records generated within the
  86. "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
  87. id.
  88. :param echo: If True, connections being pulled and retrieved
  89. from the pool will be logged to the standard output, as well
  90. as pool sizing information. Echoing can also be achieved by
  91. enabling logging for the "sqlalchemy.pool"
  92. namespace. Defaults to False.
  93. :param use_threadlocal: If set to True, repeated calls to
  94. :meth:`connect` within the same application thread will be
  95. guaranteed to return the same connection object, if one has
  96. already been retrieved from the pool and has not been
  97. returned yet. Offers a slight performance advantage at the
  98. cost of individual transactions by default. The
  99. :meth:`.Pool.unique_connection` method is provided to return
  100. a consistently unique connection to bypass this behavior
  101. when the flag is set.
  102. .. warning:: The :paramref:`.Pool.use_threadlocal` flag
  103. **does not affect the behavior** of :meth:`.Engine.connect`.
  104. :meth:`.Engine.connect` makes use of the
  105. :meth:`.Pool.unique_connection` method which **does not use thread
  106. local context**. To produce a :class:`.Connection` which refers
  107. to the :meth:`.Pool.connect` method, use
  108. :meth:`.Engine.contextual_connect`.
  109. Note that other SQLAlchemy connectivity systems such as
  110. :meth:`.Engine.execute` as well as the orm
  111. :class:`.Session` make use of
  112. :meth:`.Engine.contextual_connect` internally, so these functions
  113. are compatible with the :paramref:`.Pool.use_threadlocal` setting.
  114. .. seealso::
  115. :ref:`threadlocal_strategy` - contains detail on the
  116. "threadlocal" engine strategy, which provides a more comprehensive
  117. approach to "threadlocal" connectivity for the specific
  118. use case of using :class:`.Engine` and :class:`.Connection` objects
  119. directly.
  120. :param reset_on_return: Determine steps to take on
  121. connections as they are returned to the pool.
  122. reset_on_return can have any of these values:
  123. * ``"rollback"`` - call rollback() on the connection,
  124. to release locks and transaction resources.
  125. This is the default value. The vast majority
  126. of use cases should leave this value set.
  127. * ``True`` - same as 'rollback', this is here for
  128. backwards compatibility.
  129. * ``"commit"`` - call commit() on the connection,
  130. to release locks and transaction resources.
  131. A commit here may be desirable for databases that
  132. cache query plans if a commit is emitted,
  133. such as Microsoft SQL Server. However, this
  134. value is more dangerous than 'rollback' because
  135. any data changes present on the transaction
  136. are committed unconditionally.
  137. * ``None`` - don't do anything on the connection.
  138. This setting should only be made on a database
  139. that has no transaction support at all,
  140. namely MySQL MyISAM. By not doing anything,
  141. performance can be improved. This
  142. setting should **never be selected** for a
  143. database that supports transactions,
  144. as it will lead to deadlocks and stale
  145. state.
  146. * ``"none"`` - same as ``None``
  147. .. versionadded:: 0.9.10
  148. * ``False`` - same as None, this is here for
  149. backwards compatibility.
  150. .. versionchanged:: 0.7.6
  151. :paramref:`.Pool.reset_on_return` accepts ``"rollback"``
  152. and ``"commit"`` arguments.
  153. :param events: a list of 2-tuples, each of the form
  154. ``(callable, target)`` which will be passed to :func:`.event.listen`
  155. upon construction. Provided here so that event listeners
  156. can be assigned via :func:`.create_engine` before dialect-level
  157. listeners are applied.
  158. :param listeners: Deprecated. A list of
  159. :class:`~sqlalchemy.interfaces.PoolListener`-like objects or
  160. dictionaries of callables that receive events when DB-API
  161. connections are created, checked out and checked in to the
  162. pool. This has been superseded by
  163. :func:`~sqlalchemy.event.listen`.
  164. :param dialect: a :class:`.Dialect` that will handle the job
  165. of calling rollback(), close(), or commit() on DBAPI connections.
  166. If omitted, a built-in "stub" dialect is used. Applications that
  167. make use of :func:`~.create_engine` should not use this parameter
  168. as it is handled by the engine creation strategy.
  169. .. versionadded:: 1.1 - ``dialect`` is now a public parameter
  170. to the :class:`.Pool`.
  171. """
  172. if logging_name:
  173. self.logging_name = self._orig_logging_name = logging_name
  174. else:
  175. self._orig_logging_name = None
  176. log.instance_logger(self, echoflag=echo)
  177. self._threadconns = threading.local()
  178. self._creator = creator
  179. self._recycle = recycle
  180. self._invalidate_time = 0
  181. self._use_threadlocal = use_threadlocal
  182. if reset_on_return in ('rollback', True, reset_rollback):
  183. self._reset_on_return = reset_rollback
  184. elif reset_on_return in ('none', None, False, reset_none):
  185. self._reset_on_return = reset_none
  186. elif reset_on_return in ('commit', reset_commit):
  187. self._reset_on_return = reset_commit
  188. else:
  189. raise exc.ArgumentError(
  190. "Invalid value for 'reset_on_return': %r"
  191. % reset_on_return)
  192. self.echo = echo
  193. if _dispatch:
  194. self.dispatch._update(_dispatch, only_propagate=False)
  195. if dialect:
  196. self._dialect = dialect
  197. if events:
  198. for fn, target in events:
  199. event.listen(self, target, fn)
  200. if listeners:
  201. util.warn_deprecated(
  202. "The 'listeners' argument to Pool (and "
  203. "create_engine()) is deprecated. Use event.listen().")
  204. for l in listeners:
  205. self.add_listener(l)
  206. @property
  207. def _creator(self):
  208. return self.__dict__['_creator']
  209. @_creator.setter
  210. def _creator(self, creator):
  211. self.__dict__['_creator'] = creator
  212. self._invoke_creator = self._should_wrap_creator(creator)
  213. def _should_wrap_creator(self, creator):
  214. """Detect if creator accepts a single argument, or is sent
  215. as a legacy style no-arg function.
  216. """
  217. try:
  218. argspec = util.get_callable_argspec(self._creator, no_self=True)
  219. except TypeError:
  220. return lambda crec: creator()
  221. defaulted = argspec[3] is not None and len(argspec[3]) or 0
  222. positionals = len(argspec[0]) - defaulted
  223. # look for the exact arg signature that DefaultStrategy
  224. # sends us
  225. if (argspec[0], argspec[3]) == (['connection_record'], (None,)):
  226. return creator
  227. # or just a single positional
  228. elif positionals == 1:
  229. return creator
  230. # all other cases, just wrap and assume legacy "creator" callable
  231. # thing
  232. else:
  233. return lambda crec: creator()
  234. def _close_connection(self, connection):
  235. self.logger.debug("Closing connection %r", connection)
  236. try:
  237. self._dialect.do_close(connection)
  238. except Exception:
  239. self.logger.error("Exception closing connection %r",
  240. connection, exc_info=True)
  241. @util.deprecated(
  242. 2.7, "Pool.add_listener is deprecated. Use event.listen()")
  243. def add_listener(self, listener):
  244. """Add a :class:`.PoolListener`-like object to this pool.
  245. ``listener`` may be an object that implements some or all of
  246. PoolListener, or a dictionary of callables containing implementations
  247. of some or all of the named methods in PoolListener.
  248. """
  249. interfaces.PoolListener._adapt_listener(self, listener)
  250. def unique_connection(self):
  251. """Produce a DBAPI connection that is not referenced by any
  252. thread-local context.
  253. This method is equivalent to :meth:`.Pool.connect` when the
  254. :paramref:`.Pool.use_threadlocal` flag is not set to True.
  255. When :paramref:`.Pool.use_threadlocal` is True, the
  256. :meth:`.Pool.unique_connection` method provides a means of bypassing
  257. the threadlocal context.
  258. """
  259. return _ConnectionFairy._checkout(self)
  260. def _create_connection(self):
  261. """Called by subclasses to create a new ConnectionRecord."""
  262. return _ConnectionRecord(self)
  263. def _invalidate(self, connection, exception=None):
  264. """Mark all connections established within the generation
  265. of the given connection as invalidated.
  266. If this pool's last invalidate time is before when the given
  267. connection was created, update the timestamp til now. Otherwise,
  268. no action is performed.
  269. Connections with a start time prior to this pool's invalidation
  270. time will be recycled upon next checkout.
  271. """
  272. rec = getattr(connection, "_connection_record", None)
  273. if not rec or self._invalidate_time < rec.starttime:
  274. self._invalidate_time = time.time()
  275. if getattr(connection, 'is_valid', False):
  276. connection.invalidate(exception)
  277. def recreate(self):
  278. """Return a new :class:`.Pool`, of the same class as this one
  279. and configured with identical creation arguments.
  280. This method is used in conjunction with :meth:`dispose`
  281. to close out an entire :class:`.Pool` and create a new one in
  282. its place.
  283. """
  284. raise NotImplementedError()
  285. def dispose(self):
  286. """Dispose of this pool.
  287. This method leaves the possibility of checked-out connections
  288. remaining open, as it only affects connections that are
  289. idle in the pool.
  290. See also the :meth:`Pool.recreate` method.
  291. """
  292. raise NotImplementedError()
  293. def connect(self):
  294. """Return a DBAPI connection from the pool.
  295. The connection is instrumented such that when its
  296. ``close()`` method is called, the connection will be returned to
  297. the pool.
  298. """
  299. if not self._use_threadlocal:
  300. return _ConnectionFairy._checkout(self)
  301. try:
  302. rec = self._threadconns.current()
  303. except AttributeError:
  304. pass
  305. else:
  306. if rec is not None:
  307. return rec._checkout_existing()
  308. return _ConnectionFairy._checkout(self, self._threadconns)
  309. def _return_conn(self, record):
  310. """Given a _ConnectionRecord, return it to the :class:`.Pool`.
  311. This method is called when an instrumented DBAPI connection
  312. has its ``close()`` method called.
  313. """
  314. if self._use_threadlocal:
  315. try:
  316. del self._threadconns.current
  317. except AttributeError:
  318. pass
  319. self._do_return_conn(record)
  320. def _do_get(self):
  321. """Implementation for :meth:`get`, supplied by subclasses."""
  322. raise NotImplementedError()
  323. def _do_return_conn(self, conn):
  324. """Implementation for :meth:`return_conn`, supplied by subclasses."""
  325. raise NotImplementedError()
  326. def status(self):
  327. raise NotImplementedError()
  328. class _ConnectionRecord(object):
  329. """Internal object which maintains an individual DBAPI connection
  330. referenced by a :class:`.Pool`.
  331. The :class:`._ConnectionRecord` object always exists for any particular
  332. DBAPI connection whether or not that DBAPI connection has been
  333. "checked out". This is in contrast to the :class:`._ConnectionFairy`
  334. which is only a public facade to the DBAPI connection while it is checked
  335. out.
  336. A :class:`._ConnectionRecord` may exist for a span longer than that
  337. of a single DBAPI connection. For example, if the
  338. :meth:`._ConnectionRecord.invalidate`
  339. method is called, the DBAPI connection associated with this
  340. :class:`._ConnectionRecord`
  341. will be discarded, but the :class:`._ConnectionRecord` may be used again,
  342. in which case a new DBAPI connection is produced when the :class:`.Pool`
  343. next uses this record.
  344. The :class:`._ConnectionRecord` is delivered along with connection
  345. pool events, including :meth:`.PoolEvents.connect` and
  346. :meth:`.PoolEvents.checkout`, however :class:`._ConnectionRecord` still
  347. remains an internal object whose API and internals may change.
  348. .. seealso::
  349. :class:`._ConnectionFairy`
  350. """
  351. def __init__(self, pool, connect=True):
  352. self.__pool = pool
  353. if connect:
  354. self.__connect(first_connect_check=True)
  355. self.finalize_callback = deque()
  356. fairy_ref = None
  357. starttime = None
  358. connection = None
  359. """A reference to the actual DBAPI connection being tracked.
  360. May be ``None`` if this :class:`._ConnectionRecord` has been marked
  361. as invalidated; a new DBAPI connection may replace it if the owning
  362. pool calls upon this :class:`._ConnectionRecord` to reconnect.
  363. """
  364. _soft_invalidate_time = 0
  365. @util.memoized_property
  366. def info(self):
  367. """The ``.info`` dictionary associated with the DBAPI connection.
  368. This dictionary is shared among the :attr:`._ConnectionFairy.info`
  369. and :attr:`.Connection.info` accessors.
  370. .. note::
  371. The lifespan of this dictionary is linked to the
  372. DBAPI connection itself, meaning that it is **discarded** each time
  373. the DBAPI connection is closed and/or invalidated. The
  374. :attr:`._ConnectionRecord.record_info` dictionary remains
  375. persistent throughout the lifespan of the
  376. :class:`._ConnectionRecord` container.
  377. """
  378. return {}
  379. @util.memoized_property
  380. def record_info(self):
  381. """An "info' dictionary associated with the connection record
  382. itself.
  383. Unlike the :attr:`._ConnectionRecord.info` dictionary, which is linked
  384. to the lifespan of the DBAPI connection, this dictionary is linked
  385. to the lifespan of the :class:`._ConnectionRecord` container itself
  386. and will remain persisent throughout the life of the
  387. :class:`._ConnectionRecord`.
  388. .. versionadded:: 1.1
  389. """
  390. return {}
  391. @classmethod
  392. def checkout(cls, pool):
  393. rec = pool._do_get()
  394. try:
  395. dbapi_connection = rec.get_connection()
  396. except:
  397. with util.safe_reraise():
  398. rec.checkin()
  399. echo = pool._should_log_debug()
  400. fairy = _ConnectionFairy(dbapi_connection, rec, echo)
  401. rec.fairy_ref = weakref.ref(
  402. fairy,
  403. lambda ref: _finalize_fairy and
  404. _finalize_fairy(
  405. dbapi_connection,
  406. rec, pool, ref, echo)
  407. )
  408. _refs.add(rec)
  409. if echo:
  410. pool.logger.debug("Connection %r checked out from pool",
  411. dbapi_connection)
  412. return fairy
  413. def checkin(self):
  414. self.fairy_ref = None
  415. connection = self.connection
  416. pool = self.__pool
  417. while self.finalize_callback:
  418. finalizer = self.finalize_callback.pop()
  419. finalizer(connection)
  420. if pool.dispatch.checkin:
  421. pool.dispatch.checkin(connection, self)
  422. pool._return_conn(self)
  423. @property
  424. def in_use(self):
  425. return self.fairy_ref is not None
  426. @property
  427. def last_connect_time(self):
  428. return self.starttime
  429. def close(self):
  430. if self.connection is not None:
  431. self.__close()
  432. def invalidate(self, e=None, soft=False):
  433. """Invalidate the DBAPI connection held by this :class:`._ConnectionRecord`.
  434. This method is called for all connection invalidations, including
  435. when the :meth:`._ConnectionFairy.invalidate` or
  436. :meth:`.Connection.invalidate` methods are called, as well as when any
  437. so-called "automatic invalidation" condition occurs.
  438. :param e: an exception object indicating a reason for the invalidation.
  439. :param soft: if True, the connection isn't closed; instead, this
  440. connection will be recycled on next checkout.
  441. .. versionadded:: 1.0.3
  442. .. seealso::
  443. :ref:`pool_connection_invalidation`
  444. """
  445. # already invalidated
  446. if self.connection is None:
  447. return
  448. if soft:
  449. self.__pool.dispatch.soft_invalidate(self.connection, self, e)
  450. else:
  451. self.__pool.dispatch.invalidate(self.connection, self, e)
  452. if e is not None:
  453. self.__pool.logger.info(
  454. "%sInvalidate connection %r (reason: %s:%s)",
  455. "Soft " if soft else "",
  456. self.connection, e.__class__.__name__, e)
  457. else:
  458. self.__pool.logger.info(
  459. "%sInvalidate connection %r",
  460. "Soft " if soft else "",
  461. self.connection)
  462. if soft:
  463. self._soft_invalidate_time = time.time()
  464. else:
  465. self.__close()
  466. self.connection = None
  467. def get_connection(self):
  468. recycle = False
  469. if self.connection is None:
  470. self.info.clear()
  471. self.__connect()
  472. elif self.__pool._recycle > -1 and \
  473. time.time() - self.starttime > self.__pool._recycle:
  474. self.__pool.logger.info(
  475. "Connection %r exceeded timeout; recycling",
  476. self.connection)
  477. recycle = True
  478. elif self.__pool._invalidate_time > self.starttime:
  479. self.__pool.logger.info(
  480. "Connection %r invalidated due to pool invalidation; " +
  481. "recycling",
  482. self.connection
  483. )
  484. recycle = True
  485. elif self._soft_invalidate_time > self.starttime:
  486. self.__pool.logger.info(
  487. "Connection %r invalidated due to local soft invalidation; " +
  488. "recycling",
  489. self.connection
  490. )
  491. recycle = True
  492. if recycle:
  493. self.__close()
  494. self.info.clear()
  495. self.__connect()
  496. return self.connection
  497. def __close(self):
  498. self.finalize_callback.clear()
  499. if self.__pool.dispatch.close:
  500. self.__pool.dispatch.close(self.connection, self)
  501. self.__pool._close_connection(self.connection)
  502. self.connection = None
  503. def __connect(self, first_connect_check=False):
  504. pool = self.__pool
  505. # ensure any existing connection is removed, so that if
  506. # creator fails, this attribute stays None
  507. self.connection = None
  508. try:
  509. self.starttime = time.time()
  510. connection = pool._invoke_creator(self)
  511. pool.logger.debug("Created new connection %r", connection)
  512. self.connection = connection
  513. except Exception as e:
  514. pool.logger.debug("Error on connect(): %s", e)
  515. raise
  516. else:
  517. if first_connect_check:
  518. pool.dispatch.first_connect.\
  519. for_modify(pool.dispatch).\
  520. exec_once(self.connection, self)
  521. if pool.dispatch.connect:
  522. pool.dispatch.connect(self.connection, self)
  523. def _finalize_fairy(connection, connection_record,
  524. pool, ref, echo, fairy=None):
  525. """Cleanup for a :class:`._ConnectionFairy` whether or not it's already
  526. been garbage collected.
  527. """
  528. _refs.discard(connection_record)
  529. if ref is not None and \
  530. connection_record.fairy_ref is not ref:
  531. return
  532. if connection is not None:
  533. if connection_record and echo:
  534. pool.logger.debug("Connection %r being returned to pool",
  535. connection)
  536. try:
  537. fairy = fairy or _ConnectionFairy(
  538. connection, connection_record, echo)
  539. assert fairy.connection is connection
  540. fairy._reset(pool)
  541. # Immediately close detached instances
  542. if not connection_record:
  543. if pool.dispatch.close_detached:
  544. pool.dispatch.close_detached(connection)
  545. pool._close_connection(connection)
  546. except BaseException as e:
  547. pool.logger.error(
  548. "Exception during reset or similar", exc_info=True)
  549. if connection_record:
  550. connection_record.invalidate(e=e)
  551. if not isinstance(e, Exception):
  552. raise
  553. if connection_record:
  554. connection_record.checkin()
  555. _refs = set()
  556. class _ConnectionFairy(object):
  557. """Proxies a DBAPI connection and provides return-on-dereference
  558. support.
  559. This is an internal object used by the :class:`.Pool` implementation
  560. to provide context management to a DBAPI connection delivered by
  561. that :class:`.Pool`.
  562. The name "fairy" is inspired by the fact that the
  563. :class:`._ConnectionFairy` object's lifespan is transitory, as it lasts
  564. only for the length of a specific DBAPI connection being checked out from
  565. the pool, and additionally that as a transparent proxy, it is mostly
  566. invisible.
  567. .. seealso::
  568. :class:`._ConnectionRecord`
  569. """
  570. def __init__(self, dbapi_connection, connection_record, echo):
  571. self.connection = dbapi_connection
  572. self._connection_record = connection_record
  573. self._echo = echo
  574. connection = None
  575. """A reference to the actual DBAPI connection being tracked."""
  576. _connection_record = None
  577. """A reference to the :class:`._ConnectionRecord` object associated
  578. with the DBAPI connection.
  579. This is currently an internal accessor which is subject to change.
  580. """
  581. _reset_agent = None
  582. """Refer to an object with a ``.commit()`` and ``.rollback()`` method;
  583. if non-None, the "reset-on-return" feature will call upon this object
  584. rather than directly against the dialect-level do_rollback() and
  585. do_commit() methods.
  586. In practice, a :class:`.Connection` assigns a :class:`.Transaction` object
  587. to this variable when one is in scope so that the :class:`.Transaction`
  588. takes the job of committing or rolling back on return if
  589. :meth:`.Connection.close` is called while the :class:`.Transaction`
  590. still exists.
  591. This is essentially an "event handler" of sorts but is simplified as an
  592. instance variable both for performance/simplicity as well as that there
  593. can only be one "reset agent" at a time.
  594. """
  595. @classmethod
  596. def _checkout(cls, pool, threadconns=None, fairy=None):
  597. if not fairy:
  598. fairy = _ConnectionRecord.checkout(pool)
  599. fairy._pool = pool
  600. fairy._counter = 0
  601. if threadconns is not None:
  602. threadconns.current = weakref.ref(fairy)
  603. if fairy.connection is None:
  604. raise exc.InvalidRequestError("This connection is closed")
  605. fairy._counter += 1
  606. if not pool.dispatch.checkout or fairy._counter != 1:
  607. return fairy
  608. # Pool listeners can trigger a reconnection on checkout
  609. attempts = 2
  610. while attempts > 0:
  611. try:
  612. pool.dispatch.checkout(fairy.connection,
  613. fairy._connection_record,
  614. fairy)
  615. return fairy
  616. except exc.DisconnectionError as e:
  617. pool.logger.info(
  618. "Disconnection detected on checkout: %s", e)
  619. fairy._connection_record.invalidate(e)
  620. try:
  621. fairy.connection = \
  622. fairy._connection_record.get_connection()
  623. except:
  624. with util.safe_reraise():
  625. fairy._connection_record.checkin()
  626. attempts -= 1
  627. pool.logger.info("Reconnection attempts exhausted on checkout")
  628. fairy.invalidate()
  629. raise exc.InvalidRequestError("This connection is closed")
  630. def _checkout_existing(self):
  631. return _ConnectionFairy._checkout(self._pool, fairy=self)
  632. def _checkin(self):
  633. _finalize_fairy(self.connection, self._connection_record,
  634. self._pool, None, self._echo, fairy=self)
  635. self.connection = None
  636. self._connection_record = None
  637. _close = _checkin
  638. def _reset(self, pool):
  639. if pool.dispatch.reset:
  640. pool.dispatch.reset(self, self._connection_record)
  641. if pool._reset_on_return is reset_rollback:
  642. if self._echo:
  643. pool.logger.debug("Connection %s rollback-on-return%s",
  644. self.connection,
  645. ", via agent"
  646. if self._reset_agent else "")
  647. if self._reset_agent:
  648. self._reset_agent.rollback()
  649. else:
  650. pool._dialect.do_rollback(self)
  651. elif pool._reset_on_return is reset_commit:
  652. if self._echo:
  653. pool.logger.debug("Connection %s commit-on-return%s",
  654. self.connection,
  655. ", via agent"
  656. if self._reset_agent else "")
  657. if self._reset_agent:
  658. self._reset_agent.commit()
  659. else:
  660. pool._dialect.do_commit(self)
  661. @property
  662. def _logger(self):
  663. return self._pool.logger
  664. @property
  665. def is_valid(self):
  666. """Return True if this :class:`._ConnectionFairy` still refers
  667. to an active DBAPI connection."""
  668. return self.connection is not None
  669. @util.memoized_property
  670. def info(self):
  671. """Info dictionary associated with the underlying DBAPI connection
  672. referred to by this :class:`.ConnectionFairy`, allowing user-defined
  673. data to be associated with the connection.
  674. The data here will follow along with the DBAPI connection including
  675. after it is returned to the connection pool and used again
  676. in subsequent instances of :class:`._ConnectionFairy`. It is shared
  677. with the :attr:`._ConnectionRecord.info` and :attr:`.Connection.info`
  678. accessors.
  679. The dictionary associated with a particular DBAPI connection is
  680. discarded when the connection itself is discarded.
  681. """
  682. return self._connection_record.info
  683. @property
  684. def record_info(self):
  685. """Info dictionary associated with the :class:`._ConnectionRecord
  686. container referred to by this :class:`.ConnectionFairy`.
  687. Unlike the :attr:`._ConnectionFairy.info` dictionary, the lifespan
  688. of this dictionary is persistent across connections that are
  689. disconnected and/or invalidated within the lifespan of a
  690. :class:`._ConnectionRecord`.
  691. .. versionadded:: 1.1
  692. """
  693. if self._connection_record:
  694. return self._connection_record.record_info
  695. else:
  696. return None
  697. def invalidate(self, e=None, soft=False):
  698. """Mark this connection as invalidated.
  699. This method can be called directly, and is also called as a result
  700. of the :meth:`.Connection.invalidate` method. When invoked,
  701. the DBAPI connection is immediately closed and discarded from
  702. further use by the pool. The invalidation mechanism proceeds
  703. via the :meth:`._ConnectionRecord.invalidate` internal method.
  704. :param e: an exception object indicating a reason for the invalidation.
  705. :param soft: if True, the connection isn't closed; instead, this
  706. connection will be recycled on next checkout.
  707. .. versionadded:: 1.0.3
  708. .. seealso::
  709. :ref:`pool_connection_invalidation`
  710. """
  711. if self.connection is None:
  712. util.warn("Can't invalidate an already-closed connection.")
  713. return
  714. if self._connection_record:
  715. self._connection_record.invalidate(e=e, soft=soft)
  716. if not soft:
  717. self.connection = None
  718. self._checkin()
  719. def cursor(self, *args, **kwargs):
  720. """Return a new DBAPI cursor for the underlying connection.
  721. This method is a proxy for the ``connection.cursor()`` DBAPI
  722. method.
  723. """
  724. return self.connection.cursor(*args, **kwargs)
  725. def __getattr__(self, key):
  726. return getattr(self.connection, key)
  727. def detach(self):
  728. """Separate this connection from its Pool.
  729. This means that the connection will no longer be returned to the
  730. pool when closed, and will instead be literally closed. The
  731. containing ConnectionRecord is separated from the DB-API connection,
  732. and will create a new connection when next used.
  733. Note that any overall connection limiting constraints imposed by a
  734. Pool implementation may be violated after a detach, as the detached
  735. connection is removed from the pool's knowledge and control.
  736. """
  737. if self._connection_record is not None:
  738. rec = self._connection_record
  739. _refs.remove(rec)
  740. rec.fairy_ref = None
  741. rec.connection = None
  742. # TODO: should this be _return_conn?
  743. self._pool._do_return_conn(self._connection_record)
  744. self.info = self.info.copy()
  745. self._connection_record = None
  746. if self._pool.dispatch.detach:
  747. self._pool.dispatch.detach(self.connection, rec)
  748. def close(self):
  749. self._counter -= 1
  750. if self._counter == 0:
  751. self._checkin()
  752. class SingletonThreadPool(Pool):
  753. """A Pool that maintains one connection per thread.
  754. Maintains one connection per each thread, never moving a connection to a
  755. thread other than the one which it was created in.
  756. .. warning:: the :class:`.SingletonThreadPool` will call ``.close()``
  757. on arbitrary connections that exist beyond the size setting of
  758. ``pool_size``, e.g. if more unique **thread identities**
  759. than what ``pool_size`` states are used. This cleanup is
  760. non-deterministic and not sensitive to whether or not the connections
  761. linked to those thread identities are currently in use.
  762. :class:`.SingletonThreadPool` may be improved in a future release,
  763. however in its current status it is generally used only for test
  764. scenarios using a SQLite ``:memory:`` database and is not recommended
  765. for production use.
  766. Options are the same as those of :class:`.Pool`, as well as:
  767. :param pool_size: The number of threads in which to maintain connections
  768. at once. Defaults to five.
  769. :class:`.SingletonThreadPool` is used by the SQLite dialect
  770. automatically when a memory-based database is used.
  771. See :ref:`sqlite_toplevel`.
  772. """
  773. def __init__(self, creator, pool_size=5, **kw):
  774. kw['use_threadlocal'] = True
  775. Pool.__init__(self, creator, **kw)
  776. self._conn = threading.local()
  777. self._all_conns = set()
  778. self.size = pool_size
  779. def recreate(self):
  780. self.logger.info("Pool recreating")
  781. return self.__class__(self._creator,
  782. pool_size=self.size,
  783. recycle=self._recycle,
  784. echo=self.echo,
  785. logging_name=self._orig_logging_name,
  786. use_threadlocal=self._use_threadlocal,
  787. reset_on_return=self._reset_on_return,
  788. _dispatch=self.dispatch,
  789. dialect=self._dialect)
  790. def dispose(self):
  791. """Dispose of this pool."""
  792. for conn in self._all_conns:
  793. try:
  794. conn.close()
  795. except Exception:
  796. # pysqlite won't even let you close a conn from a thread
  797. # that didn't create it
  798. pass
  799. self._all_conns.clear()
  800. def _cleanup(self):
  801. while len(self._all_conns) >= self.size:
  802. c = self._all_conns.pop()
  803. c.close()
  804. def status(self):
  805. return "SingletonThreadPool id:%d size: %d" % \
  806. (id(self), len(self._all_conns))
  807. def _do_return_conn(self, conn):
  808. pass
  809. def _do_get(self):
  810. try:
  811. c = self._conn.current()
  812. if c:
  813. return c
  814. except AttributeError:
  815. pass
  816. c = self._create_connection()
  817. self._conn.current = weakref.ref(c)
  818. if len(self._all_conns) >= self.size:
  819. self._cleanup()
  820. self._all_conns.add(c)
  821. return c
  822. class QueuePool(Pool):
  823. """A :class:`.Pool` that imposes a limit on the number of open connections.
  824. :class:`.QueuePool` is the default pooling implementation used for
  825. all :class:`.Engine` objects, unless the SQLite dialect is in use.
  826. """
  827. def __init__(self, creator, pool_size=5, max_overflow=10, timeout=30,
  828. **kw):
  829. r"""
  830. Construct a QueuePool.
  831. :param creator: a callable function that returns a DB-API
  832. connection object, same as that of :paramref:`.Pool.creator`.
  833. :param pool_size: The size of the pool to be maintained,
  834. defaults to 5. This is the largest number of connections that
  835. will be kept persistently in the pool. Note that the pool
  836. begins with no connections; once this number of connections
  837. is requested, that number of connections will remain.
  838. ``pool_size`` can be set to 0 to indicate no size limit; to
  839. disable pooling, use a :class:`~sqlalchemy.pool.NullPool`
  840. instead.
  841. :param max_overflow: The maximum overflow size of the
  842. pool. When the number of checked-out connections reaches the
  843. size set in pool_size, additional connections will be
  844. returned up to this limit. When those additional connections
  845. are returned to the pool, they are disconnected and
  846. discarded. It follows then that the total number of
  847. simultaneous connections the pool will allow is pool_size +
  848. `max_overflow`, and the total number of "sleeping"
  849. connections the pool will allow is pool_size. `max_overflow`
  850. can be set to -1 to indicate no overflow limit; no limit
  851. will be placed on the total number of concurrent
  852. connections. Defaults to 10.
  853. :param timeout: The number of seconds to wait before giving up
  854. on returning a connection. Defaults to 30.
  855. :param \**kw: Other keyword arguments including
  856. :paramref:`.Pool.recycle`, :paramref:`.Pool.echo`,
  857. :paramref:`.Pool.reset_on_return` and others are passed to the
  858. :class:`.Pool` constructor.
  859. """
  860. Pool.__init__(self, creator, **kw)
  861. self._pool = sqla_queue.Queue(pool_size)
  862. self._overflow = 0 - pool_size
  863. self._max_overflow = max_overflow
  864. self._timeout = timeout
  865. self._overflow_lock = threading.Lock()
  866. def _do_return_conn(self, conn):
  867. try:
  868. self._pool.put(conn, False)
  869. except sqla_queue.Full:
  870. try:
  871. conn.close()
  872. finally:
  873. self._dec_overflow()
  874. def _do_get(self):
  875. use_overflow = self._max_overflow > -1
  876. try:
  877. wait = use_overflow and self._overflow >= self._max_overflow
  878. return self._pool.get(wait, self._timeout)
  879. except sqla_queue.Empty:
  880. if use_overflow and self._overflow >= self._max_overflow:
  881. if not wait:
  882. return self._do_get()
  883. else:
  884. raise exc.TimeoutError(
  885. "QueuePool limit of size %d overflow %d reached, "
  886. "connection timed out, timeout %d" %
  887. (self.size(), self.overflow(), self._timeout))
  888. if self._inc_overflow():
  889. try:
  890. return self._create_connection()
  891. except:
  892. with util.safe_reraise():
  893. self._dec_overflow()
  894. else:
  895. return self._do_get()
  896. def _inc_overflow(self):
  897. if self._max_overflow == -1:
  898. self._overflow += 1
  899. return True
  900. with self._overflow_lock:
  901. if self._overflow < self._max_overflow:
  902. self._overflow += 1
  903. return True
  904. else:
  905. return False
  906. def _dec_overflow(self):
  907. if self._max_overflow == -1:
  908. self._overflow -= 1
  909. return True
  910. with self._overflow_lock:
  911. self._overflow -= 1
  912. return True
  913. def recreate(self):
  914. self.logger.info("Pool recreating")
  915. return self.__class__(self._creator, pool_size=self._pool.maxsize,
  916. max_overflow=self._max_overflow,
  917. timeout=self._timeout,
  918. recycle=self._recycle, echo=self.echo,
  919. logging_name=self._orig_logging_name,
  920. use_threadlocal=self._use_threadlocal,
  921. reset_on_return=self._reset_on_return,
  922. _dispatch=self.dispatch,
  923. dialect=self._dialect)
  924. def dispose(self):
  925. while True:
  926. try:
  927. conn = self._pool.get(False)
  928. conn.close()
  929. except sqla_queue.Empty:
  930. break
  931. self._overflow = 0 - self.size()
  932. self.logger.info("Pool disposed. %s", self.status())
  933. def status(self):
  934. return "Pool size: %d Connections in pool: %d "\
  935. "Current Overflow: %d Current Checked out "\
  936. "connections: %d" % (self.size(),
  937. self.checkedin(),
  938. self.overflow(),
  939. self.checkedout())
  940. def size(self):
  941. return self._pool.maxsize
  942. def checkedin(self):
  943. return self._pool.qsize()
  944. def overflow(self):
  945. return self._overflow
  946. def checkedout(self):
  947. return self._pool.maxsize - self._pool.qsize() + self._overflow
  948. class NullPool(Pool):
  949. """A Pool which does not pool connections.
  950. Instead it literally opens and closes the underlying DB-API connection
  951. per each connection open/close.
  952. Reconnect-related functions such as ``recycle`` and connection
  953. invalidation are not supported by this Pool implementation, since
  954. no connections are held persistently.
  955. .. versionchanged:: 0.7
  956. :class:`.NullPool` is used by the SQlite dialect automatically
  957. when a file-based database is used. See :ref:`sqlite_toplevel`.
  958. """
  959. def status(self):
  960. return "NullPool"
  961. def _do_return_conn(self, conn):
  962. conn.close()
  963. def _do_get(self):
  964. return self._create_connection()
  965. def recreate(self):
  966. self.logger.info("Pool recreating")
  967. return self.__class__(self._creator,
  968. recycle=self._recycle,
  969. echo=self.echo,
  970. logging_name=self._orig_logging_name,
  971. use_threadlocal=self._use_threadlocal,
  972. reset_on_return=self._reset_on_return,
  973. _dispatch=self.dispatch,
  974. dialect=self._dialect)
  975. def dispose(self):
  976. pass
  977. class StaticPool(Pool):
  978. """A Pool of exactly one connection, used for all requests.
  979. Reconnect-related functions such as ``recycle`` and connection
  980. invalidation (which is also used to support auto-reconnect) are not
  981. currently supported by this Pool implementation but may be implemented
  982. in a future release.
  983. """
  984. @memoized_property
  985. def _conn(self):
  986. return self._creator()
  987. @memoized_property
  988. def connection(self):
  989. return _ConnectionRecord(self)
  990. def status(self):
  991. return "StaticPool"
  992. def dispose(self):
  993. if '_conn' in self.__dict__:
  994. self._conn.close()
  995. self._conn = None
  996. def recreate(self):
  997. self.logger.info("Pool recreating")
  998. return self.__class__(creator=self._creator,
  999. recycle=self._recycle,
  1000. use_threadlocal=self._use_threadlocal,
  1001. reset_on_return=self._reset_on_return,
  1002. echo=self.echo,
  1003. logging_name=self._orig_logging_name,
  1004. _dispatch=self.dispatch,
  1005. dialect=self._dialect)
  1006. def _create_connection(self):
  1007. return self._conn
  1008. def _do_return_conn(self, conn):
  1009. pass
  1010. def _do_get(self):
  1011. return self.connection
  1012. class AssertionPool(Pool):
  1013. """A :class:`.Pool` that allows at most one checked out connection at
  1014. any given time.
  1015. This will raise an exception if more than one connection is checked out
  1016. at a time. Useful for debugging code that is using more connections
  1017. than desired.
  1018. .. versionchanged:: 0.7
  1019. :class:`.AssertionPool` also logs a traceback of where
  1020. the original connection was checked out, and reports
  1021. this in the assertion error raised.
  1022. """
  1023. def __init__(self, *args, **kw):
  1024. self._conn = None
  1025. self._checked_out = False
  1026. self._store_traceback = kw.pop('store_traceback', True)
  1027. self._checkout_traceback = None
  1028. Pool.__init__(self, *args, **kw)
  1029. def status(self):
  1030. return "AssertionPool"
  1031. def _do_return_conn(self, conn):
  1032. if not self._checked_out:
  1033. raise AssertionError("connection is not checked out")
  1034. self._checked_out = False
  1035. assert conn is self._conn
  1036. def dispose(self):
  1037. self._checked_out = False
  1038. if self._conn:
  1039. self._conn.close()
  1040. def recreate(self):
  1041. self.logger.info("Pool recreating")
  1042. return self.__class__(self._creator, echo=self.echo,
  1043. logging_name=self._orig_logging_name,
  1044. _dispatch=self.dispatch,
  1045. dialect=self._dialect)
  1046. def _do_get(self):
  1047. if self._checked_out:
  1048. if self._checkout_traceback:
  1049. suffix = ' at:\n%s' % ''.join(
  1050. chop_traceback(self._checkout_traceback))
  1051. else:
  1052. suffix = ''
  1053. raise AssertionError("connection is already checked out" + suffix)
  1054. if not self._conn:
  1055. self._conn = self._create_connection()
  1056. self._checked_out = True
  1057. if self._store_traceback:
  1058. self._checkout_traceback = traceback.format_stack()
  1059. return self._conn
  1060. class _DBProxy(object):
  1061. """Layers connection pooling behavior on top of a standard DB-API module.
  1062. Proxies a DB-API 2.0 connect() call to a connection pool keyed to the
  1063. specific connect parameters. Other functions and attributes are delegated
  1064. to the underlying DB-API module.
  1065. """
  1066. def __init__(self, module, poolclass=QueuePool, **kw):
  1067. """Initializes a new proxy.
  1068. module
  1069. a DB-API 2.0 module
  1070. poolclass
  1071. a Pool class, defaulting to QueuePool
  1072. Other parameters are sent to the Pool object's constructor.
  1073. """
  1074. self.module = module
  1075. self.kw = kw
  1076. self.poolclass = poolclass
  1077. self.pools = {}
  1078. self._create_pool_mutex = threading.Lock()
  1079. def close(self):
  1080. for key in list(self.pools):
  1081. del self.pools[key]
  1082. def __del__(self):
  1083. self.close()
  1084. def __getattr__(self, key):
  1085. return getattr(self.module, key)
  1086. def get_pool(self, *args, **kw):
  1087. key = self._serialize(*args, **kw)
  1088. try:
  1089. return self.pools[key]
  1090. except KeyError:
  1091. self._create_pool_mutex.acquire()
  1092. try:
  1093. if key not in self.pools:
  1094. kw.pop('sa_pool_key', None)
  1095. pool = self.poolclass(
  1096. lambda: self.module.connect(*args, **kw), **self.kw)
  1097. self.pools[key] = pool
  1098. return pool
  1099. else:
  1100. return self.pools[key]
  1101. finally:
  1102. self._create_pool_mutex.release()
  1103. def connect(self, *args, **kw):
  1104. """Activate a connection to the database.
  1105. Connect to the database using this DBProxy's module and the given
  1106. connect arguments. If the arguments match an existing pool, the
  1107. connection will be returned from the pool's current thread-local
  1108. connection instance, or if there is no thread-local connection
  1109. instance it will be checked out from the set of pooled connections.
  1110. If the pool has no available connections and allows new connections
  1111. to be created, a new database connection will be made.
  1112. """
  1113. return self.get_pool(*args, **kw).connect()
  1114. def dispose(self, *args, **kw):
  1115. """Dispose the pool referenced by the given connect arguments."""
  1116. key = self._serialize(*args, **kw)
  1117. try:
  1118. del self.pools[key]
  1119. except KeyError:
  1120. pass
  1121. def _serialize(self, *args, **kw):
  1122. if "sa_pool_key" in kw:
  1123. return kw['sa_pool_key']
  1124. return tuple(
  1125. list(args) +
  1126. [(k, kw[k]) for k in sorted(kw)]
  1127. )