o znhΊ@sdZddlmZddlZddlZddlmZddlmZddlmZddlm Z dd lm Z dd l m Z e d Z e d Ze d ZGdddeZGddde jZGdddeZ dddZeZGdddeZdS)z'Base constructs for connection pools. )dequeN)event)exc) interfaces)log)util) threadingreset_rollback reset_commit reset_nonec@s0eZdZdZddZddZddZdd Zd S) _ConnDialectzpartial implementation of :class:`.Dialect` which provides DBAPI connection methods. When a :class:`.Pool` is combined with an :class:`.Engine`, the :class:`.Engine` replaces this with its own :class:`.Dialect`. cC |dSN)rollbackselfdbapi_connectionr?/usr/local/lib/python3.10/dist-packages/sqlalchemy/pool/base.py do_rollback) z_ConnDialect.do_rollbackcCrr)commitrrrr do_commit,rz_ConnDialect.do_commitcCrr)closerrrrdo_close/rz_ConnDialect.do_closecCstd)NzJThe ping feature requires that a dialect is passed to the connection pool.NotImplementedErrorrrrrdo_ping2sz_ConnDialect.do_pingN)__name__ __module__ __qualname____doc__rrrrrrrrr s   r c@seZdZdZeZejddd          d*d d Ze d d Z e j d d Z ddZ ddZ eddddZddZddZd+ddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)ZdS),Poolz)Abstract base class for connection pools.)z1.3zfThe :paramref:`.Pool.use_threadlocal` parameter is deprecated and will be removed in a future release.)0.7z:class:`.PoolListener` is deprecated in favor of the :class:`.PoolEvents` listener interface. The :paramref:`.Pool.listeners` parameter will be removed in a future release.)use_threadlocal listenersNFTc Cs|r ||_|_nd|_tj||dt|_||_||_d|_ ||_ | |_ t j j|tddgtgdtdgidd d |_||_| rJ|jj| d d | rO| |_|r_|D] \} } t|| | qS|rk|D] }||qcdSdS) a Construct a Pool. :param creator: a callable function that returns a DB-API connection object. The function will be called with parameters. :param recycle: If set to a value other than -1, number of seconds between connection recycling, which means upon checkout, if this timeout is surpassed the connection will be closed and replaced with a newly opened connection. Defaults to -1. :param logging_name: String identifier which will be used within the "name" field of logging records generated within the "sqlalchemy.pool" logger. Defaults to a hexstring of the object's id. :param echo: if True, the connection pool will log informational output such as when connections are invalidated as well as when connections are recycled to the default log handler, which defaults to ``sys.stdout`` for output.. If set to the string ``"debug"``, the logging will include pool checkouts and checkins. The :paramref:`.Pool.echo` parameter can also be set from the :func:`.create_engine` call by using the :paramref:`.create_engine.echo_pool` parameter. .. seealso:: :ref:`dbengine_logging` - further detail on how to configure logging. :param use_threadlocal: If set to True, repeated calls to :meth:`connect` within the same application thread will be guaranteed to return the same connection object that is already checked out. This is a legacy use case and the flag has no effect when using the pool with a :class:`.Engine` object. :param reset_on_return: Determine steps to take on connections as they are returned to the pool. reset_on_return can have any of these values: * ``"rollback"`` - call rollback() on the connection, to release locks and transaction resources. This is the default value. The vast majority of use cases should leave this value set. * ``True`` - same as 'rollback', this is here for backwards compatibility. * ``"commit"`` - call commit() on the connection, to release locks and transaction resources. A commit here may be desirable for databases that cache query plans if a commit is emitted, such as Microsoft SQL Server. However, this value is more dangerous than 'rollback' because any data changes present on the transaction are committed unconditionally. * ``None`` - don't do anything on the connection. This setting should generally only be made on a database that has no transaction support at all, namely MySQL MyISAM; when used on this backend, performance can be improved as the "rollback" call is still expensive on MySQL. It is **strongly recommended** that this setting not be used for transaction-supporting databases in conjunction with a persistent pool such as :class:`.QueuePool`, as it opens the possibility for connections still in a transaction to be idle in the pool. The setting may be appropriate in the case of :class:`.NullPool` or special circumstances where the connection pool in use is not being used to maintain connection lifecycle. * ``False`` - same as None, this is here for backwards compatibility. :param events: a list of 2-tuples, each of the form ``(callable, target)`` which will be passed to :func:`.event.listen` upon construction. Provided here so that event listeners can be assigned via :func:`.create_engine` before dialect-level listeners are applied. :param listeners: A list of :class:`.PoolListener`-like objects or dictionaries of callables that receive events when DB-API connections are created, checked out and checked in to the pool. :param dialect: a :class:`.Dialect` that will handle the job of calling rollback(), close(), or commit() on DBAPI connections. If omitted, a built-in "stub" dialect is used. Applications that make use of :func:`~.create_engine` should not use this parameter as it is handled by the engine creation strategy. .. versionadded:: 1.1 - ``dialect`` is now a public parameter to the :class:`.Pool`. :param pre_ping: if True, the pool will emit a "ping" (typically "SELECT 1", but is dialect-specific) on the connection upon checkout, to test if the connection is alive or not. If not, the connection is transparently re-connected and upon success, all other pooled connections established prior to that timestamp are invalidated. Requires that a dialect is passed as well to interpret the disconnection error. .. versionadded:: 1.2 N)echoflagrrT)noneNFrreset_on_returnF)resolve_symbol_names)only_propagate) logging_name_orig_logging_namerinstance_loggerr local _threadconns_creator_recycle_invalidate_time_use_threadlocal _pre_pingrsymbolparse_user_argumentr r r _reset_on_returnechodispatch_update_dialectrlisten add_listener)rcreatorrecycler:r%r-r*r&eventsdialectpre_ping _dispatchfntargetlrrr__init__?sB    z Pool.__init__cCs |jdSNr2)__dict__rrrrr2 z Pool._creatorcCs||jd<|||_dSrJ)rK_should_wrap_creator_invoke_creator)rr@rrrr2s csz tj|jdd}WntyfddYSw|ddur&t|dp'd}t|d|}|d|dfdgd fkr?S|d krESfd dS) zlDetect if creator accepts a single argument, or is sent as a legacy style no-arg function. T)no_selfcSrrcrecr@rrz+Pool._should_wrap_creator..Nrconnection_recordrcrQrrrRrTrrrUrV)rget_callable_argspecr2 TypeErrorlen)rr@argspec defaulted positionalsrrTrrNs  zPool._should_wrap_creatorcCsH|jd|z |j|WdSty#|jjd|ddYdSw)NzClosing connection %rzException closing connection %rTexc_info)loggerdebugr=r Exceptionerror)r connectionrrr_close_connection s  zPool._close_connectionr$zThe :meth:`.Pool.add_listener` method is deprecated and will be removed in a future release. Please use the :class:`.PoolEvents` listener interface.cCstj||dS)aAdd a :class:`.PoolListener`-like object to this pool. ``listener`` may be an object that implements some or all of PoolListener, or a dictionary of callables containing implementations of some or all of the named methods in PoolListener. N)r PoolListener_adapt_listener)rlistenerrrrr?szPool.add_listenercCs t|S)aProduce a DBAPI connection that is not referenced by any thread-local context. This method is equivalent to :meth:`.Pool.connect` when the :paramref:`.Pool.use_threadlocal` flag is not set to True. When :paramref:`.Pool.use_threadlocal` is True, the :meth:`.Pool.unique_connection` method provides a means of bypassing the threadlocal context. )_ConnectionFairy _checkoutrLrrrunique_connection$s zPool.unique_connectioncCst|S)z6Called by subclasses to create a new ConnectionRecord.)_ConnectionRecordrLrrr_create_connection1szPool._create_connectioncCsLt|dd}|r|j|jkrt|_|r"t|ddr$||dSdSdS)aMark all connections established within the generation of the given connection as invalidated. If this pool's last invalidate time is before when the given connection was created, update the timestamp til now. Otherwise, no action is performed. Connections with a start time prior to this pool's invalidation time will be recycled upon next checkout. _connection_recordNis_validF)getattrr4 starttimetime invalidate)rrf exception_checkinrecrrr _invalidate6s  zPool._invalidatecCt)aReturn a new :class:`.Pool`, of the same class as this one and configured with identical creation arguments. This method is used in conjunction with :meth:`dispose` to close out an entire :class:`.Pool` and create a new one in its place. rrLrrrrecreateGs z Pool.recreatecCrz)zDispose of this pool. This method leaves the possibility of checked-out connections remaining open, as it only affects connections that are idle in the pool. .. seealso:: :meth:`Pool.recreate` rrLrrrdisposeSs z Pool.disposecCsP|jst|Sz|j}Wn tyYn w|dur!|St||jS)zReturn a DBAPI connection from the pool. The connection is instrumented such that when its ``close()`` method is called, the connection will be returned to the pool. N)r5rkrlr1currentAttributeError_checkout_existingrrxrrrconnectbs  z Pool.connectcCs2|jrz|j`Wn tyYnw||dS)zGiven a _ConnectionRecord, return it to the :class:`.Pool`. This method is called when an instrumented DBAPI connection has its ``close()`` method called. N)r5r1r}r~_do_return_conn)rrecordrrr _return_connws  zPool._return_conncCrz)z7Implementation for :meth:`get`, supplied by subclasses.rrLrrr_do_getz Pool._do_getcCrz)z?Implementation for :meth:`return_conn`, supplied by subclasses.r)rconnrrrrrzPool._do_return_conncCrzrrrLrrrstatussz Pool.status) r'NFNTNNNFN)NT)rr r!r"r r=rdeprecated_paramsrIpropertyr2setterrNrg deprecatedr?rmroryr{r|rrrrrrrrrr#9sP         r#c@seZdZdZd ddZdZdZdZ dZe j ddZ e j d d Z e d d Zd dZd!ddZeddZeddZddZd"ddZddZddZd!ddZdS)#rnaInternal object which maintains an individual DBAPI connection referenced by a :class:`.Pool`. The :class:`._ConnectionRecord` object always exists for any particular DBAPI connection whether or not that DBAPI connection has been "checked out". This is in contrast to the :class:`._ConnectionFairy` which is only a public facade to the DBAPI connection while it is checked out. A :class:`._ConnectionRecord` may exist for a span longer than that of a single DBAPI connection. For example, if the :meth:`._ConnectionRecord.invalidate` method is called, the DBAPI connection associated with this :class:`._ConnectionRecord` will be discarded, but the :class:`._ConnectionRecord` may be used again, in which case a new DBAPI connection is produced when the :class:`.Pool` next uses this record. The :class:`._ConnectionRecord` is delivered along with connection pool events, including :meth:`.PoolEvents.connect` and :meth:`.PoolEvents.checkout`, however :class:`._ConnectionRecord` still remains an internal object whose API and internals may change. .. seealso:: :class:`._ConnectionFairy` TcCs"||_|r |jddt|_dS)NT)first_connect_check)_ConnectionRecord__pool_ConnectionRecord__connectrfinalize_callback)rpoolrrrrrIs  z_ConnectionRecord.__init__NrcCiS)aYThe ``.info`` dictionary associated with the DBAPI connection. This dictionary is shared among the :attr:`._ConnectionFairy.info` and :attr:`.Connection.info` accessors. .. note:: The lifespan of this dictionary is linked to the DBAPI connection itself, meaning that it is **discarded** each time the DBAPI connection is closed and/or invalidated. The :attr:`._ConnectionRecord.record_info` dictionary remains persistent throughout the lifespan of the :class:`._ConnectionRecord` container. rrLrrrinfosz_ConnectionRecord.infocCr)aAn "info' dictionary associated with the connection record itself. Unlike the :attr:`._ConnectionRecord.info` dictionary, which is linked to the lifespan of the DBAPI connection, this dictionary is linked to the lifespan of the :class:`._ConnectionRecord` container itself and will remain persistent throughout the life of the :class:`._ConnectionRecord`. .. versionadded:: 1.1 rrLrrr record_infosz_ConnectionRecord.record_infoc sz}Wn+ty5}zt |Wdn1s&wYWYd}~nd}~wwt|}t |fdd_ t r[j d||S)Ncsto td|Sr)_finalize_fairy)refr:rrxrrrUsz,_ConnectionRecord.checkout..z#Connection %r checked out from pool)rget_connectionrdr safe_reraise_checkin_failed_should_log_debugrkweakrefr fairy_ref_refsaddrbrc)clsrrerrfairyrrrcheckouts*     z_ConnectionRecord.checkoutcCs|j|d|jdddS)NeT) _no_fairy_ref)rucheckin)rrrrrrs z!_ConnectionRecord._checkin_failedFcCst|jdur|std|dSd|_|j}|j}|jr(|j}|||js|jjr3|j||| |dS)NzDouble checkin attempted on %s) rrwarnrfrrpopr;rr)rrrfr finalizerrrrrs z_ConnectionRecord.checkincCs |jduSr)rrLrrrin_userMz_ConnectionRecord.in_usecCs|jSr)rsrLrrrlast_connect_timesz#_ConnectionRecord.last_connect_timecCs|jdur |dSdSr)rf_ConnectionRecord__closerLrrrrs  z_ConnectionRecord.closecCs|jdurdS|r|jj|j||n |jj|j|||dur5|jjd|r+dnd|j|jj|n|jjd|r>dnd|j|rLt |_ dS| d|_dS)aInvalidate the DBAPI connection held by this :class:`._ConnectionRecord`. This method is called for all connection invalidations, including when the :meth:`._ConnectionFairy.invalidate` or :meth:`.Connection.invalidate` methods are called, as well as when any so-called "automatic invalidation" condition occurs. :param e: an exception object indicating a reason for the invalidation. :param soft: if True, the connection isn't closed; instead, this connection will be recycled on next checkout. .. versionadded:: 1.0.3 .. seealso:: :ref:`pool_connection_invalidation` Nz*%sInvalidate connection %r (reason: %s:%s)zSoft z%sInvalidate connection %r) rfrr;soft_invalidaterurbr __class__rrt_soft_invalidate_timerrrsoftrrrrus,    z_ConnectionRecord.invalidatecCsd}|jdur|j|nA|jjdkr.t|j|jjkr.|jjd|jd}n$|jj |jkrA|jjd|jd}n|j |jkrR|jjd|jd}|ra| |j||jS)NFr'z)Connection %r exceeded timeout; recyclingTz=Connection %r invalidated due to pool invalidation; recyclingzCConnection %r invalidated due to local soft invalidation; recycling) rfrclearrrr3rtrsrbr4rr)rrArrrrMs6      z _ConnectionRecord.get_connectioncCs>|j|jjjr|jj|j||j|jd|_dSr)rrrr;rrfrgrLrrr__close}s   z_ConnectionRecord.__closec Cs|j}d|_zt|_||}|jd|||_Wnty0}z|jd|d}~ww|r@|jj |j |j||jj rN|j |j|dSdS)NzCreated new connection %rzError on connect(): %s) rrfrtrsrOrbrcrdr; first_connect for_modifyexec_once_unless_exceptionr)rrrrfrrrr __connects(    z_ConnectionRecord.__connect)T)FNF)rr r!r"rIrrsrfrrmemoized_propertyrr classmethodrrrrrrrrurrrrrrrrns2        /0rnc Cst||dur|j|urdS|dusJ|j}|durx|r(|r(|jd|z'|p0t|||}|j|us8J|||sN|jj rI|j || |Wn(t yw}z|jj ddd|rg|j |dt|tsmWYd}~nd}~ww|r|jdur|dSdSdS)zfCleanup for a :class:`._ConnectionFairy` whether or not it's already been garbage collected. Nz$Connection %r being returned to poolz!Exception during reset or similarTr`r)rdiscardrrfrbrcrk_resetr;close_detachedrg BaseExceptionreru isinstancerdr)rfrXrrr:rrrrrrsH          rc@seZdZdZddZdZ dZ dZ ed ddZ ddZ d d Z e Z d d Z ed dZeddZejddZeddZd!ddZddZddZddZddZdS)"rkaXProxies a DBAPI connection and provides return-on-dereference support. This is an internal object used by the :class:`.Pool` implementation to provide context management to a DBAPI connection delivered by that :class:`.Pool`. The name "fairy" is inspired by the fact that the :class:`._ConnectionFairy` object's lifespan is transitory, as it lasts only for the length of a specific DBAPI connection being checked out from the pool, and additionally that as a transparent proxy, it is mostly invisible. .. seealso:: :class:`._ConnectionRecord` cCs||_||_||_dSr)rfrp_echo)rrrXr:rrrrIs z_ConnectionFairy.__init__NcCs|st|}||_d|_|durt||_|jdur!t d|jd7_|j js/|j r4|jdkr6|Sd}|dkrz3|j rc|j rK|j d|j|j|j}|sc|j r_|j d|jt|j |j|j||WStjy}zg|jr|j d||j||j||dd n|j d |j||j|z|j|_Wn,ty}z t|j|Wdn1swYWYd}~nd}~ww|d8}WYd}~nd}~ww|dks<|j d |t d) NrzThis connection is closedrYrzPool pre-ping on connection %sz;Pool pre-ping on connection %s failed, will invalidate poolzoDisconnection detected on checkout, invalidating all pooled connections prior to current timestamp (reason: %r)F)rwzVDisconnection detected on checkout, invalidating individual connection %s (reason: %r)z+Reconnection attempts exhausted on checkout)rnr_pool_counterrrr}rfrInvalidRequestErrorr;r6rrbrcr=rInvalidatePoolErrorrpDisconnectionErrorinvalidate_poolrruryrrdrrr)rr threadconnsrattemptsresultrrrrrrls          2 z_ConnectionFairy._checkoutcCstj|j|dSN)r)rkrlrrLrrrrRsz#_ConnectionFairy._checkout_existingcCs,t|j|j|jd|j|dd|_d|_dSr)rrfrprrrLrrrrwUs z_ConnectionFairy._checkincCs|jjr |j||j|jtur4|jr"|jd|j|j rdnd|j r,|j dS|j |dS|jt ur\|jrJ|jd|j|j rGdnd|j rT|j dS|j |dSdS)Nz"Connection %s rollback-on-return%sz , via agentrz Connection %s commit-on-return%s)r;resetrpr9r rrbrcrf _reset_agentrr=rr rr)rrrrrrcs.    z_ConnectionFairy._resetcC|jjSr)rrbrLrrr_logger}sz_ConnectionFairy._loggercCs |jduS)zbReturn True if this :class:`._ConnectionFairy` still refers to an active DBAPI connection.N)rfrLrrrrqs z_ConnectionFairy.is_validcCr)aInfo dictionary associated with the underlying DBAPI connection referred to by this :class:`.ConnectionFairy`, allowing user-defined data to be associated with the connection. The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of :class:`._ConnectionFairy`. It is shared with the :attr:`._ConnectionRecord.info` and :attr:`.Connection.info` accessors. The dictionary associated with a particular DBAPI connection is discarded when the connection itself is discarded. )rprrLrrrrsz_ConnectionFairy.infocCs|jr|jjSdS)aInfo dictionary associated with the :class:`._ConnectionRecord container referred to by this :class:`.ConnectionFairy`. Unlike the :attr:`._ConnectionFairy.info` dictionary, the lifespan of this dictionary is persistent across connections that are disconnected and/or invalidated within the lifespan of a :class:`._ConnectionRecord`. .. versionadded:: 1.1 N)rprrLrrrrs z_ConnectionFairy.record_infoFcCsH|jdur tddS|jr|jj||d|s"d|_|dSdS)aMark this connection as invalidated. This method can be called directly, and is also called as a result of the :meth:`.Connection.invalidate` method. When invoked, the DBAPI connection is immediately closed and discarded from further use by the pool. The invalidation mechanism proceeds via the :meth:`._ConnectionRecord.invalidate` internal method. :param e: an exception object indicating a reason for the invalidation. :param soft: if True, the connection isn't closed; instead, this connection will be recycled on next checkout. .. versionadded:: 1.0.3 .. seealso:: :ref:`pool_connection_invalidation` Nz.Can't invalidate an already-closed connection.)rr)rfrrrprurwrrrrrus   z_ConnectionFairy.invalidatecOs|jj|i|S)zReturn a new DBAPI cursor for the underlying connection. This method is a proxy for the ``connection.cursor()`` DBAPI method. )rfcursor)rargskwargsrrrrsz_ConnectionFairy.cursorcCs t|j|Sr)rrrf)rkeyrrr __getattr__rz_ConnectionFairy.__getattr__cCsn|jdur3|j}t|d|_d|_|j|j|j|_d|_|jj j r5|jj |j|dSdSdS)a"Separate this connection from its Pool. This means that the connection will no longer be returned to the pool when closed, and will instead be literally closed. The containing ConnectionRecord is separated from the DB-API connection, and will create a new connection when next used. Note that any overall connection limiting constraints imposed by a Pool implementation may be violated after a detach, as the detached connection is removed from the pool's knowledge and control. N) rprremoverrfrrrcopyr;detachrrrrrs     z_ConnectionFairy.detachcCs(|jd8_|jdkr|dSdS)NrYr)rrwrLrrrrs  z_ConnectionFairy.close)NNr)rr r!r"rIrfrprrrlrrw_closerrrrqrrrrrurrrrrrrrrks8 O        rkr)r" collectionsrrtrrrrrrrr r7r r r objectr Identifiedr#rnrsetrrkrrrrs0          \ .