o
    "4g\                     @  s  U d Z ddlmZ ddlZddlZddlmZmZmZm	Z	 ddl
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 ddlmZ ddlmZmZmZ ddl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* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 e	rddl5m6Z6m7Z7 ddl8m9Z9 e*dZ:ej;j<Z<ej;j=Z=ej>j?Z?ej>j@Z@ejAjBZBejAjCZCejAjDZDejEjFZFejEjGZGe2H ZIeJdZKG dd deZLdeL_MeejNgdf ZOdePd < eeLgdf ZQdePd!< G d"d# d#ee! ZRdS )$z
psycopg connection objects
    )annotationsN)CallableGeneric
NamedTupleTYPE_CHECKING)refReferenceType)warn)partial   )pq)errors)postgres)
generators)PQGen	PQGenConnQuery)
ComposableSQL)Xid)Row)AdaptersMap)IsolationLevel)LiteralStringSelf	TypeAliasTypeVar)connection_summary)BasePipeline)PrepareManager)capabilities)ConnectionInfo)PGconnPGresult)BasePool	CursorRowpsycopgc                   @  s.   e Zd ZU dZded< 	 ded< 	 ded< dS )Notifyz8An asynchronous notification received from the database.strchannelpayloadintpidN)__name__
__module____qualname____doc____annotations__ r2   r2   a/var/www/html/authentication-server/venv/lib/python3.10/site-packages/psycopg/_connection_base.pyr'   ;   s   
 r'   r   NoticeHandlerNotifyHandlerc                   @  s  e Zd ZdZejZejZejZejZej	Z	ej
Z
ejZejZejZejZdddZddd	ZdddZedddZedddZedddZejdddZdddZdddZedddZejdddZddd Zdd!d"Zedd$d%Zejdd&d%Zdd'd(Zdd)d*Zedd+d,Zejdd-d,Zdd.d/Z dd0d1Z!dd3d4Z"edd6d7Z#edd9d:Z$edd<d=Z%dd?d@Z&ddAdBZ'ddCdDZ(ddHdIZ)ddLdMZ*ddNdOZ+e,ddTdUZ-ddWdXZ.ddYdZZ/e,dd]d^Z0edd`daZ1e1jddbdaZ1eddcddZ2e2jddeddZ2e3	fddgdhddkdlZ4e5fddrdsZ6ddvdwZ7ddxdyZ8ddzd{Z9dd}d~Z:dddZ;dddZ<dddZ=dddZ>dddZ?dddZ@dddZAdS )BaseConnectionz
    Base class for different types of connections.

    Share common functionalities such as access to the wrapped PGconn, but
    allow different interfaces (sync/async).
    pgconnr"   c                 C  s   || _ d| _d | _g | _g | _d| _d| _t | _d | _	t
| }ttj||_ttj||_|  d | _|  d | _d | _d | _d| _d S )NFr       )r7   _autocommit	_adapters_notice_handlers_notify_handlers_num_transactions_closedr   	_prepared_tpcr   r
   r6   _notice_handlernotice_handler_notify_handlernotify_handler	_pipeline_isolation_level
_read_only_deferrable_begin_statement)selfr7   wselfr2   r2   r3   __init__b   s&   
zBaseConnection.__init__returnNonec                 C  s<   t | dsd S | jrd S t | drd S td|  dt d S )Nr7   _poolzconnection zV was deleted while still open. Please use 'with' or '.close()' to close the connection)hasattrclosedr	   ResourceWarningrJ   r2   r2   r3   __del__   s   


zBaseConnection.__del__r(   c                 C  s>   | j j d| j j }t| j}d| d| dt| ddS )N.< z at 0xx>)	__class__r.   r/   r   r7   id)rJ   clsinfor2   r2   r3   __repr__   s   
zBaseConnection.__repr__boolc                 C  s   | j jtkS )z$`!True` if the connection is closed.)r7   statusBADrS   r2   r2   r3   rQ      s   zBaseConnection.closedc                 C  s   | j jtko	| j S )z
        `!True` if the connection was interrupted.

        A broken connection is always `closed`, but wasn't closed in a clean
        way, such as using `close()` or a `!with` block.
        )r7   r`   ra   r>   rS   r2   r2   r3   broken   s   zBaseConnection.brokenc                 C     | j S )z'The autocommit state of the connection.)r9   rS   r2   r2   r3   
autocommit   s   zBaseConnection.autocommitvaluec                 C     |  | d S N)_set_autocommitrJ   re   r2   r2   r3   rd         c                 C     t rg   NotImplementedErrorri   r2   r2   r3   rh         zBaseConnection._set_autocommitPQGen[None]c                 c  s     |  dE d H  t|| _d S )Nrd   )_check_intrans_genr_   r9   ri   r2   r2   r3   _set_autocommit_gen   s   z"BaseConnection._set_autocommit_genIsolationLevel | Nonec                 C  rc   )zX
        The isolation level of the new transactions started on the connection.
        )rF   rS   r2   r2   r3   isolation_level      zBaseConnection.isolation_levelc                 C  rf   rg   )_set_isolation_levelri   r2   r2   r3   rs      rj   c                 C  rk   rg   rl   ri   r2   r2   r3   ru      rn   z#BaseConnection._set_isolation_levelc                 c  2    |  dE d H  |d urt|nd | _d| _d S )Nrs   r8   )rp   r   rF   rI   ri   r2   r2   r3   _set_isolation_level_gen      
z'BaseConnection._set_isolation_level_genbool | Nonec                 C  rc   )zX
        The read-only state of the new transactions started on the connection.
        )rG   rS   r2   r2   r3   	read_only   rt   zBaseConnection.read_onlyc                 C  rf   rg   )_set_read_onlyri   r2   r2   r3   rz      rj   c                 C  rk   rg   rl   ri   r2   r2   r3   r{      rn   zBaseConnection._set_read_onlyc                 c  rv   )Nrz   r8   )rp   r_   rG   rI   ri   r2   r2   r3   _set_read_only_gen   rx   z!BaseConnection._set_read_only_genc                 C  rc   )zY
        The deferrable state of the new transactions started on the connection.
        )rH   rS   r2   r2   r3   
deferrable   rt   zBaseConnection.deferrablec                 C  rf   rg   )_set_deferrableri   r2   r2   r3   r}      rj   c                 C  rk   rg   rl   ri   r2   r2   r3   r~      rn   zBaseConnection._set_deferrablec                 c  rv   )Nr}   r8   )rp   r_   rH   rI   ri   r2   r2   r3   _set_deferrable_gen   rx   z"BaseConnection._set_deferrable_gen	attributec                 c  sr    | j j}|tkr| jr| j E d H  | j j}|tkr7| jr(td|dtd|dt	|j
 d S )Nzcan't change z2 now: connection.transaction() context in progressz' now: connection in transaction status )r7   transaction_statusIDLErE   	_sync_genr=   eProgrammingErrorr   TransactionStatusname)rJ   r   r`   r2   r2   r3   rp      s    

z!BaseConnection._check_intrans_genr!   c                 C  s
   t | jS )z>A `ConnectionInfo` attribute to inspect connection properties.)r!   r7   rS   r2   r2   r3   r]     s   
zBaseConnection.infor   c                 C  s   | j s	ttj| _ | j S rg   )r:   r   r   adaptersrS   r2   r2   r3   r     s   zBaseConnection.adaptersBaseConnection[Row]c                 C  s   | S rg   r2   rS   r2   r2   r3   
connection     zBaseConnection.connectionr+   c                 C     | j jS )zReturn the file descriptor of the connection.

        This function allows to use the connection as file-like object in
        functions waiting for readiness, such as the ones defined in the
        `selectors` module.
        )r7   socketrS   r2   r2   r3   fileno  s   zBaseConnection.filenoc                 C  s"   |   r| j }|  dS dS )z/Cancel the current operation on the connection.N)_should_cancelr7   
get_cancelcancel)rJ   cr2   r2   r3   r   "  s   
zBaseConnection.cancelc                 C  s(   | j rdS | jr| jd rtddS )zhCheck whether the current command should actually be cancelled when
        invoking cancel*().
        Fr   z=cancel() cannot be used with a prepared two-phase transactionT)rQ   r@   r   r   rS   r2   r2   r3   r   (  s   zBaseConnection._should_canceltimeoutfloatPQGenConn[None]c                c  s,    | j  }|  tj||dE d H  d S )Nr   )r7   cancel_connstartr   r   )rJ   r   r   r2   r2   r3   _cancel_gen7  s   
zBaseConnection._cancel_gencallbackr4   c                 C     | j | dS )z
        Register a callable to be invoked when a notice message is received.

        :param callback: the callback to call upon message received.
        :type callback: Callable[[~psycopg.errors.Diagnostic], None]
        N)r;   appendrJ   r   r2   r2   r3   add_notice_handler<     z!BaseConnection.add_notice_handlerc                 C  r   )z
        Unregister a notice message callable previously registered.

        :param callback: the callback to remove.
        :type callback: Callable[[~psycopg.errors.Diagnostic], None]
        N)r;   remover   r2   r2   r3   remove_notice_handlerE  r   z$BaseConnection.remove_notice_handlerrK   "ReferenceType[BaseConnection[Row]]resr#   c                 C  sr   |  }|r|j s
d S t||jj}|j D ]!}z|| W q ty6 } ztd|| W Y d }~qd }~ww d S )Nz)error processing notice callback '%s': %s)r;   r   
Diagnosticr7   	_encoding	Exceptionlogger	exception)rK   r   rJ   diagcbexr2   r2   r3   rA   N  s   

zBaseConnection._notice_handlerr5   c                 C  r   )z
        Register a callable to be invoked whenever a notification is received.

        :param callback: the callback to call upon notification received.
        :type callback: Callable[[~psycopg.Notify], None]
        N)r<   r   r   r2   r2   r3   add_notify_handler]  r   z!BaseConnection.add_notify_handlerc                 C  r   )z
        Unregister a notification callable previously registered.

        :param callback: the callback to remove.
        :type callback: Callable[[~psycopg.Notify], None]
        N)r<   r   r   r2   r2   r3   remove_notify_handlerf  r   z$BaseConnection.remove_notify_handlerpgnpq.PGnotifyc                 C  sR   |  }|r|j s
d S |jj}t|j||j||j}|j D ]}|| q d S rg   )r<   r7   r   r'   relnamedecodeextrabe_pid)rK   r   rJ   encnr   r2   r2   r3   rC   o  s   


zBaseConnection._notify_handler
int | Nonec                 C  r   )a&  
        Number of times a query is executed before it is prepared.

        - If it is set to 0, every query is prepared the first time it is
          executed.
        - If it is set to `!None`, prepared statements are disabled on the
          connection.

        Default value: 5
        r?   prepare_thresholdrS   r2   r2   r3   r   |  s   z BaseConnection.prepare_thresholdc                 C  s   || j _d S rg   r   ri   r2   r2   r3   r     s   c                 C  s   | j j}|tjkr|S dS )z
        Maximum number of prepared statements on the connection.

        `!None` means no max number of prepared statements. The default value
        is 100.
        N)r?   prepared_maxsysmaxsize)rJ   rvr2   r2   r3   r     s   zBaseConnection.prepared_maxc                 C  s   |d u rt j}|| j_d S rg   )r   r   r?   r   ri   r2   r2   r3   r     s    g        r   conninfoPQGenConn[Self]c                c  s"    t j||dE dH }| |}|S )z?Generator to connect to the database and create a new instance.r   N)r   connect)r\   r   r   r7   connr2   r2   r3   _connect_gen  s   zBaseConnection._connect_gencommandr   result_format	pq.FormatPQGen[PGresult | None]c                 c  s   |    t|tr|| jj}n
t|tr|| }| jr9t	| jj
|d|d}| jj| | jjd dS |tkrD| j| n	| jj
|d|d t| jE dH d }|jtkr|jtkr|jtkrptj|| jjdtdt|jj d| |S )z
        Generator to send a command and receive the result to the backend.

        Only used to implement internal commands such as "commit", with eventual
        arguments bound client-side. The cursor can do more complex stuff.
        N)r   encodingunexpected result z from command )_check_connection_ok
isinstancer(   encoder7   r   r   as_bytesrE   r
   send_query_paramscommand_queuer   result_queueTEXT
send_queryr   executer`   
COMMAND_OK	TUPLES_OKFATAL_ERRORr   error_from_resultInterfaceErrorr   
ExecStatusr   r   )rJ   r   r   cmdresultr2   r2   r3   _exec_command  s:   	



zBaseConnection._exec_commandr   bytes | Nonec                 c  s    |du st s|durd| nd}| |E dH  dS |   | jr9t| jj|}| jj| | jj	d dS | j| t
| jE dH d }|jtkrk|jtkr]tj|| jjdtdt|jj ddS )ae  
        Deallocate one, or all, prepared statement in the session.

        ``name == None`` stands for DEALLOCATE ALL.

        If possible, use protocol-level commands; otherwise use SQL statements.

        Note that PgBouncer doesn't support DEALLOCATE name, but it supports
        protocol-level Close from 1.21 and DEALLOCATE ALL from 1.22.
        Ns   DEALLOCATE s   DEALLOCATE ALLr   r   r   z0 from sending closing prepared statement message)_HAS_SEND_CLOSEr   r   rE   r
   r7   send_close_preparedr   r   r   r   r   r`   r   r   r   r   r   r   r   r   r   )rJ   r   stmtr   r   r2   r2   r3   _deallocate  s.   

zBaseConnection._deallocatec                 C  s:   | j jtkrd S | j jtkrtdtd| j j )Nzthe connection is closedz7cannot execute operations: the connection is in status )r7   r`   OKra   r   OperationalErrorr   rS   r2   r2   r3   r     s   
z#BaseConnection._check_connection_okc                 c  sN    | j rdS | jjtkrdS | |  E dH  | jr%| j E dH  dS dS )z.Generator to start a transaction if necessary.N)r9   r7   r   r   r   _get_tx_start_commandrE   r   rS   r2   r2   r3   _start_query  s   zBaseConnection._start_querybytesc                 C  s   | j r| j S dg}| jd ur$t| j}|d ||jdd  | jd ur3|| jr0dnd | jd urB|| jr?dnd d		|| _ | j S )
Ns   BEGINs   ISOLATION LEVEL_rW   s	   READ ONLYs
   READ WRITEs
   DEFERRABLEs   NOT DEFERRABLE    )
rI   rs   r   r   r   replacer   rz   r}   join)rJ   partsvalr2   r2   r3   r     s   




z$BaseConnection._get_tx_start_commandc                 c  s`    | j r	td| jrtd| jjtkrdS | dE dH  | jr.| j	 E dH  dS dS )z-Generator implementing `Connection.commit()`.zExplicit commit() forbidden within a Transaction context. (Transaction will be automatically committed on successful exit from context.)z6commit() cannot be used during a two-phase transactionNs   COMMIT)
r=   r   r   r@   r7   r   r   r   rE   r   rS   r2   r2   r3   _commit_gen2  s   zBaseConnection._commit_genc                 c  s    | j r	td| jrtd| jr| j E dH  | jjtkr$dS | 	dE dH  | j
  | j
| E dH  | jrG| j E dH  dS dS )z/Generator implementing `Connection.rollback()`.zExplicit rollback() forbidden within a Transaction context. (Either raise Rollback() or allow an exception to propagate out of the context.)z8rollback() cannot be used during a two-phase transactionNs   ROLLBACK)r=   r   r   r@   rE   r   r7   r   r   r   r?   clearmaintain_genrS   r2   r2   r3   _rollback_genF  s&   
zBaseConnection._rollback_gen	format_idgtridbqualr   c                 C  s   |    t|||S )aL  
        Returns a `Xid` to pass to the `!tpc_*()` methods of this connection.

        The argument types and constraints are explained in
        :ref:`two-phase-commit`.

        The values passed to the method will be available on the returned
        object as the members `~Xid.format_id`, `~Xid.gtrid`, `~Xid.bqual`.
        )
_check_tpcr   
from_parts)rJ   r   r   r   r2   r2   r3   xida  s   
zBaseConnection.xidr   	Xid | strc                 c  sx    |    t|tst|}| jjtkr#tdt	
| jjj | jr+td|df| _| |  E d H  d S )Nz8can't start two-phase transaction: connection in status z3can't use two-phase transactions in autocommit modeF)r   r   r   from_stringr7   r   r   r   r   r   r   r   r9   r@   r   r   rJ   r   r2   r2   r3   _tpc_begin_genn  s    


zBaseConnection._tpc_begin_genc                 c  sv    | j s	td| j d rtd| j d }|df| _ | tdt|E d H  | jr9| j E d H  d S d S )Nz='tpc_prepare()' must be called inside a two-phase transactionr   zF'tpc_prepare()' cannot be used during a prepared two-phase transactionr   TzPREPARE TRANSACTION {})	r@   r   r   r   r   formatr(   rE   r   r   r2   r2   r3   _tpc_prepare_gen  s   


zBaseConnection._tpc_prepare_genactionr   Xid | str | Nonec                 c  s    d|   d}|d u r| jst| d| jd }n| jr)t| dt|ts3t|}| jrQ| jd sQt| d|   d}d | _| E d H  d S | t	d	
t	|t|E d H  d | _d S )
Ntpc_z()z? without xid must must be called inside a two-phase transactionr   z= with xid must must be called outside a two-phase transactionr   r   _genz{} PREPARED {})lowerr@   r   r   r   r   r   getattrr   r   r   r(   )rJ   r   r   fnamemethr2   r2   r3   _tpc_finish_gen  s,   



zBaseConnection._tpc_finish_genc                 C  s   dS )z0Raise NotSupportedError if TPC is not supported.Nr2   rS   r2   r2   r3   r     r   zBaseConnection._check_tpcN)r7   r"   )rM   rN   )rM   r(   )rM   r_   )re   r_   rM   rN   )re   r_   rM   ro   )rM   rr   )re   rr   rM   rN   )re   rr   rM   ro   )rM   ry   )re   ry   rM   rN   )re   ry   rM   ro   )r   r(   rM   ro   )rM   r!   )rM   r   )rM   r   )rM   r+   )r   r   rM   r   )r   r4   rM   rN   )rK   r   r   r#   rM   rN   )r   r5   rM   rN   )rK   r   r   r   rM   rN   )rM   r   )re   r   rM   rN   )r   )r   r(   r   r   rM   r   )r   r   r   r   rM   r   )r   r   rM   ro   )rM   ro   )rM   r   )r   r+   r   r(   r   r(   rM   r   )r   r   rM   ro   )r   r   r   r   rM   ro   )Br-   r.   r/   r0   r   WarningErrorr   DatabaseError	DataErrorr   IntegrityErrorInternalErrorr   NotSupportedErrorrL   rT   r^   propertyrQ   rb   rd   setterrh   rq   rs   ru   rw   rz   r{   r|   r}   r~   r   rp   r]   r   r   r   r   r   r   r   r   staticmethodrA   r   r   rC   r   r   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r  r   r2   r2   r2   r3   r6   N   s    

#
	










	



		

		
	
.
'







r6   )Sr0   
__future__r   r   loggingtypingr   r   r   r   weakrefr   r   warningsr	   	functoolsr
   r   r   r   r   r   r   abcr   r   r   sqlr   r   r@   r   rowsr   adaptr   _enumsr   _compatr   r   r   r   pq.miscr   rE   r   
_preparingr   _capabilitiesr    _connection_infor!   pq.abcr"   r#   psycopg_pool.baser$   r%   Formatr   BINARY
ConnStatusr   ra   r   r   r   r   r   r   INTRANShas_send_close_preparedr   	getLoggerr   r'   r.   r   r4   r1   r5   r6   r2   r2   r2   r3   <module>   sX    
