o
    "4gE                     @  s  d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZmZmZmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl+m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z>m?Z? 	 ddl@Z@ddlAZAddlAmBZB ddl)mCZC erddlEmFZF dZGejHjIZIejHjJZJejKjLZLejKjMZMejKjNZN	 eAjOePfZQeRd ZSG d!d" d"e=e! ZTdS )#z+
Psycopg connection object (async version)
    )annotationsN)	monotonic)TracebackType)AnyAsyncGeneratorAsyncIteratorcastoverloadTYPE_CHECKING)asynccontextmanager   )pq)errors)waiting)AdaptContextConnDict	ConnParamParamsPQGenQueryRV)Xid)RowAsyncRowFactory	tuple_rowargs_row)AdaptersMap)IsolationLevel)Self)make_conninfoconninfo_to_dict)conninfo_attempts_asynctimeout_from_conninfo)AsyncPipeline)notifies)AsyncTransaction)AsyncCursor)capabilities)AsyncServerCursor)BaseConnection	CursorRowNotifyT)Lock)	to_thread)PGconng?psycopgc                      s0  e Zd ZU dZdZded< ded< ded< d	ed
< eee efd fddZ	e
	ddddddddd"d#Zdd$d%Zdd-d.Ze
dd1d2Zdd3d4Zedd5dd8d9Zedd5dd<d9Zedddd=ddCd9Zedddd=ddEd9Z	ddddddFddId9Z	ddddJddPdQZddRdSZddTdUZdVdWddZd[Zd\dWdd]d^Ze	dddcddZdddeddidjZeddldmZefddrdsZddudvZddwdxZddzd{Zdd|d}Z dd~dZ!dddZ"dddZ#dddZ$	 dddZ%dddZ&dddZ'ddddZ(ddddZ)dddZ*  Z+S )AsyncConnectionz3
    Wrapper for a connection to the database.
    r/   ztype[AsyncCursor[Row]]cursor_factoryztype[AsyncServerCursor[Row]]server_cursor_factoryAsyncRowFactory[Row]row_factoryzAsyncPipeline | None	_pipelinepgconnr.   c                   s*   t  | || _t | _t| _t| _d S N)	super__init__r4   r,   lockr&   r1   r(   r2   )selfr6   r4   	__class__ a/var/www/html/authentication-server/venv/lib/python3.10/site-packages/psycopg/connection_async.pyr9   J   s
   
zAsyncConnection.__init__ F   N)
autocommitprepare_thresholdcontextr4   r1   conninfostrrB   boolrC   
int | NonerD   AdaptContext | NoneAsyncRowFactory[Row] | Nonetype[AsyncCursor[Row]] | Nonekwargsr   returnr   c                  sJ  	 t jdkrt }t|tjrtd| j|fi |I dH }	t	|	}
d}t
|	I dH }|D ]L}ztdi |}| j||
d}tj|tdI dH }W n/ tjy| } z"t|dkrptd	|d
|d|dt| |}W Y d}~q1d}~ww  |s|sJ |dt||_|r||_|r||_|rt|j|_||_|S )z[
        Connect to a database server and return a new `AsyncConnection` instance.
        Twin32zPsycopg cannot use the 'ProactorEventLoop' to run in async mode. Please use a compatible event loop, for instance by setting 'asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())'Nr@   timeoutintervalr   z=connection attempt failed: host: %r port: %r, hostaddr %r: %shostporthostaddrr@   )sysplatformasyncioget_running_loop
isinstanceProactorEventLoopeInterfaceError_get_connection_paramsr"   r!   r   _connect_genr   wait_conn_async_WAIT_INTERVAL_NO_TRACEBACKlenloggerdebuggetrF   with_tracebackrG   _autocommitr4   r1   r   adapters	_adaptersrC   )clsrE   rB   rC   rD   r4   r1   rL   loopparamsrP   rvattemptsattemptgenexlast_exr>   r>   r?   connectU   sT   


zAsyncConnection.connectc                   s   | S r7   r>   r;   r>   r>   r?   
__aenter__   s   zAsyncConnection.__aenter__exc_typetype[BaseException] | Noneexc_valBaseException | Noneexc_tbTracebackType | NoneNonec              
     s   | j rd S |r+z	|  I d H  W n  ty* } ztd| | W Y d }~nd }~ww |  I d H  t| dd sA|  I d H  d S d S )Nz#error ignored in rollback on %s: %s_pool)closedrollback	Exceptionre   warningcommitgetattrclose)r;   rx   rz   r|   exc2r>   r>   r?   	__aexit__   s   zAsyncConnection.__aexit__r   r   c                   s   t |fi |S )z3Manipulate connection parameters before connecting.)r    )rl   rE   rL   r>   r>   r?   r_      s   z&AsyncConnection._get_connection_paramsc                   s    | j rdS d| _| j  dS )zClose the database connection.NT)r   _closedr6   finishrv   r>   r>   r?   r      s
   zAsyncConnection.close)binaryr   AsyncCursor[Row]c                C     d S r7   r>   )r;   r   r>   r>   r?   cursor   s   zAsyncConnection.cursorAsyncRowFactory[CursorRow]AsyncCursor[CursorRow]c                C  r   r7   r>   )r;   r   r4   r>   r>   r?   r      s   )r   
scrollablewithholdnamer   bool | Noner   AsyncServerCursor[Row]c                C  r   r7   r>   )r;   r   r   r   r   r>   r>   r?   r      s   AsyncServerCursor[CursorRow]c                C  r   r7   r>   )r;   r   r   r4   r   r   r>   r>   r?   r      s   	)r   r4   r   r   AsyncRowFactory[Any] | None)AsyncCursor[Any] | AsyncServerCursor[Any]c                C  sH   |    |s	| j}|r| j| ||||d}n| j| |d}|r"t|_|S )z\
        Return a new `AsyncCursor` to send commands and queries to the connection.
        )r   r4   r   r   r4   )_check_connection_okr4   r2   r1   BINARYformat)r;   r   r   r4   r   r   curr>   r>   r?   r      s   )preparer   queryr   rn   Params | Noner   c             
     sR   z|   }|rt|_|j|||dI dH W S  tjy( } z|dd}~ww )z8Execute a query and return a cursor to read its results.)r   N)r   r   r   executer]   rc   rh   )r;   r   rn   r   r   r   rs   r>   r>   r?   r      s   	
zAsyncConnection.executec              	     V   | j 4 I dH  | |  I dH  W d  I dH  dS 1 I dH s$w   Y  dS )z/Commit any pending transaction to the database.N)r:   wait_commit_genrv   r>   r>   r?   r        .zAsyncConnection.commitc              	     r   )z2Roll back to the start of any pending transaction.N)r:   r   _rollback_genrv   r>   r>   r?   r     r   zAsyncConnection.rollbackg      >@rO   rP   floatc                  sL   |   sdS t rtj| j|dtdI dH  dS 	 t| jI dH  dS )a  Cancel the current operation on the connection.

        :param timeout: raise a `~errors.CancellationTimeout` if the
            cancellation request does not succeed within `timeout` seconds.

        Note that a successful cancel attempt on the client is not a guarantee
        that the server will successfully manage to cancel the operation.

        This is a non-blocking version of `~Connection.cancel()` which
        leverages a more secure and improved cancellation feature of the libpq,
        which is only available from version 17.

        If the underlying libpq is older than version 17, the method will fall
        back to using the same implementation of `!cancel()`.
        NrO   rQ   )	_should_cancelr'   has_cancel_safer   ra   _cancel_genrb   r-   cancel)r;   rP   r>   r>   r?   cancel_safe  s   zAsyncConnection.cancel_safe      @c             
     sN   z| j |dI d H  W d S  ty& } ztd| W Y d }~d S d }~ww )NrO   zquery cancellation failed: %s)r   r   re   r   )r;   rP   rs   r>   r>   r?   _try_cancel5  s   zAsyncConnection._try_cancelsavepoint_name
str | Noneforce_rollbackAsyncIterator[AsyncTransaction]c                 C s  t | ||}| jrh|  4 I dH I |4 I dH , |  4 I dH  |V  W d  I dH  n1 I dH s6w   Y  W d  I dH  n1 I dH sKw   Y  W d  I dH  dS 1 I dH saw   Y  dS |4 I dH  |V  W d  I dH  dS 1 I dH sw   Y  dS )a  
        Start a context block with a new transaction or nested transaction.

        :param savepoint_name: Name of the savepoint used to manage a nested
            transaction. If `!None`, one will be chosen automatically.
        :param force_rollback: Roll back the transaction at the end of the
            block even if there were no error (e.g. to try a no-op process).
        :rtype: AsyncTransaction
        N)r%   r5   pipeline)r;   r   r   txr>   r>   r?   transaction;  s   2.zAsyncConnection.transaction)rP   
stop_afterfloat | Noner   AsyncGenerator[Notify, None]c                C s"  |durt  | }t|t}nd}t}d}| j4 I dH g | jj}	 z| jt| j|dI dH }W n tj	yD } z|
dd}~ww |D ]}	t|	j||	j||	j}
|
V  |d7 }qG|duri||krin|rxtt|t   }|dk rxnq#W d  I dH  dS 1 I dH sw   Y  dS )a  
        Yield `Notify` objects as soon as they are received from the database.

        :param timeout: maximum amount of time to wait for notifications.
            `!None` means no timeout.
        :param stop_after: stop after receiving this number of notifications.
            You might actually receive more than this number if more than one
            notifications arrives in the same packet.
        Nr   TrQ   r   g        )r   minrb   r:   r6   	_encodingr   r$   r]   rc   rh   r+   relnamedecodeextrabe_pid)r;   rP   r   deadlinerR   	nreceivedencnsrs   pgnnr>   r>   r?   r$   P  s<   


.zAsyncConnection.notifiesAsyncIterator[AsyncPipeline]c                 C s^  | j 4 I dH  |   | j}|du rt|  }| _W d  I dH  n1 I dH s+w   Y  zQ|4 I dH  |V  W d  I dH  n1 I dH sKw   Y  W |jdkr| j 4 I dH  || ju seJ d| _W d  I dH  dS 1 I dH syw   Y  dS dS |jdkr| j 4 I dH  || ju sJ d| _W d  I dH  w 1 I dH sw   Y  w )z<Context manager to switch the connection into pipeline mode.Nr   )r:   r   r5   r#   level)r;   r   r>   r>   r?   r     s,   ((
.*zAsyncConnection.pipelinerr   	PQGen[RV]rR   r   c                   s   zt j|| jj|dI dH W S  ty@   | jjtkr?| jddI dH  zt j|| jj|dI dH  W   tj	y>   Y  w  w )z
        Consume a generator operating on the connection.

        The function must be used on generators that don't change connection
        fd (i.e. not on connect and reset).
        rQ   Nr   rO   )
r   
wait_asyncr6   socket_INTERRUPTEDtransaction_statusACTIVEr   r]   QueryCanceled)r;   rr   rR   r>   r>   r?   r     s   zAsyncConnection.waitvaluec                 C     	 |  d d S )NTrB   )_no_set_asyncset_autocommitr;   r   r>   r>   r?   _set_autocommit     zAsyncConnection._set_autocommitc              	     X   | j 4 I dH  | | |I dH  W d  I dH  dS 1 I dH s%w   Y  dS )z6Method version of the `~Connection.autocommit` setter.N)r:   r   _set_autocommit_genr   r>   r>   r?   r        .zAsyncConnection.set_autocommitIsolationLevel | Nonec                 C  r   )NTisolation_level)r   set_isolation_levelr   r>   r>   r?   _set_isolation_level  r   z$AsyncConnection._set_isolation_levelc              	     r   )z;Method version of the `~Connection.isolation_level` setter.N)r:   r   _set_isolation_level_genr   r>   r>   r?   r     r   z#AsyncConnection.set_isolation_levelc                 C  r   )NT	read_only)r   set_read_onlyr   r>   r>   r?   _set_read_only  r   zAsyncConnection._set_read_onlyc              	     r   )z5Method version of the `~Connection.read_only` setter.N)r:   r   _set_read_only_genr   r>   r>   r?   r     r   zAsyncConnection.set_read_onlyc                 C  r   )NT
deferrable)r   set_deferrabler   r>   r>   r?   _set_deferrable  r   zAsyncConnection._set_deferrablec              	     r   )z6Method version of the `~Connection.deferrable` setter.N)r:   r   _set_deferrable_genr   r>   r>   r?   r     r   zAsyncConnection.set_deferrableT	attributec                 C  s   t d|d| d)Nz'the zD property is read-only on async connections: please use 'await .set_z()' instead.)AttributeError)r;   r   r>   r>   r?   r     s
   zAsyncConnection._no_set_asyncxid	Xid | strc              	     r   )zO
        Begin a TPC transaction with the given transaction ID `!xid`.
        N)r:   r   _tpc_begin_genr;   r   r>   r>   r?   	tpc_begin  s   .zAsyncConnection.tpc_beginc              
     s   z,| j 4 I dH  | |  I dH  W d  I dH  W dS 1 I dH s&w   Y  W dS  tjyB } ztt|dd}~ww )zV
        Perform the first phase of a transaction started with `tpc_begin()`.
        N)r:   r   _tpc_prepare_genr]   ObjectNotInPrerequisiteStateNotSupportedErrorrF   )r;   rs   r>   r>   r?   tpc_prepare  s   2zAsyncConnection.tpc_prepareXid | str | Nonec              	     Z   | j 4 I dH  | | d|I dH  W d  I dH  dS 1 I dH s&w   Y  dS )z:
        Commit a prepared two-phase transaction.
        NCOMMITr:   r   _tpc_finish_genr   r>   r>   r?   
tpc_commit     .zAsyncConnection.tpc_commitc              	     r   )z=
        Roll back a prepared two-phase transaction.
        NROLLBACKr   r   r>   r>   r?   tpc_rollback  r   zAsyncConnection.tpc_rollback	list[Xid]c              	     s   |    | jj}| jttjd4 I d H }|t I d H  |	 I d H }W d   I d H  n1 I d H s8w   Y  |t
krN| jjtkrN|  I d H  |S )Nr   )
_check_tpcinfor   r   r   r   _from_recordr   _get_recover_queryfetchallIDLEINTRANSr   )r;   statusr   resr>   r>   r?   tpc_recover  s   (zAsyncConnection.tpc_recover)r6   r.   r4   r3   rV   )rE   rF   rB   rG   rC   rH   rD   rI   r4   rJ   r1   rK   rL   r   rM   r   )rM   r   )rx   ry   rz   r{   r|   r}   rM   r~   )rE   rF   rL   r   rM   r   )rM   r~   )r   rG   rM   r   )r   rG   r4   r   rM   r   )
r   rF   r   rG   r   r   r   rG   rM   r   )r   rF   r   rG   r4   r   r   r   r   rG   rM   r   )r   rF   r   rG   r4   r   r   r   r   rG   rM   r   r7   )
r   r   rn   r   r   r   r   rG   rM   r   )rP   r   rM   r~   )NF)r   r   r   rG   rM   r   )rP   r   r   rH   rM   r   )rM   r   )rr   r   rR   r   rM   r   )r   rG   rM   r~   )r   r   rM   r~   )r   r   rM   r~   )r   rF   rM   r~   )r   r   rM   r~   )r   r   rM   r~   )rM   r   ),__name__
__module____qualname____doc____annotations__r   r   r   r   r9   classmethodru   rw   r   r_   r   r	   r   r   r   r   r   r   r   r   r$   r   rb   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  __classcell__r>   r>   r<   r?   r0   >   s   
 
=


	%

2











r0   )Ur  
__future__r   loggingtimer   typesr   typingr   r   r   r   r	   r
   
contextlibr   r@   r   r   r]   r   abcr   r   r   r   r   r   r   _tpcr   rowsr   r   r   r   adaptr   _enumsr   _compatr   rE   r   r    r!   r"   r5   r#   
generatorsr$   r   r%   cursor_asyncr&   _capabilitiesr'   server_cursorr(   _connection_baser)   r*   r+   rW   rY   r,   r-   	threadingpq.abcr.   rb   FormatTEXTr   TransactionStatusr   r   r   CancelledErrorKeyboardInterruptr   	getLoggerre   r0   r>   r>   r>   r?   <module>   sT     $

