U
    ڲgI=                     @  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@mAZA erddlBmCZC dZDejEjFZFejEjGZGejHjIZIejHjJZJejHjKZKeLZMeNdZOG dd  d e=e! ZPdS )!z*
Psycopg connection object (sync version)
    )annotationsN)	monotonic)TracebackType)Any	GeneratorIteratorcastoverloadTYPE_CHECKING)contextmanager   )pq)errors)waiting)AdaptContextConnDict	ConnParamParamsPQGenQueryRV)Xid)Row
RowFactory	tuple_rowargs_row)AdaptersMap)IsolationLevel)Self)make_conninfoconninfo_to_dict)conninfo_attemptstimeout_from_conninfo)Pipeline)notifies)Transaction)Cursor)capabilities)ServerCursor)BaseConnection	CursorRowNotify)Lock)PGconng?psycopgc                      s
  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dd fddZ	e
ddddddddddddddddddZddd d!Zd"d#d$d%d&d'd(Ze
dd)d*d+d,d-Zd%dd.d/Zedd0dd1d2d3d4Zedd0dd5d6d7d8d4Zedddd9ddd:dd;d<d=d4Zedddd9ddd5d:dd>d?d@d4ZddddddAdddBd:ddCd?dDd4ZddddEdFdGd:dd1dHdIdJZd%ddKdLZd%ddMdNZdOdPdQd%dRdSdTZdUdPdQd%dRdVdWZeddXddYdZd[d\Zddd]d^dd_d`dadbZedcddddeZefdfd^dgdhdidjZdd%dkdldmZdd%dkdndoZdpd%dkdqdrZdpd%dkdsdtZ d:d%dkdudvZ!d:d%dkdwdxZ"d:d%dkdydzZ#d:d%dkd{d|Z$d}d%d~ddZ%d%dddZ&ddd%d~ddZ'ddd%d~ddZ(ddddZ)  Z*S )
Connectionz3
    Wrapper for a connection to the database.
    r.   ztype[Cursor[Row]]cursor_factoryztype[ServerCursor[Row]]server_cursor_factoryzRowFactory[Row]row_factoryzPipeline | None	_pipeliner-   )pgconnr2   c                   s*   t  | || _t | _t| _t| _d S N)	super__init__r2   r,   lockr&   r0   r(   r1   )selfr4   r2   	__class__ 6/tmp/pip-unpacked-wheel-b_ea6rx_/psycopg/connection.pyr7   D   s
    zConnection.__init__ F   N)
autocommitprepare_thresholdcontextr2   r0   strboolz
int | NonezAdaptContext | NonezRowFactory[Row] | Noneztype[Cursor[Row]] | Noner   r   )conninfor@   rA   rB   r2   r0   kwargsreturnc                K  s  | j |f|}t|}	d}
t|}|D ]}z*td
|}| j||	d}tj|td}
W n\ tj	k
r } z<t
|dkrtd|d|d|d	t| |}W 5 d}~X Y q&X  qq&|
s|st|dt||
_|r||
_|r||
_|rt|j|
_||
_|
S )zV
        Connect to a database server and return a new `Connection` instance.
        Nr>   timeoutintervalr   z=connection attempt failed: host: %r port: %r, hostaddr %r: %shostportZhostaddr)r>   )_get_connection_paramsr"   r!   r   Z_connect_genr   	wait_conn_WAIT_INTERVALe_NO_TRACEBACKlenloggerdebuggetrC   AssertionErrorwith_tracebackrD   Z_autocommitr2   r0   r   adaptersZ	_adaptersrA   )clsrE   r@   rA   rB   r2   r0   rF   paramsrI   rvattemptsattemptgenexZlast_exr<   r<   r=   connectO   s@    


zConnection.connect)rG   c                 C  s   | S r5   r<   r9   r<   r<   r=   	__enter__   s    zConnection.__enter__ztype[BaseException] | NonezBaseException | NonezTracebackType | NoneNone)exc_typeexc_valexc_tbrG   c              
   C  sn   | j r
d S |rNz|   W qV tk
rJ } ztd| | W 5 d }~X Y qVX n|   t| dd sj|   d S )Nz#error ignored in rollback on %s: %s_pool)closedrollback	ExceptionrT   warningcommitgetattrclose)r9   re   rf   rg   Zexc2r<   r<   r=   __exit__   s    "zConnection.__exit__r   r   )rE   rF   rG   c                 K  s   t |f|S )z3Manipulate connection parameters before connecting.)r    )rZ   rE   rF   r<   r<   r=   rN      s    z!Connection._get_connection_paramsc                 C  s   | j r
dS d| _| j  dS )zClose the database connection.NT)ri   _closedr4   finishrb   r<   r<   r=   ro      s    zConnection.close)binaryzCursor[Row])rs   rG   c                C  s   d S r5   r<   )r9   rs   r<   r<   r=   cursor   s    zConnection.cursorzRowFactory[CursorRow]zCursor[CursorRow])rs   r2   rG   c                C  s   d S r5   r<   )r9   rs   r2   r<   r<   r=   rt      s    )rs   
scrollablewithholdzbool | NonezServerCursor[Row])namers   ru   rv   rG   c                C  s   d S r5   r<   )r9   rw   rs   ru   rv   r<   r<   r=   rt      s    zServerCursor[CursorRow])rw   rs   r2   ru   rv   rG   c                C  s   d S r5   r<   )r9   rw   rs   r2   ru   rv   r<   r<   r=   rt      s    	)rs   r2   ru   rv   zRowFactory[Any] | NonezCursor[Any] | ServerCursor[Any]c                C  sH   |    |s| j}|r,| j| ||||d}n| j| |d}|rDt|_|S )zW
        Return a new `Cursor` to send commands and queries to the connection.
        )rw   r2   ru   rv   r2   )_check_connection_okr2   r1   r0   BINARYformat)r9   rw   rs   r2   ru   rv   curr<   r<   r=   rt      s    )preparers   r   zParams | None)queryr[   r}   rs   rG   c             
   C  sX   z$|   }|rt|_|j|||dW S  tjk
rR } z|dW 5 d}~X Y nX dS )z8Execute a query and return a cursor to read its results.)r}   N)rt   rz   r{   executerQ   rR   rX   )r9   r~   r[   r}   rs   r|   r`   r<   r<   r=   r      s    	zConnection.executec              	   C  s$   | j  | |   W 5 Q R X dS )z/Commit any pending transaction to the database.N)r8   waitZ_commit_genrb   r<   r<   r=   rm      s    zConnection.commitc              	   C  s$   | j  | |   W 5 Q R X dS )z2Roll back to the start of any pending transaction.N)r8   r   Z_rollback_genrb   r<   r<   r=   rj     s    zConnection.rollbackg      >@rH   float)rI   rG   c                C  s8   |   sdS t r,tj| j|dtd n|   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()`.
        NrH   rJ   )Z_should_cancelr'   Zhas_cancel_safer   rO   Z_cancel_genrP   cancel)r9   rI   r<   r<   r=   cancel_safe  s    
 zConnection.cancel_safe      @c             
   C  sD   z| j |d W n. tk
r> } ztd| W 5 d }~X Y nX d S )NrH   zquery cancellation failed: %s)r   rk   rT   rl   )r9   rI   r`   r<   r<   r=   _try_cancel!  s    zConnection._try_cancelz
str | NonezIterator[Transaction])savepoint_nameforce_rollbackrG   c                 c  sl   t | ||}| jrR|  0 |  |   |V  W 5 Q R X W 5 Q R X W 5 Q R X n| |V  W 5 Q R X 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: Transaction
        N)r%   r3   pipeline)r9   r   r   Ztxr<   r<   r=   transaction'  s    &zConnection.transaction)rI   
stop_afterzfloat | NonezGenerator[Notify, None, None])rI   r   rG   c                c  s   |dk	rt  | }t|t}nd}t}d}| j | jj}z| jt| j|d}W n. tj	k
r } z|
dW 5 d}~X Y nX |D ]0}	t|	j||	j||	j}
|
V  |d7 }q|dk	r||krq|r:tt|t   }|dk r:qq:W 5 Q R X 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   rJ   r   g        )r   minrP   r8   r4   	_encodingr   r$   rQ   rR   rX   r+   ZrelnamedecodeextraZbe_pid)r9   rI   r   deadlinerK   Z	nreceivedencnsr`   Zpgnnr<   r<   r=   r$   <  s4    

 
 
zConnection.notifieszIterator[Pipeline]c                 c  s   | j * |   | j}|dkr,t|  }| _W 5 Q R X z| |V  W 5 Q R X W 5 |jdkr| j  || jksrtd| _W 5 Q R X X dS )z<Context manager to switch the connection into pipeline mode.Nr   )r8   ry   r3   r#   levelrW   )r9   r   r<   r<   r=   r   n  s    
zConnection.pipelinez	PQGen[RV]r   )r_   rK   rG   c                 C  sz   zt j|| jj|dW S  tk
rt   | jjtkrn| jdd zt j|| jj|d W n tj	k
rl   Y nX  Y nX dS )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).
        rJ   r   rH   N)
r   r   r4   socket_INTERRUPTEDtransaction_statusACTIVEr   rQ   ZQueryCanceled)r9   r_   rK   r<   r<   r=   r     s    zConnection.wait)valuerG   c                 C  s   |  | d S r5   )set_autocommitr9   r   r<   r<   r=   _set_autocommit  s    zConnection._set_autocommitc              	   C  s&   | j  | | | W 5 Q R X dS )z6Method version of the `~Connection.autocommit` setter.N)r8   r   Z_set_autocommit_genr   r<   r<   r=   r     s    zConnection.set_autocommitzIsolationLevel | Nonec                 C  s   |  | d S r5   )set_isolation_levelr   r<   r<   r=   _set_isolation_level  s    zConnection._set_isolation_levelc              	   C  s&   | j  | | | W 5 Q R X dS )z;Method version of the `~Connection.isolation_level` setter.N)r8   r   Z_set_isolation_level_genr   r<   r<   r=   r     s    zConnection.set_isolation_levelc                 C  s   |  | d S r5   )set_read_onlyr   r<   r<   r=   _set_read_only  s    zConnection._set_read_onlyc              	   C  s&   | j  | | | W 5 Q R X dS )z5Method version of the `~Connection.read_only` setter.N)r8   r   Z_set_read_only_genr   r<   r<   r=   r     s    zConnection.set_read_onlyc                 C  s   |  | d S r5   )set_deferrabler   r<   r<   r=   _set_deferrable  s    zConnection._set_deferrablec              	   C  s&   | j  | | | W 5 Q R X dS )z6Method version of the `~Connection.deferrable` setter.N)r8   r   Z_set_deferrable_genr   r<   r<   r=   r     s    zConnection.set_deferrablez	Xid | str)xidrG   c              	   C  s&   | j  | | | W 5 Q R X dS )zO
        Begin a TPC transaction with the given transaction ID `!xid`.
        N)r8   r   Z_tpc_begin_genr9   r   r<   r<   r=   	tpc_begin  s    zConnection.tpc_beginc              
   C  s^   z$| j  | |   W 5 Q R X W n4 tjk
rX } ztt|dW 5 d}~X Y nX dS )zV
        Perform the first phase of a transaction started with `tpc_begin()`.
        N)r8   r   Z_tpc_prepare_genrQ   ZObjectNotInPrerequisiteStateZNotSupportedErrorrC   )r9   r`   r<   r<   r=   tpc_prepare  s
    zConnection.tpc_preparezXid | str | Nonec              	   C  s(   | j  | | d| W 5 Q R X dS )z:
        Commit a prepared two-phase transaction.
        ZCOMMITNr8   r   Z_tpc_finish_genr   r<   r<   r=   
tpc_commit  s    zConnection.tpc_commitc              	   C  s(   | j  | | d| W 5 Q R X dS )z=
        Roll back a prepared two-phase transaction.
        ZROLLBACKNr   r   r<   r<   r=   tpc_rollback  s    zConnection.tpc_rollbackz	list[Xid]c              	   C  sd   |    | jj}| jttjd}|t  |	 }W 5 Q R X |t
kr`| jjtkr`|   |S )Nrx   )Z
_check_tpcinfor   rt   r   r   Z_from_recordr   Z_get_recover_queryZfetchallIDLEINTRANSrj   )r9   statusr|   resr<   r<   r=   tpc_recover  s    zConnection.tpc_recover)r>   )r>   )N)NF)N)N)+__name__
__module____qualname____doc____annotations__r   r   r   r   r7   classmethodra   rc   rp   rN   ro   r	   rt   r   rm   rj   r   r   r   r   r$   r   rP   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r<   r<   r:   r=   r/   8   s   
 "3
	 %     2
r/   )Qr   
__future__r   loggingtimer   typesr   typingr   r   r   r   r	   r
   
contextlibr   r>   r   r   rQ   r   abcr   r   r   r   r   r   r   Z_tpcr   Zrowsr   r   r   r   Zadaptr   Z_enumsr   _compatr   rE   r   r    r!   r"   r3   r#   
generatorsr$   r   r%   rt   r&   Z_capabilitiesr'   Zserver_cursorr(   Z_connection_baser)   r*   r+   	threadingr,   Zpq.abcr-   rP   ZFormatZTEXTrz   ZTransactionStatusr   r   r   KeyboardInterruptr   	getLoggerrT   r/   r<   r<   r<   r=   <module>   sH    $
