
    i<                        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
e          Zd Z G d de          Z G d de          Z G d de          ZeZ G d d          Zej        D ]ZefdZ eee ee                     e`[[ G d de          Z G d d          ZdS )    )deque)contextmanagerN)Pool)timeout)hubs)Timer)GreenThreadc                       e Zd ZdS )ConnectTimeoutN)__name__
__module____qualname__     ;/usr/local/lib/python3.11/dist-packages/eventlet/db_pool.pyr   r      s        Dr   r   c                 .    |                                   d S N)rollback)conns    r   cleanup_rollbackr      s    MMOOOOOr   c                        e Zd Zdddddef fd	Zd Zd Zd	 Zd
 ZddZ	 fdZ
ef fd	Zeefd            Zd Zd Z xZS )BaseConnectionPoolr      
         c                     |sJ || _         || _        |	| _        || _        || _        || _        d| _        || _        t                      	                    ||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_size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__s             r   r*   zBaseConnectionPool.__init__   sp    4 #
 .!%(XdSSSSSr   c                    | j         dk    s| j        dk    rdS | j        t          | j        dd          sdS 	 t	          j                    }|                     |           | j        d         d         |z
  | j        z   }t          d | j        D                       }||z
  | j         z   }t          ||          }n# t          t          f$ r d| _        Y dS w xY w|dk    r`t          |t          t          j                    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   NcalledFc                     g | ]
}|d          S )   r   ).0ts     r   
<listcomp>z;BaseConnectionPool._schedule_expiration.<locals>.<listcomp>Z   s    8881!A$888r   )r%   r$   r'   getattrtime_expire_old_connections
free_itemsmin
IndexError
ValueErrorr   r	   r   get_hubgreenletswitch_schedule_expirationschedule)r+   now
idle_delayoldest	age_delay
next_delays         r   rB   z'BaseConnectionPool._schedule_expiration>   s_    <1 2 2 F". 6%HH / F	)++C((--- /"-a036$-GJ8888899F#5IZ33JJJ' 	 	 	%)D"FF	
 >>%*:{4<>>CZ7[7[7b+/+Db"&N &ND""++-----	 >s   BB; ;CCc                 j    t           j                  } fd j        D             } fd j        D             } j                                          j                            |            xj        |t           j                  z
  z  c_        |D ]}                     |d           d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                 J    g | ]\  }}}                     ||          | S r   _is_expiredr5   	last_used
created_atr   rD   r+   s       r   r7   z>BaseConnectionPool._expire_old_connections.<locals>.<listcomp>q   sG     = = =+	:tY
;;== = =r   c                 P    g | ]"\  }}}                     ||          |||f#S r   rK   rM   s       r   r7   z>BaseConnectionPool._expire_old_connections.<locals>.<listcomp>v   sU     A A A+	:t##CJ??A
D)A A Ar   TquietN)lenr;   clearextendcurrent_size_safe_close)r+   rD   original_countexpirednew_freer   s   ``    r   r:   z*BaseConnectionPool._expire_old_connectionsi   s    T_--= = = = =/3= = =
A A A A A/3A A A 	x((( 	^c$/.B.BBB 	/ 	/DT....	/ 	/r   c                 n    | j         dk    s'| j        dk    s||z
  | j         k    s||z
  | j        k    rdS dS )z@Returns true and closes the connection if it's expired.
        r   TF)r$   r%   )r+   rD   rN   rO   s       r   rL   zBaseConnectionPool._is_expired   sJ     MQ$,!"3"3?T]22#dl224ur   c                 n    d}	 |r|j         }|                                 nd}n# t          $ r Y nw xY w|S )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   bases      r   _unwrap_connectionz%BaseConnectionPool._unwrap_connection   sW     	 z 	 	 	D	s    % 
22Fc                     	 |                                  dS # t          $ r Y dS t          $ r2 |s,t          dt	          j                    d         z             Y dS Y dS w xY w)zVCloses the (already unwrapped) connection, squelching any
        exceptions.
        zConnection.close raised: %sr4   N)closer_   	Exceptionprintsysexc_info)r+   r   rR   s      r   rW   zBaseConnectionPool._safe_close   s    	KJJLLLLL 	 	 	DD 	K 	K 	K K3s|~~a7HIJJJJJJK K K	Ks    
A 4A A c                 B   t                                                      }|5	 |                                 }n# t          $ r | xj        dz  c_         w xY wt          |t                    r|\  }}}nt          j                    }t          ||           }||_	        |S )Nr4   )
r)   getcreaterd   rV   
isinstancetupler9   PooledConnectionWrapper_db_pool_created_at)r+   r   
_last_usedrO   wrappedr/   s        r   ri   zBaseConnectionPool.get   s    ww{{}} <{{}}   
 !!Q&!! dE"" 	%+/(J
DDJ *$55 '1#s	   : Ac                    t          |dd          }t          j                    }|                     |          }|                     |||          r|                     |d           d }nR|P|t
          u r| j        }	 |r ||           n1# t          $ r!}t          d|d|           d }Y d }~nd }~w d } xY w|%t                      
                    |||f           nJ|                                 dk    r"t                      
                    d            n| xj        dz  c_        |                                  d S )Nrn   r   FrQ   zWARNING: cleanup z	 raised: r4   )r8   r9   ra   rL   rW   _MISSINGr(   rd   re   r)   putwaitingrV   rB   )r+   r   r(   rO   rD   er/   s         r   rs   zBaseConnectionPool.put   su   T#8!<<
ikk&&t,,Cj11 	T///DD ("",
 "GDMMM    '''11EFFFGGKKj$/0000 ||~~!!D!!!! !!Q&!!!!#####s   ?B 
B;B33B;c              #      K   |                                  }	 |V  |                     ||           d S # |                     ||           w xY w)N)r(   )ri   rs   )r+   r(   r   s      r   itemzBaseConnectionPool.item   sY      xxzz	,JJJHHT7H+++++DHHT7H++++s	   5 Ac                    | j         r| j                                          | j        t                      c}| _        |D ]H}t	          |t
                    r|d         n|}|                     |d           | xj        dz  c_        IdS )zuClose all connections that this pool still holds a reference to,
        and removes all references to them.
           TrQ   r4   N)r'   cancelr;   r   rk   rl   rW   rV   )r+   r;   rw   r   s       r   rT   zBaseConnectionPool.clear   s     ! 	,"))+++&*ouww#
DO 	# 	#D(u55?4774DT..."		# 	#r   c                 .    |                                   d S r   )rT   r+   s    r   __del__zBaseConnectionPool.__del__  s    

r   )F)r   r   r   r   r*   rB   r:   rL   ra   rW   ri   rr   rs   r   rw   rT   r}   __classcell__r/   s   @r   r   r      s'       ab!")	#T #T #T #T #T #TJ). ). ).V/ / /6    $
K 
K 
K 
K    < !) $$ $$ $$ $$ $$ $$L # , , , ^,# # #      r   r   c                   .    e Zd ZdZd Zed             ZdS )TpooledConnectionPoolzZA pool which gives out :class:`~eventlet.tpool.Proxy`-based database
    connections.
    c                 z    t          j                     }|| | j        | j        | j        g| j        R i | j        fS r   r9   connectr!   r&   r"   r#   r+   rD   s     r   rj   zTpooledConnectionPool.create  \    ikkCOT1P48JP P PBF,P P P 	Pr   c                    t          j        |t                                }	 ddlm}  |j        |j        g|R i |}|                    |d          |                                 S # |                                 w xY w)Nr   )tpool)cursor)autowrap_names)	r   Timeoutr   eventletr   executer   Proxyrz   )clsr,   r&   r-   kwr6   r   r   s           r   r   zTpooledConnectionPool.connect  s    OO^-=-=>>	&&&&&& 5=!2@T@@@R@@D;;tK;@@HHJJJJAHHJJJJs   2A* *B Nr   r   r   __doc__rj   classmethodr   r   r   r   r   r     sK         P P P
   [  r   r   c                   .    e Zd ZdZd Zed             ZdS )RawConnectionPoolz7A pool which gives out plain database connections.
    c                 z    t          j                     }|| | j        | j        | j        g| j        R i | j        fS r   r   r   s     r   rj   zRawConnectionPool.create!  r   r   c                     t          j        |t                                }	  |j        |i ||                                 S # |                                 w xY wr   )r   r   r   r   rz   )r   r,   r&   r-   r   r6   s         r   r   zRawConnectionPool.connect&  sT    OO^-=-=>>	$9$d1b11HHJJJJAHHJJJJs   A ANr   r   r   r   r   r     sK         P P P
   [  r   r   c                   *    e Zd Zd Zd Zd Zd ZdZdS )GenericConnectionWrapperc                     || _         d S r   )r]   )r+   baseconns     r   r*   z!GenericConnectionWrapper.__init__4  s    


r   c                 4    | j                                         S r   )r]   	__enter__r|   s    r   r   z"GenericConnectionWrapper.__enter__=  s    z##%%%r   c                 :    | j                             |||          S r   )r]   __exit__)r+   excvaluetbs       r   r   z!GenericConnectionWrapper.__exit__@  s    z""3r222r   c                 4    | j                                         S r   )r]   __repr__r|   s    r   r   z!GenericConnectionWrapper.__repr__C  s    z""$$$r   )!affected_rows
autocommitbeginchange_usercharacter_set_namerc   commitr   dump_debug_infoerrnoerrorerrorhandlerget_server_info	insert_idliteralpingqueryr   	select_dbserver_capabilitiesset_character_setset_isolation_levelset_server_optionset_sql_modeshow_warningsshutdownsqlstatestatstore_resultstring_literal	thread_id
use_resultwarning_countN)r   r   r   r*   r   r   r   _proxy_funcsr   r   r   r   r   3  sQ          & & &3 3 3% % %"LLLr   r   c                 B      fd} |_          |_        d z   |_        |S )Nc                 :     t          | j                  |i |S r   )r8   r]   )r+   r-   r.   
_proxy_funs      r   _proxy_methodz_wrapper.<locals>._proxy_methodn  s$    274:z22DCFCCCr   zGenericConnectionWrapper.)	func_namer   r   )r   r   s   ` r   _wrapperr   m  sD    	D 	D 	D 	D 	D",!+%@:%M"r   c                   >     e Zd ZdZ fdZd ZeZd Zd Zd Z	 xZ
S )rm   zA 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                 X    t                                          |           || _        d S r   )r)   r*   _pool)r+   r   poolr/   s      r   r*   z PooledConnectionWrapper.__init__  s&    """


r   c                 J    t          | d          ot          | j                  S )Nr]   )hasattrboolr]   r|   s    r   __nonzero__z#PooledConnectionWrapper.__nonzero__  s!    g&&;4
+;+;<r   c                 <    d | _         	 | `d S # t          $ r Y d S w xY wr   )r   r]   r_   r|   s    r   r^   z PooledConnectionWrapper._destroy  s9    
	


 	 	 	DD	s    
c                 t    | r!| j         r| j                             |            |                                  dS )zReturn 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   rs   r^   r|   s    r   rc   zPooledConnectionWrapper.close  s:    
  	!DJ 	!JNN4   r   c                     d S r   r   r|   s    r   r}   zPooledConnectionWrapper.__del__  s    r   )r   r   r   r   r*   r   __bool__r^   rc   r}   r~   r   s   @r   rm   rm   z  s             = = = H          r   rm   c                   (    e Zd ZdZ	 ddZd Zd ZdS )DatabaseConnectorzr
    This is an object which will maintain a collection of database
    connection pools on a per-host basis.
    Nc                     |sJ || _         | j         t          | _         || _        || _        || _        || _        i | _        dS )zconstructor
        *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credentials	conn_poolr-   r.   s         r   r*   zDatabaseConnector.__init__  sN      ) ($2D!
'r   c                 d    || j         v r| j         |         S | j                             dd           S )Ndefault)r   ri   )r+   hosts     r   credentials_forz!DatabaseConnector.credentials_for  s7    4$$$$T**$((D999r   c                    ||f}|| j         vrp| 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   dbnamekey
new_kwargsdbpools         r   ri   zDatabaseConnector.get  s     Vndo%%**,,J%Jt!%Jvd22488999*T*9#z9 9 9-79 9F#)DOC s##r   r   )r   r   r   r   r*   r   ri   r   r   r   r   r     sU              &: : :$ $ $ $ $r   r   )collectionsr   
contextlibr   rf   r9   eventlet.poolsr   r   r   r   eventlet.hubs.timerr   eventlet.greenthreadr	   objectrr   rd   r   r   r   r   r   r   r   r   r   r   setattrrm   r   r   r   r   <module>r      sO         % % % % % % 



                    % % % % % % , , , , , , 688	 	 	 	 	Y 	 	 	  m m m m m m m m`    .   *    *   & '5 5 5 5 5 5 5 5p +7 	H 	HJ&     G$j((:2F2FGGGG)! ! ! ! !6 ! ! !L,$ ,$ ,$ ,$ ,$ ,$ ,$ ,$ ,$ ,$r   