U a2@sdZddlmZddlZddlZddlmZddlmZddlmZddlm Z e d Z e d Z e d Z Gd d d eZGdddeZGdddejZGdddeZdddZiZGdddeZdS)z'Base constructs for connection pools. )dequeN)event)exc)log)utilreset_rollback reset_commit reset_nonec@s4eZdZdZdZddZddZddZd d Zd S) _ConnDialectzpartial implementation of :class:`.Dialect` which provides DBAPI connection methods. When a :class:`_pool.Pool` is combined with an :class:`_engine.Engine`, the :class:`_engine.Engine` replaces this with its own :class:`.Dialect`. FcCs |dSN)rollbackselfdbapi_connectionrUC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\pool\base.py do_rollback(sz_ConnDialect.do_rollbackcCs |dSr )commitrrrr do_commit+sz_ConnDialect.do_commitcCs |dSr )closerrrrdo_close.sz_ConnDialect.do_closecCs tddS)NzJThe ping feature requires that a dialect is passed to the connection pool.NotImplementedErrorrrrrdo_ping1sz_ConnDialect.do_pingN) __name__ __module__ __qualname____doc__is_asyncrrrrrrrrr s  r c@seZdZdZdS)_AsyncConnDialectTN)rrrrrrrrr 8sr c@seZdZdZeZd#ddZejdd Z e d d Z e j d d Z d dZ ddZddZd$ddZddZddZddZddZddZdd Zd!d"ZdS)%Poolz)Abstract base class for connection pools.NTFc Cs|r||_|_nd|_tj||d||_||_d|_||_tj j |t ddgt dddgt dgid dd |_||_| r|jj| dd |r||_|r|D]\} } t|| | qdS) 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.Pool.echo` parameter can also be set from the :func:`_sa.create_engine` call by using the :paramref:`_sa.create_engine.echo_pool` parameter. .. seealso:: :ref:`dbengine_logging` - further detail on how to configure logging. :param reset_on_return: Determine steps to take on connections as they are returned to the pool, which were not otherwise handled by a :class:`_engine.Connection`. 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 is only appropriate if the database / DBAPI works in pure "autocommit" mode at all times, or if the application uses the :class:`_engine.Engine` with consistent connectivity patterns. See the section :ref:`pool_reset_on_return` for more details. * ``False`` - same as None, this is here for backwards compatibility. .. seealso:: :ref:`pool_reset_on_return` :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:`_sa.create_engine` before dialect-level listeners are applied. :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:`_sa.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.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)Zechoflagrr TnoneFrreset_on_return)Zresolve_symbol_names)Zonly_propagate) logging_nameZ_orig_logging_namerZinstance_logger_creator_recycle_invalidate_time _pre_pingrsymbolZparse_user_argumentrr r _reset_on_returnechodispatch_update_dialectrlisten) rcreatorrecycler,r%r$eventsdialectZpre_ping _dispatchfntargetrrr__init__Bs8h  z Pool.__init__cCs|jjSr )r/rrrrr _is_asyncioszPool._is_asynciocCs |jdSNr&)__dict__r9rrrr&sz Pool._creatorcCs||jd<|||_dSr;)r<_should_wrap_creator_invoke_creator)rr1rrrr&s csztj|jdd}Wn tk r4fddYSX|ddk rNt|dpPd}t|d|}|d|dfdgd fkrS|d krSfd dSdS) zlDetect if creator accepts a single argument, or is sent as a legacy style no-arg function. T)Zno_selfcsSr rZcrecr1rrz+Pool._should_wrap_creator..Nrconnection_recordr csSr rr?r@rrrArB)rZget_callable_argspecr& TypeErrorlen)rr1ZargspecZ defaultedZ positionalsrr@rr=szPool._should_wrap_creatorcCsJ|jd|z|j|Wn&tk rD|jjd|ddYnXdS)NzClosing connection %rzException closing connection %rTexc_info)loggerdebugr/r Exceptionerror)r connectionrrr_close_connectionszPool._close_connectioncCst|S)z6Called by subclasses to create a new ConnectionRecord.)_ConnectionRecordr9rrr_create_connectionszPool._create_connectioncCsDt|dd}|r|j|jkr&t|_|r@t|ddr@||dS)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)getattrr( starttimetime invalidate)rrN exception_checkinrecrrr _invalidates  zPool._invalidatecCs tdS)a"Return a new :class:`_pool.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.Pool` and create a new one in its place. Nrr9rrrrecreates z Pool.recreatecCs tdS)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` Nrr9rrrdisposes z Pool.disposecCs t|S)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. )_ConnectionFairy _checkoutr9rrrconnect+sz Pool.connectcCs||dS)zGiven a _ConnectionRecord, return it to the :class:`_pool.Pool`. This method is called when an instrumented DBAPI connection has its ``close()`` method called. N)_do_return_conn)rrecordrrr _return_conn5szPool._return_conncCs tdS)z7Implementation for :meth:`get`, supplied by subclasses.Nrr9rrr_do_get>sz Pool._do_getcCs tdS)z?Implementation for :meth:`return_conn`, supplied by subclasses.Nr)rconnrrrraCszPool._do_return_conncCs tdSr rr9rrrstatusHsz Pool.status)r"NNTNNFN)NT)rrrrr r/r8rZhybridpropertyr:propertyr&setterr=rOrQr[r\r]r`rcrdrarfrrrrr!<s:         r!c@seZdZdZd"ddZdZdZdZdZdZ e j dd Z e j d d Z ed d Zd#ddZd$ddZeddZeddZddZd%ddZddZddZddZd d!ZdS)&rPaInternal object which maintains an individual DBAPI connection referenced by a :class:`_pool.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.Pool` next uses this record. The :class:`._ConnectionRecord` is delivered along with connection pool events, including :meth:`_events.PoolEvents.connect` and :meth:`_events.PoolEvents.checkout`, however :class:`._ConnectionRecord` still remains an internal object whose API and internals may change. .. seealso:: :class:`._ConnectionFairy` TcCs||_|r|t|_dSr )_ConnectionRecord__pool_ConnectionRecord__connectrfinalize_callback)rpoolr`rrrr8msz_ConnectionRecord.__init__FNrcCsiS)a`The ``.info`` dictionary associated with the DBAPI connection. This dictionary is shared among the :attr:`._ConnectionFairy.info` and :attr:`_engine.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. rr9rrrinfosz_ConnectionRecord.infocCsiS)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 rr9rrr record_infosz_ConnectionRecord.record_infoc sz }WnDtk rX}z&tj|ddW5QRXW5d}~XYnXt|}t |fdd_ }t |<rj d||S)NF_fairy_was_createdcstotd|dS)NT)_finalize_fairy)refr,rlrZrrrAsz,_ConnectionRecord.checkout..z#Connection %r checked out from pool)rdget_connectionrLr safe_reraise_checkin_failedZ_should_log_debugr^weakrefrr fairy_ref_strong_ref_connection_recordsrJrK)clsrlrerrfairyrrrrsrcheckouts&  *  z_ConnectionRecord.checkoutcCs|j|d|j|ddS)Nero)rWcheckin)rr{rprrrrvs z!_ConnectionRecord._checkin_failedcCsp|jdkr |r td|dSd|_|j}|j}|jrL|j}||q2|jjrb|j||| |dS)NzDouble checkin attempted on %s) rxrwarnrNrirkpopr-rrc)rrprNrl finalizerrrrrs  z_ConnectionRecord.checkincCs |jdk Sr )rxr9rrrin_usesz_ConnectionRecord.in_usecCs|jSr )rUr9rrrlast_connect_timesz#_ConnectionRecord.last_connect_timecCs|jdk r|dSr )rN_ConnectionRecord__closer9rrrrs z_ConnectionRecord.closecCs|jdkrdS|r(|jj|j||n|jj|j|||dk rj|jjd|rVdnd|j|jj|n|jjd|r|dnd|j|rt |_ n| 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:`_engine.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) rNrir-Zsoft_invalidaterWrJrm __class__rrV_soft_invalidate_timerrrsoftrrrrWs,    z_ConnectionRecord.invalidatecCsd}|jdkr"|j|n|jjdkr\t|j|jjkr\|jjd|jd}nH|jj |jkr|jjd|jd}n"|j |jkr|jjd|jd}|r| |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) rNrmclearrjrir'rVrUrJr(rr)rr2rrrrts<      z _ConnectionRecord.get_connectioncCs$|jdkp"|jj|jkp"|j|jkSr )rNrir(rUrr9rrr_is_hard_or_soft_invalidatedGs    z._ConnectionRecord._is_hard_or_soft_invalidatedcCs>|j|jjjr&|jj|j||j|jd|_dSr )rkrrir-rrNrOr9rrr__closeNs   z_ConnectionRecord.__closec Cs|j}d|_z2t|_||}|jd|||_d|_WnDtk r}z&t |jd|W5QRXW5d}~XYn>X|j j r|j j |j |j||j j |j |j|dS)NzCreated new connection %rTzError on connect(): %s)rirNrVrUr>rJrKfreshrLrrur-Z first_connectZ for_modifyZexec_once_unless_exceptionr`Z_exec_w_sync_on_first_run)rrlrNrrrrZ __connectUs0    *z_ConnectionRecord.__connect)T)T)T)NF)rrrrr8rrxrUrNrrmemoized_propertyrmrn classmethodr}rvrrgrrrrWrtrrrjrrrrrPLs2          10rPTc Cs|rt|dn|r(tt|d|dk rP|j|k r>dS|dksJt|j}|jj}|rn| pd|}| } n | }d} |dk r|r|r|j d||sdndz|pt |||}|j|kst|r| r| ||r2|r||_ || r|jjr|j|||nd|} |j | t| WnTtk r} z4|j jddd|rj|j| d t| tsxW5d} ~ XYnX|r|jdk r|dS) acCleanup for a :class:`._ConnectionFairy` whether or not it's already been garbage collected. When using an async dialect no IO can happen here (without using a dedicated thread), since this is called outside the greenlet context and with an already running loop. In this case function will only log a message and raise a warning. NTz&Connection %r being returned to pool%sz/, transaction state was already reset by callerra2The garbage collector is trying to clean up connection %r. This feature is unsupported on async dbapi, since no IO can be performed at this stage to reset the connection. Please close out all connections when they are no longer used, calling ``close()`` or using a context manager to manage their lifetime.z!Exception during reset or similarrHr~)ryrrwrrrxAssertionErrorrNr/rrJrKr^_reset_pooldetachr-Zclose_detachedrOrMrr BaseExceptionrW isinstancerLr) rNrDrlrrr,resetr|Zdont_restore_gcedrZcan_manipulate_connectionmessagerrrrrqssr           rqc@seZdZdZddZdZdZed#ddZddZ d$d d Z e Z d d Z e ddZe ddZejddZe ddZd%ddZddZddZddZdd Zd!d"ZdS)&r^abProxies a DBAPI connection and provides return-on-dereference support. This is an internal object used by the :class:`_pool.Pool` implementation to provide context management to a DBAPI connection delivered by that :class:`_pool.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 )rNrR_echo)rrrDr,rrrr8sz_ConnectionFairy.__init__Nc Cs|s.t|}||_d|_|dk r.t||_|jdkrBt d|jd7_|j js^|j rh|jdkrl|Sd}|dkr|j j }d|j _ z|j r|s|jr|jd|j|j|j}|s|jr|jd|jtn|jr|jd|j|j |j|j ||WStjk r}z|jrV|jd ||j ||j||dd n|jd |j||j |z|j |_WnJtk r}z*t|j j|d d ~W5QRXW5d}~XYnX|d8}W5d}~XYqpXqp|jd|t ddS)NrzThis connection is closedrErFzPool pre-ping on connection %sz;Pool pre-ping on connection %s failed, will invalidate poolz)Connection %s is fresh, skipping pre-pingzoDisconnection detected on checkout, invalidating all pooled connections prior to current timestamp (reason: %r))rYzVDisconnection detected on checkout, invalidating individual connection %s (reason: %r)Troz+Reconnection attempts exhausted on checkout)rPr}r_counterrwrrcurrentrNrZInvalidRequestErrorr-r)rRrrrJrKr/rZInvalidatePoolErrorZDisconnectionErrorZinvalidate_poolrmrWr[rtrLrrurv) rzrlZ threadconnsr|attemptsZconnection_is_freshresultrr{rrrr_s           z_ConnectionFairy._checkoutcCstj|j|dS)N)r|)r^r_rr9rrr_checkout_existing]sz#_ConnectionFairy._checkout_existingTc Cs.t|j|j|jd|j||dd|_d|_dS)N)rr|)rqrNrRrr)rrrrrrY`s z_ConnectionFairy._checkincCsv|jjr|j||j|jtkrF|jr8|jd|j|j |n,|jt krr|jrf|jd|j|j |dS)Nz Connection %s rollback-on-returnzConnection %s commit-on-return) r-rrRr+rrrJrKrNr/rr r)rrlrrrros   z_ConnectionFairy._resetcCs|jjSr )rrJr9rrr_loggersz_ConnectionFairy._loggercCs |jdk S)zbReturn True if this :class:`._ConnectionFairy` still refers to an active DBAPI connection.N)rNr9rrrrSsz_ConnectionFairy.is_validcCs|jjS)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:`_engine.Connection.info` accessors. The dictionary associated with a particular DBAPI connection is discarded when the connection itself is discarded. )rRrmr9rrrrmsz_ConnectionFairy.infocCs|jr|jjSdSdS)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)rRrnr9rrrrns z_ConnectionFairy.record_infoFcCsD|jdkrtddS|jr.|jj||d|s@d|_|dS)aMark this connection as invalidated. This method can be called directly, and is also called as a result of the :meth:`_engine.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)rNrrrRrWrYrrrrrWs  z_ConnectionFairy.invalidatecOs|jj||S)zReturn a new DBAPI cursor for the underlying connection. This method is a proxy for the ``connection.cursor()`` DBAPI method. )rNcursor)rargskwargsrrrrsz_ConnectionFairy.cursorcCs t|j|Sr )rTrN)rkeyrrr __getattr__sz_ConnectionFairy.__getattr__cCs\|jdk rX|j}d|_d|_|j|j|j|_d|_|jjjrX|jj|j|dS)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) rRrxrNrrarmcopyr-r)rrZrrrrs   z_ConnectionFairy.detachcCs$|jd8_|jdkr |dS)NrErrrYr9rrrrs z_ConnectionFairy.closecCs(|jd8_|jdkr$|jdddS)NrErF)rrr9rrr_close_no_resets z _ConnectionFairy._close_no_reset)NN)T)NF)rrrrr8rNrRrr_rrY_closerrgrrSrrrmrnrWrrrrrrrrrr^s0 `       r^)TN)r collectionsrrVrwrrrrrr*rr r objectr r Z Identifiedr!rPrqryr^rrrr s.        / a