o
    LDi                     @  s$  d dl mZ d dlZd dlmZmZ d dlZd dlZd dlZd dl	Z	d dl
mZ d dlmZmZmZ d dlZddlmZ ddlmZ dd	lmZ dd
lmZ eeZG dd deZG dd dejeddZG dd dZG dd dZG dd dZddddddddddej ej!dddZ"dS )    )annotationsN)	AwaitableCallable)TracebackType)AnyOptionalType   )compat
connection)
exceptions)protocolc                      s2   e Zd Zddd fddZedddZ  ZS )PoolConnectionProxyMetaF)wrapnamestrbasestuple[Type[Any], ...]dctdict[str, Any]r   boolreturnc          	        s   |r?t tjD ]-}|ds||v rqttj|}t|sqt|}| ||}t	
||}|||< qd|vr?tjj|d< t | |||S )N___doc__)dirr   
Connection
startswithgetattrinspect
isfunctioniscoroutinefunction_wrap_connection_method	functoolsupdate_wrapperr   super__new__)	mclsr   r   r   r   attrnamemethiscoroutinewrapper	__class__ X/var/www/www-root/data/www/77.83.87.30/venv/lib/python3.10/site-packages/asyncpg/pool.pyr&      s   


zPoolConnectionProxyMeta.__new__	meth_namer*   Callable[..., Any]c                   s    d fdd}|rt | |S )	Nselfr   argskwargsr   c                   s@   | j d u rtd t| j j }|| j g|R i |S )NzJcannot call Connection.{}(): connection has been released back to the pool)_conr   InterfaceErrorformatr   r-   )r2   r3   r4   r)   r0   r.   r/   call_con_method=   s   
zHPoolConnectionProxyMeta._wrap_connection_method.<locals>.call_con_method)r2   r   r3   r   r4   r   r   r   )r
   markcoroutinefunction)r0   r*   r9   r.   r8   r/   r"   9   s   
z/PoolConnectionProxyMeta._wrap_connection_method)
r   r   r   r   r   r   r   r   r   r   )r0   r   r*   r   r   r1   )__name__
__module____qualname__r&   staticmethodr"   __classcell__r.   r.   r,   r/   r      s
    r   c                   @  s8   e Zd ZdZddd	ZdddZdddZdddZdS )PoolConnectionProxy)r5   _holderholderPoolConnectionHolderconconnection.Connectionr   Nonec                 C  s   || _ || _||  d S N)r5   rA   
_set_proxy)r2   rB   rD   r.   r.   r/   __init__T   s   zPoolConnectionProxy.__init__attrr   r   c                 C  s   t | j|S rG   )r   r5   )r2   rJ   r.   r.   r/   __getattr__[   s   zPoolConnectionProxy.__getattr__Optional[connection.Connection]c                 C  s*   | j d u rd S | j d }| _ |d  |S rG   )r5   rH   )r2   rD   r.   r.   r/   _detach_   s
   

zPoolConnectionProxy._detachc                 C  s:   | j d u rdj| jjt| dS dj| jj| j t| dS )Nz <{classname} [released] {id:#x}>)	classnameidz<{classname} {con!r} {id:#x}>)rN   rD   rO   )r5   r7   r-   r;   rO   r2   r.   r.   r/   __repr__g   s   
zPoolConnectionProxy.__repr__N)rB   rC   rD   rE   r   rF   )rJ   r   r   r   )r   rL   )r   r   )r;   r<   r=   	__slots__rI   rK   rM   rQ   r.   r.   r.   r/   r@   N   s    


r@   T)	metaclassr   c                   @  s   e Zd ZdZd,ddZd-ddZd-ddZd.ddZd/ddZd0ddZ	d.ddZ
d.ddZd.dd Zd.d!d"Zd.d#d$Zd.d%d&Zd.d'd(Zd.d)d*Zd+S )1rC   )r5   _pool_loop_proxy_max_queries_setup_max_inactive_time_in_use_inactive_callback_timeout_generationpool'Pool'max_queriesfloatsetup:Optional[Callable[[PoolConnectionProxy], Awaitable[None]]]max_inactive_timer   rF   c                C  s@   || _ d | _d | _|| _|| _|| _d | _d | _d | _d | _	d S rG   )
rT   r5   rV   rW   rY   rX   r[   rZ   r\   r]   )r2   r^   r`   rb   rd   r.   r.   r/   rI   x   s   	
zPoolConnectionHolder.__init__r   c                 C  s   | j d uo
| j   S rG   )r5   	is_closedrP   r.   r.   r/   is_connected   s   z!PoolConnectionHolder.is_connectedc                 C  s   | j  S rG   rZ   rP   r.   r.   r/   is_idle   s   zPoolConnectionHolder.is_idlec                   sF   | j d urtd| j I d H | _ | jj| _|   |   d S )NzMPoolConnectionHolder.connect() called while another connection already exists)r5   r   InternalClientErrorrT   _get_new_connectionr]   _maybe_cancel_inactive_callback_setup_inactive_callbackrP   r.   r.   r/   connect   s   

zPoolConnectionHolder.connectr@   c              
     s   | j d u s| j  rd | _ |  I d H  n| j| jjkr4| jj| j j| jd d | _ |  I d H  | 	  t
| | j  | _}| jd urnz
| |I d H  W n ttjfym } zz| j  I d H  W ||d }~ww | jj | _|S )Ntimeout)r5   re   rm   r]   rT   rU   create_taskcloser\   rk   r@   rV   rX   	ExceptionasyncioCancelledErrorcreate_futurerZ   )r2   proxyexr.   r.   r/   acquire   s.   
zPoolConnectionHolder.acquirero   Optional[float]c              
     s  | j d u rtd| j rd S d | _| jjj| jkr)| jj	|dI d H  d S | j
| jj
kr<| jj	|dI d H  d S zi|}| jj rbt }t| jj |I d H  |d urb|t | 8 }| jjd urt|4 I d H  | j I d H  | j| jI d H  W d   I d H  n1 I d H sw   Y  n
| jj|dI d H  W n ttjfy } zz| j  W ||d }~ww |   |   d S )NzAPoolConnectionHolder.release() called on a free connection holderrn   )rZ   r   ri   r5   re   r\   	_protocolqueries_countrW   rq   r]   rT   _is_cancellingtime	monotonicr
   wait_for_wait_for_cancellation_resetro   resetrr   rs   rt   	terminate_releaserl   )r2   ro   budgetstartedrw   r.   r.   r/   release   sP   



(zPoolConnectionHolder.releasec                   s    | j d u rd S | j I d H  d S rG   rg   rP   r.   r.   r/   wait_until_released  s   
z(PoolConnectionHolder.wait_until_releasedc                   s$   | j d ur| j  I d H  d S d S rG   )r5   rq   rP   r.   r.   r/   rq     s   
zPoolConnectionHolder.closec                 C  s   | j d ur| j   d S d S rG   )r5   r   rP   r.   r.   r/   r     s   
zPoolConnectionHolder.terminatec                 C  s8   | j d ur
td| jr| jj| j| j| _ d S d S )Nz/pool connection inactivity timer already exists)r[   r   ri   rY   rT   rU   
call_later_deactivate_inactive_connectionrP   r.   r.   r/   rl     s   

z-PoolConnectionHolder._setup_inactive_callbackc                 C  s"   | j d ur| j   d | _ d S d S rG   )r[   cancelrP   r.   r.   r/   rk     s   


z4PoolConnectionHolder._maybe_cancel_inactive_callbackc                 C  s8   | j d ur
td| jd ur| j  |   d S d S )Nz/attempting to deactivate an acquired connection)rZ   r   ri   r5   r   _release_on_closerP   r.   r.   r/   r   "  s   


z4PoolConnectionHolder._deactivate_inactive_connectionc                 C  s   |    |   d | _d S rG   )rk   r   r5   rP   r.   r.   r/   r   0  s   
z&PoolConnectionHolder._release_on_closec                 C  sV   | j du rdS | j  s| j d d| _ | jdur"| j  d| _| jj|  dS )zRelease this connection holder.N)rZ   done
set_resultrV   rM   rT   _queue
put_nowaitrP   r.   r.   r/   r   5  s   



zPoolConnectionHolder._releaseN)
r^   r_   r`   ra   rb   rc   rd   ra   r   rF   )r   r   )r   rF   )r   r@   )ro   ry   r   rF   )r;   r<   r=   rR   rI   rf   rh   rm   rx   r   r   rq   r   rl   rk   r   r   r   r.   r.   r.   r/   rC   p   s     





%
?



	

rC   c                   @  s  e Zd ZdZdZdddddddZdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd ZdVddZdd ZdddWdd ZdddXd"d#Zddd$dYd&d'Zd(dd)d*d+Zddd$d,d-Zddd$d.d/Zddddddddddddd0d1d2Zddddddddddd3
d4d5Zddddddddddddddddd6d7d8Zddddd9d:d;Zddd<d=Zd>d? Zddd@dAZdBdC ZdDdE ZdFdG ZdHdI ZdJdK Z dLdM Z!dNdO Z"dPdQ Z#dRdS Z$dTdU Z%dS )ZPoola  A connection pool.

    Connection pool can be used to manage a set of connections to the database.
    Connections are first acquired from the pool, then used, and then released
    back to the pool.  Once a connection is released, it's reset to close all
    open cursors and other resources *except* prepared statements.

    Pools are created by calling :func:`~asyncpg.pool.create_pool`.
    )r   rU   _minsize_maxsize_init_connectr   _connect_args_connect_kwargs_holders_initialized_initializing_closing_closed_connection_class_record_classr]   rX   rW   !_max_inactive_connection_lifetimeN)rm   rb   initr   c                O  s:  t |dkrtjdtdd |	d u rt }	|	| _|dkr!td|dk r)td||kr1td|dkr9td	|dk rAtd
t|
t	j
sNtd|
t|tjs[td||| _|| _g | _d| _d| _d | _|
| _|| _d| _d| _d| _|d ur|nt	j| _|| _|| _|| _|| _|| _ || _!|| _"d S )Nr	   zPassing multiple positional arguments to asyncpg.Pool constructor is deprecated and will be removed in asyncpg 0.17.0.  The non-deprecated form is asyncpg.Pool(<dsn>, **kwargs)   )
stacklevelr   z,max_size is expected to be greater than zeroz3min_size is expected to be greater or equal to zeroz!min_size is greater than max_sizez/max_queries is expected to be greater than zerozKmax_inactive_connection_lifetime is expected to be greater or equal to zerozMconnection_class is expected to be a subclass of asyncpg.Connection, got {!r}zErecord_class is expected to be a subclass of asyncpg.Record, got {!r}F)#lenwarningswarnDeprecationWarningrs   get_event_looprU   
ValueError
issubclassr   r   	TypeErrorr7   r   Recordr   r   r   r   r   r   r   r   r   r   r]   rm   r   r   r   rX   r   r   rW   r   )r2   min_sizemax_sizer`    max_inactive_connection_lifetimerm   rb   r   r   loopconnection_classrecord_classconnect_argsconnect_kwargsr.   r.   r/   rI   \  sh   zPool.__init__c                   sb   | j r| S | jrtd| jrtdd| _z|  I d H  | W d| _d| _ S d| _d| _ w )Nz)pool is being initialized in another taskpool is closedTF)r   r   r   r6   r   _initializerP   r.   r.   r/   _async__init__  s"   
zPool._async__init__c                   s   t j| jd| _t| jD ]}t| | j| j| jd}| j	
| | j| q| jrh| j	d }| I d H  | jdkrjg }tt| j	d d D ]\}}|| jd krV n|
|  qIt j| I d H  d S d S d S )N)maxsize)r`   rd   rb   r	   )rs   	LifoQueuer   r   rangerC   rW   r   rX   r   appendr   r   rm   	enumeratereversedgather)r2   r   chfirst_chconnect_tasksir.   r.   r/   r     s.   

zPool._initializec                 C  s   | j p| jS )z_Return ``True`` if the pool is closing or is closed.

        .. versionadded:: 0.28.0
        )r   r   rP   r.   r.   r/   
is_closing  s   zPool.is_closingc                 C     t dd | jD S )zaReturn the current number of connections in this pool.

        .. versionadded:: 0.25.0
        c                 s  s    | ]}|  V  qd S rG   )rf   .0hr.   r.   r/   	<genexpr>  s    z Pool.get_size.<locals>.<genexpr>sumr   rP   r.   r.   r/   get_size     zPool.get_sizec                 C     | j S )zaReturn the minimum number of connections in this pool.

        .. versionadded:: 0.25.0
        )r   rP   r.   r.   r/   get_min_size     zPool.get_min_sizec                 C  r   )ziReturn the maximum allowed number of connections in this pool.

        .. versionadded:: 0.25.0
        )r   rP   r.   r.   r/   get_max_size  r   zPool.get_max_sizec                 C  r   )zfReturn the current number of idle connections in this pool.

        .. versionadded:: 0.25.0
        c                 s  s     | ]}|  o| V  qd S rG   )rf   rh   r   r.   r.   r/   r     s    z%Pool.get_idle_size.<locals>.<genexpr>r   rP   r.   r.   r/   get_idle_size  r   zPool.get_idle_sizec                 K  s   |g| _ || _dS )a  Set the new connection arguments for this pool.

        The new connection arguments will be used for all subsequent
        new connection attempts.  Existing connections will remain until
        they expire. Use :meth:`Pool.expire_connections()
        <asyncpg.pool.Pool.expire_connections>` to expedite the connection
        expiry.

        :param str dsn:
            Connection arguments specified using as a single string in
            the following format:
            ``postgres://user:pass@host:port/database?option=value``.

        :param \*\*connect_kwargs:
            Keyword arguments for the :func:`~asyncpg.connection.connect`
            function.

        .. versionadded:: 0.16.0
        N)r   r   )r2   dsnr   r.   r.   r/   set_connect_args  s   
zPool.set_connect_argsc              
     s   | j | j| j| j| jd| jI d H }t|| jsI| j}|j d|j }t	|}|jdkr4|j}n	|j d|j }t
d| d| d| jd urvz| |I d H  W |S  ttjfyu } zz
| I d H  W ||d }~ww |S )N)r   r   r   .builtinsz9expected pool connect callback to return an instance of 'z', got '')r   r   rU   r   r   r   
isinstancer<   r;   typer   r6   r   rr   rs   rt   rq   )r2   rD   goodgood_nbadbad_nrw   r.   r.   r/   rj     sD   

zPool._get_new_connectionrn   queryr   ro   ry   r   c             	     s`   |   4 I dH }|j|g|R d|iI dH W  d  I dH  S 1 I dH s)w   Y  dS )a  Execute an SQL command (or commands).

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.execute() <asyncpg.connection.Connection.execute>`.

        .. versionadded:: 0.10.0
        Nro   )rx   execute)r2   r   ro   r3   rD   r.   r.   r/   r   A  s   0zPool.executecommandc             	     sX   |   4 I dH }|j|||dI dH W  d  I dH  S 1 I dH s%w   Y  dS )aC  Execute an SQL *command* for each sequence of arguments in *args*.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.executemany()
        <asyncpg.connection.Connection.executemany>`.

        .. versionadded:: 0.10.0
        Nrn   )rx   executemany)r2   r   r3   ro   rD   r.   r.   r/   r   R  s   0zPool.executemanyro   r   listc             	     b   |   4 I dH }|j|g|R ||dI dH W  d  I dH  S 1 I dH s*w   Y  dS )a-  Run a query and return the results as a list of :class:`Record`.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.fetch() <asyncpg.connection.Connection.fetch>`.

        .. versionadded:: 0.10.0
        Nr   )rx   fetchr2   r   ro   r   r3   rD   r.   r.   r/   r   e  s   0z
Pool.fetchr   columnro   c             	     r   )a+  Run a query and return a value in the first row.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.fetchval()
        <asyncpg.connection.Connection.fetchval>`.

        .. versionadded:: 0.10.0
        Nr   )rx   fetchval)r2   r   r   ro   r3   rD   r.   r.   r/   r   |  s   
0zPool.fetchvalc             	     r   )a  Run a query and return the first row.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.fetchrow() <asyncpg.connection.Connection.fetchrow>`.

        .. versionadded:: 0.10.0
        Nr   )rx   fetchrowr   r.   r.   r/   r     s   	0zPool.fetchrowc             	     sZ   |   4 I dH }|j||||dI dH W  d  I dH  S 1 I dH s&w   Y  dS )an  Run a query for each sequence of arguments in *args*
        and return the results as a list of :class:`Record`.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.fetchmany()
        <asyncpg.connection.Connection.fetchmany>`.

        .. versionadded:: 0.30.0
        Nr   )rx   	fetchmany)r2   r   r3   ro   r   rD   r.   r.   r/   r     s   
0zPool.fetchmany)columnsschema_namero   r7   oids	delimiternullheaderquoteescapeforce_quoteencodingc                  sn   |   4 I dH !}|j|||||||||	|
||||dI dH W  d  I dH  S 1 I dH s0w   Y  dS )a;  Copy table contents to a file or file-like object.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.copy_from_table()
        <asyncpg.connection.Connection.copy_from_table>`.

        .. versionadded:: 0.24.0
        N)outputr   r   ro   r7   r   r   r   r   r   r   r   r   )rx   copy_from_table)r2   
table_namer   r   r   ro   r7   r   r   r   r   r   r   r   r   rD   r.   r.   r/   r     s&   
0zPool.copy_from_table)
ro   r7   r   r   r   r   r   r   r   r   c                  st   |   4 I dH $}|j|g|R ||||||||	|
||dI dH W  d  I dH  S 1 I dH s3w   Y  dS )aC  Copy the results of a query to a file or file-like object.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.copy_from_query()
        <asyncpg.connection.Connection.copy_from_query>`.

        .. versionadded:: 0.24.0
        N)r   ro   r7   r   r   r   r   r   r   r   r   )rx   copy_from_query)r2   r   r   ro   r7   r   r   r   r   r   r   r   r   r3   rD   r.   r.   r/   r     s(   0zPool.copy_from_query)r   r   ro   r7   r   freezer   r   r   r   r   r   force_not_null
force_nullr   wherec             	     s   |   4 I dH H}|j|fi d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|I dH W  d  I dH  S 1 I dH sWw   Y  dS )a&  Copy data to the specified table.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.copy_to_table()
        <asyncpg.connection.Connection.copy_to_table>`.

        .. versionadded:: 0.24.0
        Nsourcer   r   ro   r7   r   r   r   r   r   r   r   r   r   r   r   r   )rx   copy_to_table)r2   r   r   r   r   ro   r7   r   r   r   r   r   r   r   r   r   r   r   r   rD   r.   r.   r/   r     sP   	
0zPool.copy_to_table)r   r   ro   r   c             	     s^   |   4 I dH }|j||||||dI dH W  d  I dH  S 1 I dH s(w   Y  dS )aU  Copy a list of records to the specified table using binary COPY.

        Pool performs this operation using one of its connections.  Other than
        that, it behaves identically to
        :meth:`Connection.copy_records_to_table()
        <asyncpg.connection.Connection.copy_records_to_table>`.

        .. versionadded:: 0.24.0
        N)recordsr   r   ro   r   )rx   copy_records_to_table)r2   r   r   r   r   ro   r   rD   r.   r.   r/   r   7  s   
0zPool.copy_records_to_tablec                C  s
   t | |S )aT  Acquire a database connection from the pool.

        :param float timeout: A timeout for acquiring a Connection.
        :return: An instance of :class:`~asyncpg.connection.Connection`.

        Can be used in an ``await`` expression or with an ``async with`` block.

        .. code-block:: python

            async with pool.acquire() as con:
                await con.execute(...)

        Or:

        .. code-block:: python

            con = await pool.acquire()
            try:
                await con.execute(...)
            finally:
                await pool.release(con)
        )PoolAcquireContextr2   ro   r.   r.   r/   rx   T  s   
zPool.acquirec                   sR    fdd} j rtd   d u r| I d H S tj| dI d H S )Nc               	     sR    j  I d H } z	|  I d H }W n ttjfy#    j |   w | _|S rG   )r   getrx   rr   rs   rt   r   r\   )r   rv   r  r.   r/   _acquire_impln  s   z$Pool._acquire.<locals>._acquire_implzpool is closingrn   )r   r   r6   _check_initr
   r   )r2   ro   r  r.   r  r/   _acquirem  s   
zPool._acquirec                  sv   t |tus|jj| urtdj|d|jdu rdS |   |j	  |j}|du r0|j
}t||I dH S )a  Release a database connection back to the pool.

        :param Connection connection:
            A :class:`~asyncpg.connection.Connection` object to release.
        :param float timeout:
            A timeout for releasing the connection.  If not specified, defaults
            to the timeout provided in the corresponding call to the
            :meth:`Pool.acquire() <asyncpg.pool.Pool.acquire>` method.

        .. versionchanged:: 0.14.0
            Added the *timeout* parameter.
        zWPool.release() received invalid connection: {connection!r} is not a member of this poolr   N)r   r@   rA   rT   r   r6   r7   r5   r  _on_releaser\   rs   shieldr   )r2   r   ro   r   r.   r.   r/   r     s"   

zPool.releasec              	     s   | j rdS |   d| _d}zKz*| jd| j}dd | jD }tj| I dH  dd | jD }tj| I dH  W n t	tj
fyI   |    w W |durS|  d| _ d| _dS |durc|  d| _ d| _w )a  Attempt to gracefully close all connections in the pool.

        Wait until all pool connections are released, close them and
        shut down the pool.  If any error (including cancellation) occurs
        in ``close()`` the pool will terminate by calling
        :meth:`Pool.terminate() <pool.Pool.terminate>`.

        It is advisable to use :func:`python:asyncio.wait_for` to set
        a timeout.

        .. versionchanged:: 0.16.0
            ``close()`` now waits until all pool connections are released
            before closing them and the pool.  Errors raised in ``close()``
            will cause immediate pool termination.
        NT<   c                 S     g | ]}|  qS r.   )r   r   r   r.   r.   r/   
<listcomp>      zPool.close.<locals>.<listcomp>c                 S  r
  r.   rq   r  r.   r.   r/   r    r  F)r   r  r   rU   r   _warn_on_long_closer   rs   r   rr   rt   r   r   )r2   warning_callbackrelease_corosclose_corosr.   r.   r/   rq     s>   
z
Pool.closec                 C  s   t d d S )NzPool.close() is taking over 60 seconds to complete. Check if you have any unreleased connections left. Use asyncio.wait_for() to set a timeout for Pool.close().)loggerwarningrP   r.   r.   r/   r    s   zPool._warn_on_long_closec                 C  s0   | j rdS |   | jD ]}|  qd| _ dS )z&Terminate all connections in the pool.NT)r   r  r   r   r2   r   r.   r.   r/   r     s   


zPool.terminatec                   s   |  j d7  _ dS )zExpire all currently open connections.

        Cause all currently open connections to get replaced on the
        next :meth:`~asyncpg.pool.Pool.acquire()` call.

        .. versionadded:: 0.16.0
        r	   N)r]   rP   r.   r.   r/   expire_connections  s   zPool.expire_connectionsc                 C  s4   | j s| jrtdtd| jrtdd S )Nzipool is being initialized, but not yet ready: likely there is a race between creating a pool and using itzpool is not initializedr   )r   r   r   r6   r   rP   r.   r.   r/   r    s   

zPool._check_initc                 C  $   | j D ]}|jd ur|j  qd S rG   )r   r5   _drop_local_statement_cacher  r.   r.   r/   _drop_statement_cache  
   


zPool._drop_statement_cachec                 C  r  rG   )r   r5   _drop_local_type_cacher  r.   r.   r/   _drop_type_cache  r  zPool._drop_type_cachec                 C  s   |    S rG   )r   	__await__rP   r.   r.   r/   r    s   zPool.__await__c                   s   |   I d H  | S rG   )r   rP   r.   r.   r/   
__aenter__  s   zPool.__aenter__c                   s   |   I d H  d S rG   r  )r2   excr.   r.   r/   	__aexit__  s   zPool.__aexit__rG   )r   r   ro   ry   r   r   )r   r   ro   ry   )r   r   )&r;   r<   r=   r   rR   rI   r   r   r   r   r   r   r   r   rj   r   r   r   r   r   r   r   r   r   r   rx   r  r   rq   r  r   r  r  r  r  r  r  r   r.   r.   r.   r/   r   I  s    
Q!
,2/:&-	
r   c                   @  s<   e Zd ZdZddd	Zd
d Z			ddddZdd ZdS )r  )ro   r   r   r^   r^   r   ro   ry   r   rF   c                 C  s   || _ || _d | _d| _d S )NF)r^   ro   r   r   )r2   r^   ro   r.   r.   r/   rI     s   
zPoolAcquireContext.__init__c                   s8   | j d us	| jrtd| j| jI d H | _ | j S )Nz a connection is already acquired)r   r   r   r6   r^   r  ro   rP   r.   r.   r/   r    s
   
zPoolAcquireContext.__aenter__Nexc_typeOptional[Type[BaseException]]exc_valOptional[BaseException]exc_tbOptional[TracebackType]c                   s*   d| _ | j}d | _| j|I d H  d S NT)r   r   r^   r   )r2   r!  r#  r%  rD   r.   r.   r/   r   #  s
   zPoolAcquireContext.__aexit__c                 C  s   d| _ | j| j S r'  )r   r^   r  ro   r  rP   r.   r.   r/   r  .  s   zPoolAcquireContext.__await__)r^   r   ro   ry   r   rF   )NNN)r!  r"  r#  r$  r%  r&  r   rF   )r;   r<   r=   rR   rI   r  r   r  r.   r.   r.   r/   r    s    
r  
   iP  g     r@)r   r   r`   r   rm   rb   r   r   r   r   r   c                K  s(   t | f|
|||||	|||||d|S )a8  Create a connection pool.

    Can be used either with an ``async with`` block:

    .. code-block:: python

        async with asyncpg.create_pool(user='postgres',
                                       command_timeout=60) as pool:
            await pool.fetch('SELECT 1')

    Or to perform multiple operations on a single connection:

    .. code-block:: python

        async with asyncpg.create_pool(user='postgres',
                                       command_timeout=60) as pool:
            async with pool.acquire() as con:
                await con.execute('''
                   CREATE TABLE names (
                      id serial PRIMARY KEY,
                      name VARCHAR (255) NOT NULL)
                ''')
                await con.fetch('SELECT 1')

    Or directly with ``await`` (not recommended):

    .. code-block:: python

        pool = await asyncpg.create_pool(user='postgres', command_timeout=60)
        con = await pool.acquire()
        try:
            await con.fetch('SELECT 1')
        finally:
            await pool.release(con)

    .. warning::
        Prepared statements and cursors returned by
        :meth:`Connection.prepare() <asyncpg.connection.Connection.prepare>`
        and :meth:`Connection.cursor() <asyncpg.connection.Connection.cursor>`
        become invalid once the connection is released.  Likewise, all
        notification and log listeners are removed, and ``asyncpg`` will
        issue a warning if there are any listener callbacks registered on a
        connection that is being released to the pool.

    :param str dsn:
        Connection arguments specified using as a single string in
        the following format:
        ``postgres://user:pass@host:port/database?option=value``.

    :param \*\*connect_kwargs:
        Keyword arguments for the :func:`~asyncpg.connection.connect`
        function.

    :param Connection connection_class:
        The class to use for connections.  Must be a subclass of
        :class:`~asyncpg.connection.Connection`.

    :param type record_class:
        If specified, the class to use for records returned by queries on
        the connections in this pool.  Must be a subclass of
        :class:`~asyncpg.Record`.

    :param int min_size:
        Number of connection the pool will be initialized with.

    :param int max_size:
        Max number of connections in the pool.

    :param int max_queries:
        Number of queries after a connection is closed and replaced
        with a new connection.

    :param float max_inactive_connection_lifetime:
        Number of seconds after which inactive connections in the
        pool will be closed.  Pass ``0`` to disable this mechanism.

    :param coroutine connect:
        A coroutine that is called instead of
        :func:`~asyncpg.connection.connect` whenever the pool needs to make a
        new connection.  Must return an instance of type specified by
        *connection_class* or :class:`~asyncpg.connection.Connection` if
        *connection_class* was not specified.

    :param coroutine setup:
        A coroutine to prepare a connection right before it is returned
        from :meth:`Pool.acquire()`.  An example use
        case would be to automatically set up notifications listeners for
        all connections of a pool.

    :param coroutine init:
        A coroutine to initialize a connection when it is created.
        An example use case would be to setup type codecs with
        :meth:`Connection.set_builtin_type_codec() <\
        asyncpg.connection.Connection.set_builtin_type_codec>`
        or :meth:`Connection.set_type_codec() <\
        asyncpg.connection.Connection.set_type_codec>`.

    :param coroutine reset:
        A coroutine to reset a connection before it is returned to the pool by
        :meth:`Pool.release()`.  The function is supposed
        to reset any changes made to the database session so that the next
        acquirer gets the connection in a well-defined state.

        The default implementation calls :meth:`Connection.reset() <\
        asyncpg.connection.Connection.reset>`, which runs the following::

            SELECT pg_advisory_unlock_all();
            CLOSE ALL;
            UNLISTEN *;
            RESET ALL;

        The exact reset query is determined by detected server capabilities,
        and a custom *reset* implementation can obtain the default query
        by calling :meth:`Connection.get_reset_query() <\
        asyncpg.connection.Connection.get_reset_query>`.

    :param loop:
        An asyncio event loop instance.  If ``None``, the default
        event loop will be used.

    :return: An instance of :class:`~asyncpg.pool.Pool`.

    .. versionchanged:: 0.10.0
       An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
       attempted operation on a released connection.

    .. versionchanged:: 0.13.0
       An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
       attempted operation on a prepared statement or a cursor created
       on a connection that has been released to the pool.

    .. versionchanged:: 0.13.0
       An :exc:`~asyncpg.exceptions.InterfaceWarning` will be produced
       if there are any active listeners (added via
       :meth:`Connection.add_listener()
       <asyncpg.connection.Connection.add_listener>`
       or :meth:`Connection.add_log_listener()
       <asyncpg.connection.Connection.add_log_listener>`) present on the
       connection at the moment of its release to the pool.

    .. versionchanged:: 0.22.0
       Added the *record_class* parameter.

    .. versionchanged:: 0.30.0
       Added the *connect* and *reset* parameters.
    )r   r   r   r   r`   r   rm   rb   r   r   r   )r   )r   r   r   r`   r   rm   rb   r   r   r   r   r   r   r.   r.   r/   create_pool3  s$     r)  rG   )#
__future__r   rs   collections.abcr   r   r#   r   loggingr}   typesr   typingr   r   r   r    r
   r   r   r   	getLoggerr;   r  r   r   _ConnectionProxyr@   rC   r   r  r   r   r)  r.   r.   r.   r/   <module>   sT   
2" Z     O 