o
    ¨Ýjš<  ã                   @   s  d dl mZ d dlmZ d dl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 d dlmZ eƒ ZG d	d
„ d
eƒZdd„ ZG dd„ deƒZG dd„ deƒZG dd„ deƒZeZG dd„ dƒZejD ]Zefdd„Zeeeeeƒƒ qee`[[G dd„ deƒZG dd„ dƒZdS )é    )Údeque)ÚcontextmanagerN)ÚPool)Útimeout)Úhubs)ÚTimer)ÚGreenThreadc                   @   s   e Zd ZdS )ÚConnectTimeoutN)Ú__name__Ú
__module__Ú__qualname__© r   r   úK/var/www/html/chatgpt/venv/lib/python3.10/site-packages/eventlet/db_pool.pyr	      s    r	   c                 C   ó   |   ¡  d S ©N)Úrollback)Úconnr   r   r   Úcleanup_rollback   ó   r   c                       s�   e Zd Zdddddef‡ fdd„	Zdd	„ Zd
d„ Zdd„ Zdd„ Zddd„Z	‡ fdd„Z
ef‡ fdd„	Zeefdd„ƒZdd„ Zdd„ Z‡  ZS )ÚBaseConnectionPoolr   é   é
   é   é   c           
         sN   |sJ ‚|| _ || _|	| _|| _|| _|| _d| _|| _tƒ j	||dd� dS )a  
        Constructs a pool with at least *min_size* connections and at most
        *max_size* connections.  Uses *db_module* to construct new connections.

        The *max_idle* parameter determines how long pooled connections can
        remain idle, in seconds.  After *max_idle* seconds have elapsed
        without the connection being used, the pool closes the connection.

        *max_age* is how long any particular connection is allowed to live.
        Connections that have been open for longer than *max_age* seconds are
        closed, regardless of idle time.  If *max_age* is 0, all connections are
        closed on return to the pool, reducing it to a concurrency limiter.

        *connect_timeout* is the duration in seconds that the pool will wait
        before timing out on connect() to the database.  If triggered, the
        timeout will raise a ConnectTimeout from get().

        The remainder of the arguments are used as parameters to the
        *db_module*'s connection constructor.
        NT)Úmin_sizeÚmax_sizeZorder_as_stack)
Ú
_db_moduleÚ_argsÚ_kwargsÚmax_idleÚmax_ageÚconnect_timeoutÚ_expiration_timerÚcleanupÚsuperÚ__init__)
ÚselfÚ	db_moduler   r   r   r    r!   r#   ÚargsÚkwargs©Ú	__class__r   r   r%      s   zBaseConnectionPool.__init__c              	   C   sè   | j dks
| jdkrdS | jdurt| jddƒsdS z-t ¡ }|  |¡ | jd d | | j }tdd„ | jD ƒƒ}|| | j  }t||ƒ}W n tt	fyV   d| _Y dS w |dkrrt
|tt ¡ jƒj| jg i ƒ| _| j ¡  dS dS )a  Sets up a timer that will call _expire_old_connections when the
        oldest connection currently in the free pool is ready to expire.  This
        is the earliest possible time that a connection could expire, thus, the
        timer will be running as infrequently as possible without missing a
        possible expiration.

        If this function is called when a timer is already scheduled, it does
        nothing.

        If max_age or max_idle is 0, _schedule_expiration likewise does nothing.
        r   NZcalledFéÿÿÿÿc                 S   s   g | ]}|d  ‘qS )é   r   )Ú.0Útr   r   r   Ú
<listcomp>Z   s    z;BaseConnectionPool._schedule_expiration.<locals>.<listcomp>)r    r   r"   ÚgetattrÚtimeÚ_expire_old_connectionsÚ
free_itemsÚminÚ
IndexErrorÚ
ValueErrorr   r   r   Zget_hubZgreenletÚswitchÚ_schedule_expirationZschedule)r&   ÚnowZ
idle_delayZoldestZ	age_delayZ
next_delayr   r   r   r9   >   s.   
ÿ
ýÿüz'BaseConnectionPool._schedule_expirationc                    s€   t ˆjƒ}‡ ‡fdd„ˆjD ƒ}‡ ‡fdd„ˆjD ƒ}ˆj ¡  ˆj |¡ ˆ j|t ˆjƒ 8  _|D ]	}ˆj|dd� q4dS )a  Iterates through the open connections contained in the pool, closing
        ones that have remained idle for longer than max_idle seconds, or have
        been in existence for longer than max_age seconds.

        *now* is the current time, as returned by time.time().
        c                    s$   g | ]\}}}ˆ  ˆ ||¡r|‘qS r   ©Ú_is_expired©r.   Ú	last_usedÚ
created_atr   ©r:   r&   r   r   r0   q   s    ýÿz>BaseConnectionPool._expire_old_connections.<locals>.<listcomp>c                    s*   g | ]\}}}ˆ  ˆ ||¡s|||f‘qS r   r;   r=   r@   r   r   r0   v   s    ýÿT©ÚquietN)Úlenr4   ÚclearÚextendÚcurrent_sizeÚ_safe_close)r&   r:   Zoriginal_countZexpiredZnew_freer   r   r@   r   r3   i   s   
þþ
ÿz*BaseConnectionPool._expire_old_connectionsc                 C   s8   | j dks| jdks|| | j ks|| | jkrdS dS )z@Returns true and closes the connection if it's expired.
        r   TF)r   r    )r&   r:   r>   r?   r   r   r   r<   „   s
   zBaseConnectionPool._is_expiredc                 C   s<   d}z|r|j }| ¡  W |S d}W |S  ty   Y |S w )a$  If the connection was wrapped by a subclass of
        BaseConnectionWrapper and is still functional (as determined
        by the __nonzero__, or __bool__ in python3, method), returns
        the unwrapped connection.  If anything goes wrong with this
        process, returns None.
        N)Ú_baseÚ_destroyÚAttributeError)r&   r   Úbaser   r   r   Ú_unwrap_connection�   s   
ýþþz%BaseConnectionPool._unwrap_connectionFc                 C   sT   z|  ¡  W dS  ty   Y dS  ty)   |s&tdt ¡ d  ƒ Y dS Y dS w )zVCloses the (already unwrapped) connection, squelching any
        exceptions.
        zConnection.close raised: %sr-   N)ÚcloserJ   Ú	ExceptionÚprintÚsysÚexc_info)r&   r   rB   r   r   r   rG   Ÿ   s   ÿÿzBaseConnectionPool._safe_closec                    sp   t ƒ  ¡ }|d u rz|  ¡ }W n ty   |  jd8  _‚ w t|tƒr*|\}}}nt ¡ }t|| ƒ}||_	|S )Nr-   )
r$   ÚgetÚcreaterN   rF   Ú
isinstanceÚtupler2   ÚPooledConnectionWrapperÚ_db_pool_created_at)r&   r   Z
_last_usedr?   Úwrappedr*   r   r   rR   «   s   
ú


zBaseConnectionPool.getc              
      sú   t |ddƒ}t ¡ }|  |¡}|  |||¡r | j|dd� d }n5|d urU|tu r+| j}z|r2||ƒ W n! tyO } ztd||f ƒ d }W Y d }~n
d }~w   d }‚ |d urct	ƒ  
|||f¡ n|  ¡ dkrpt	ƒ  
d ¡ n|  jd8  _|  ¡  d S )NrW   r   FrA   zWARNING: cleanup %s raised: %sr-   )r1   r2   rL   r<   rG   Ú_MISSINGr#   rN   rO   r$   ÚputZwaitingrF   r9   )r&   r   r#   r?   r:   Úer*   r   r   rZ   É   s4   
€€zBaseConnectionPool.putc              
   c   s6   � |   ¡ }z|V  W | j||d� d S | j||d� w )N)r#   )rR   rZ   )r&   r#   r   r   r   r   Úitemï   s
   €"zBaseConnectionPool.itemc                 C   s`   | j r| j  ¡  | jtƒ }| _|D ]}t|tƒr|d n|}| j|dd� |  jd8  _qdS )zuClose all connections that this pool still holds a reference to,
        and removes all references to them.
        é   TrA   r-   N)r"   Úcancelr4   r   rT   rU   rG   rF   )r&   r4   r\   r   r   r   r   rD   ÷   s   
üzBaseConnectionPool.clearc                 C   r   r   )rD   ©r&   r   r   r   Ú__del__  r   zBaseConnectionPool.__del__)F)r
   r   r   r   r%   r9   r3   r<   rL   rG   rR   rY   rZ   r   r\   rD   r`   Ú__classcell__r   r   r*   r   r      s"    ü%+	
&r   c                   @   ó$   e Zd ZdZdd„ Zedd„ ƒZdS )ÚTpooledConnectionPoolzZA pool which gives out :class:`~eventlet.tpool.Proxy`-based database
    connections.
    c                 C   ó0   t   ¡ }||| j| j| jg| j¢R i | j¤ŽfS r   ©r2   Úconnectr   r!   r   r   ©r&   r:   r   r   r   rS     ó   ÿÿÿzTpooledConnectionPool.createc                 O   sX   t  |tƒ ¡}zddlm} |j|jg|¢R i |¤Ž}|j|dd�W | ¡  S | ¡  w )Nr   )Útpool)Úcursor)Zautowrap_names)	r   ÚTimeoutr	   Úeventletri   Úexecuterf   ZProxyr^   )Úclsr'   r!   r(   Úkwr/   ri   r   r   r   r   rf     s   zTpooledConnectionPool.connectN©r
   r   r   Ú__doc__rS   Úclassmethodrf   r   r   r   r   rc     s
    rc   c                   @   rb   )ÚRawConnectionPoolz7A pool which gives out plain database connections.
    c                 C   rd   r   re   rg   r   r   r   rS   !  rh   zRawConnectionPool.createc                 O   s4   t  |tƒ ¡}z|j|i |¤ŽW | ¡  S | ¡  w r   )r   rk   r	   rf   r^   )rn   r'   r!   r(   ro   r/   r   r   r   rf   &  s   zRawConnectionPool.connectNrp   r   r   r   r   rs     s
    rs   c                   @   s0   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	Zd
S )ÚGenericConnectionWrapperc                 C   s
   || _ d S r   )rH   )r&   Úbaseconnr   r   r   r%   4  ó   
z!GenericConnectionWrapper.__init__c                 C   ó
   | j  ¡ S r   )rH   Ú	__enter__r_   r   r   r   rx   =  rv   z"GenericConnectionWrapper.__enter__c                 C   s   | j  |||¡S r   )rH   Ú__exit__)r&   ÚexcÚvalueÚtbr   r   r   ry   @  s   z!GenericConnectionWrapper.__exit__c                 C   rw   r   )rH   Ú__repr__r_   r   r   r   r}   C  rv   z!GenericConnectionWrapper.__repr__)!Zaffected_rowsZ
autocommitÚbeginZchange_userZcharacter_set_namerM   Úcommitrj   Zdump_debug_infoÚerrnoÚerrorZerrorhandlerZget_server_infoZ	insert_idÚliteralZpingÚqueryr   Z	select_dbZserver_capabilitiesZset_character_setZset_isolation_levelZset_server_optionZset_sql_modeZshow_warningsÚshutdownZsqlstateÚstatZstore_resultZstring_literalÚ	thread_idZ
use_resultZwarning_countN)r
   r   r   r%   rx   ry   r}   Ú_proxy_funcsr   r   r   r   rt   3  s    	rt   c                    s&   ‡ fdd„}ˆ |_ ˆ |_dˆ  |_|S )Nc                    s   t | jˆ ƒ|i |¤ŽS r   )r1   rH   )r&   r(   r)   ©Ú
_proxy_funr   r   Ú_proxy_methodn  s   z_wrapper.<locals>._proxy_methodzGenericConnectionWrapper.)Ú	func_namer
   r   )r‰   rŠ   r   rˆ   r   Ú_wrapperm  s
   
rŒ   c                       sD   e Zd ZdZ‡ fdd„Zdd„ ZeZdd„ Zdd	„ Zd
d„ Z	‡  Z
S )rV   zçA connection wrapper where:
    - the close method returns the connection to the pool instead of closing it directly
    - ``bool(conn)`` returns a reasonable value
    - returns itself to the pool if it gets garbage collected
    c                    s   t ƒ  |¡ || _d S r   )r$   r%   Ú_pool)r&   ru   Úpoolr*   r   r   r%   �  s   
z PooledConnectionWrapper.__init__c                 C   s   t | dƒo	t| jƒS )NrH   )ÚhasattrÚboolrH   r_   r   r   r   Ú__nonzero__…  s   z#PooledConnectionWrapper.__nonzero__c                 C   s&   d | _ z| `W d S  ty   Y d S w r   )r�   rH   rJ   r_   r   r   r   rI   Š  s   
ÿz PooledConnectionWrapper._destroyc                 C   s"   | r| j r| j  | ¡ |  ¡  dS )z–Return the connection to the pool, and remove the
        reference to it so that you can't use it again through this
        wrapper object.
        N)r�   rZ   rI   r_   r   r   r   rM   ‘  s   
zPooledConnectionWrapper.closec                 C   s   d S r   r   r_   r   r   r   r`   š  s   zPooledConnectionWrapper.__del__)r
   r   r   rq   r%   r‘   Ú__bool__rI   rM   r`   ra   r   r   r*   r   rV   z  s    	rV   c                   @   s,   e Zd ZdZ	d	dd„Zdd„ Zdd„ ZdS )
ÚDatabaseConnectorzr
    This is an object which will maintain a collection of database
    connection pools on a per-host basis.
    Nc                 O   s@   |sJ ‚|| _ | j du rt| _ || _|| _|| _|| _i | _dS )z±constructor
        *module*
            Database module to use.
        *credentials*
            Mapping of hostname to connect arguments (e.g. username and password)
        N)Ú_conn_pool_classÚConnectionPoolÚ_moduler   r   Ú_credentialsÚ
_databases)r&   ÚmoduleÚcredentialsZ	conn_poolr(   r)   r   r   r   r%   ¦  s   

zDatabaseConnector.__init__c                 C   s"   || j v r
| j | S | j  dd ¡S )NÚdefault)r—   rR   )r&   Úhostr   r   r   Úcredentials_for¹  s   

z!DatabaseConnector.credentials_forc                 C   sl   ||f}|| j vr1| j ¡ }||d< ||d< | |  |¡¡ | j| jg| j¢R i |¤Ž}|| j |< | j | S )z@Returns a ConnectionPool to the target host and schema.
        Údbrœ   )r˜   r   ÚcopyÚupdater�   r”   r–   r   )r&   rœ   ZdbnameÚkeyZ
new_kwargsZdbpoolr   r   r   rR   ¿  s   

ÿÿÿ

zDatabaseConnector.getr   )r
   r   r   rq   r%   r�   rR   r   r   r   r   r“      s    
ÿr“   )Úcollectionsr   Ú
contextlibr   rP   r2   Zeventlet.poolsr   rl   r   r   Zeventlet.hubs.timerr   Zeventlet.greenthreadr   ÚobjectrY   rN   r	   r   r   rc   rs   r•   rt   r‡   r‰   rŒ   ÚsetattrrV   r“   r   r   r   r   Ú<module>   s4     q
8&