
    h-e                       U d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	 ddl
mZmZmZmZmZmZmZmZ ddlmZmZ ddlmZ 	 ddlZddlZdZd
dlmZmZm Z m!Z!m"Z" d
dl#m$Z$m%Z%m&Z& ddl'm(Z( erddl)m*Z*  ejV                         Z,dZ-dZ. ej^                  d      Z0e(fZ1de2d<   i Z3de2d<   ddZ4	 	 	 	 d dZ5	 	 	 	 	 	 d!dZ6d"dZ7 G d d      Z8 G d d      Z9y# e$ r d	ZY w xY w)#z5Implementing pooling of connections to MySQL servers.    )annotationsN)TracebackType)TYPE_CHECKINGAnyDictNoReturnOptionalTupleTypeUnion)UUIDuuid4)CNX_POOL_ARGSTF   )ErrorInterfaceErrorNotSupportedError	PoolErrorProgrammingError)DEFAULT_CONFIGURATIONgenerate_pool_nameread_option_files   )MySQLConnection)MySQLConnectionAbstract    @   z[^a-zA-Z0-9._:\-*$#]zUnion[type, Tuple[type, ...]]MYSQL_CNX_CLASSzDict[str, MySQLConnectionPool]_CONNECTION_POOLSPooledMySQLConnectionc                   K   d| v r| d   n
t        di | }|t        vrLt        di | }|j                          d{    t        4 d{    |t        |<   ddd      d{    nAt        t        |   t              r*t        |   j                  }d| v r| d   |k7  rt        d      	 t        |   j                          d{   S 7 7 7 j# 1 d{  7  sw Y   8xY w7 # t        $ r t        d| d      dw xY ww)z!Return a pooled MySQL connection.	pool_nameN	pool_sizez)Size can not be changed for active pools.z%Failed getting connection from pool '' )r   r   MySQLConnectionPoolinitialize_poolCONNECTION_POOL_LOCK
isinstancer#   r   get_connectionAttributeErrorr   )kwargsr"   pool
check_sizes       N/var/www/html/venv/lib/python3.12/site-packages/mysql/connector/aio/pooling.py_get_pooled_connectionr0   L   s'      +f4{:L:Vv:V 
 ))",V,""$$$' 	0 	0+/i(	0 	0 	0	%i02E	F&y1;;
& VK%8J%FGHH&y1@@BBB 	%	0 	0 	0 	0 	0 C 3I;a@
	s   ;DCDCD
CD%C&AD-C) C'C) DDDC$CC$ D'C) )DDc                 j  K   | j                         }	 |d   }|d= h d}d}|D ]  }t        |j	                               |z
  }|r4t        |      dkD  rdnd}d	j                  |      }t        d
| d|       t        |d      r|dz  }|j                  dd      |d<   |d   dk  s|d   dkD  rt        d|d          t        |d   t              rt        d|d           d|cxk  rt        |      k  rt        d       i }	g }
t        |d d      D ]>  }|d   |	vr|g|	|d   <   |
j                  |d          (|	|d      j                  |       @ |
D ]  }|	|   }t        t        |            D ]  }t        |      dz
  }t!        j"                  d|      }|j%                  |      }|j                         }|j'                  |       |j%                  dd       	 t)        di | d{   c c S   t        d      # t        $ r t        d      dw xY w7 /# t*        $ r Y w xY ww)a  Return a MySQL connection and try to failover if needed.

    An InterfaceError is raise when no MySQL is available. ValueError is
    raised when the failover server configuration contains an illegal
    connection argument. Supported arguments are user, password, host, port,
    unix_socket and database. ValueError is also raised when the failover
    argument was not provided.

    Returns MySQLConnection instance.
    failoverzfailover argument not providedN>	   hostportuserdatabasepasswordpriorityr"   r#   unix_socketr   r   s z, z Unsupported connection argument z in failover: r8   d   z9Priority value should be in the range of 0 to 100, got : zDPriority value should be an integer in the range of 0 to 100, got : z\You must either assign no priority to any of the routers or give a priority for every routerc                    | d   S )Nr8   r%   xs    r/   <lambda>z*_get_failover_connection.<locals>.<lambda>   s
    :     T)keyreversez,Unable to connect to any of the target hostsr%   )copyKeyError
ValueErrorsetkeyslenjoinhasattrgetr   r)   intr   sortedappendrangerandomrandintpopupdateconnectr   )r,   configr2   support_cnx_argspriority_countserverdiffarglstserver_directoryserver_priority_listr8   failover_list_lastindex
new_configs                    r/   _get_failover_connectionrd   i   s     [[]FE*% 	z
 N 6;;=!$44TQ#BC))D/C23%~cUK  6:&aN#ZZ
C8z*!VJ%7#%= 
+,.  &,c2 $Z013 %. 	>)CM)
 	
 * '>M @*%554:8VJ/0 ''z(:;VJ/077?@ ) (2s=)* 	A}%)DNN1d+E"&&u-FJf%NN:t,$2z222	 G
HHQ  E9:DEF 3 sY   H3H	 B:H3DH3$H$2H"3H$6H3	HH3"H$$	H0-H3/H00H3c                 z  K   dv rj                  d      nd}t        |t              st        d      |r t        st        d      dv rt        d      dv rt        d      d	v rt        d
      dvrt
        d   d<   	 t        j                  j                  d   d       d{   }g }|D ]P  }|j                  |j                  j                  d      |j                  |j                  |j                   d       R |j#                  d        |D cg c]  }|d   |d   d c}d	<   d	v rt%        di  d{   S 	 t'        fdt(        D              rt+        di  d{   S 	 dv rd   d<   j                  d       dv rt/        di }t1        di | d{   S dv rd= t3        | i }|j1                          d{    |S 7 :# t        j                  j                  $ r t        dd    d      dw xY wc c}w 7 7 # t,        $ r Y w xY w7 7 Ww)a  Creates a MySQL connection object.

    In its simpliest form, `connect()` will open a connection to a
    MySQL server and return a `MySQLConnectionAbstract` subclass
    object such as `MySQLConnection` or `CMySQLConnection`.

    Args:
        *args: N/A.
        **kwargs: For a complete list of possible arguments, see [1]. If no arguments
                  are given, it uses the already configured or default values.

    Returns:
        A `MySQLConnectionAbstract` subclass instance (such as `MySQLConnection`)
        or a `PooledMySQLConnection` instance.

    Raises:
        `mysql.connector.errors.NotSupportedError`: if pooled connection is not supported
        for the Python version and OS that are being used.

    Examples:
        A connection with the MySQL server can be established using either the
        `mysql.connector.aio.connect()` method or a `MySQLConnectionAbstract` subclass:
        ```
        >>> from mysql.connector.aio import MySQLConnection
        >>>
        >>> cnx1 = await mysql.connector.aio.connect(user='joe', database='test')
        >>> cnx2 = MySQLConnection(user='joe', database='test')
        >>>
        ```
    References:
        [1]: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
    dns_srvFz(The value of 'dns-srv' must be a booleanztMySQL host configuration requested DNS SRV. This requires the Python dnspython module. Please refer to documentationr9   z<Using Unix domain sockets with DNS SRV lookup is not allowedr4   z;Specifying a port number with DNS SRV lookup is not allowedr2   zASpecifying multiple hostnames with DNS SRV look up is not allowedr3   SRVNz Unable to locate any hosts for 'r$   T)omit_final_dot)r3   r4   r8   weightc                    | d   | d    fS )Nr8   ri   r%   r>   s    r/   r@   zconnect.<locals>.<lambda>  s    Qz]Qx[L$A rA   )rB   )r3   r4   c              3  &   K   | ]  }|v  
 y wNr%   ).0rB   r,   s     r/   	<genexpr>zconnect.<locals>.<genexpr>   s     6sf}6s   read_default_fileoption_filesuse_purer%   )rS   r)   boolr   HAVE_DNSPYTHONr   dnsasyncresolverquery	exceptionDNSExceptionrO   targetto_textr4   r8   ri   sortrd   anyr   r0   	NameErrorr   rU   r   )argsr,   rf   srv_recordsr2   srvrc   cnxs    `      r/   rU   rU      s    H (1F':fjj#Ggt$GHH 8 
 F" N  V M   S  26:F6N	 # 1 1 7 7v NNK  	COOJJ..d.CHH #!jj		 	ABBJ
;>S[#f+6
z
 V-7777666/9&999 7 f$!'(;!<~

&'&00
*z***V:
4
*6
*C
++-Ja O}})) 	 26&>2B!D	"
 8
 :  + s   BH;&G+ .G(/G+ 3A.H;!H3H;H$H;&H( 7H&8H( ;<H;7H78)H;!H9"H;(G+ +1H	H;&H( (	H41H;3H44H;9H;c                     t         j                  } t        j                  dk(  r+| j                  dk(  r| j
                  dk  rt        d      yyy)zWRaises error if the Python version and OS combination is not
    supported for Pooling.nt   
   zSPooled connections are not supported for Python versions lower than 3.11 on WindowsN)sysversion_infoosnamemajorminorr   )py_version_infos    r/   _check_supportr   7  sR     &&O	ww$?00A5/:O:OSU:U)
 	
 ;V5rA   c                  l    e Zd ZdZd
dZddZ	 	 	 	 	 	 	 	 ddZddZddZe	dd       Z
edd       Zy	)r    a  Class holding a MySQL Connection in a pool
    PooledMySQLConnection is used by MySQLConnectionPool to return an
    instance holding a MySQL connection. It works like a MySQLConnection
    except for methods like close() and config().
    The close()-method will add the connection back to the pool rather
    than disconnecting from the MySQL server.
    Configuring the connection have to be done through the MySQLConnectionPool
    method set_config(). Using config() on pooled connection will raise a
    PoolError.
    Attributes:
        pool_name (str): Returns the name of the connection pool to which the
                         connection belongs.
    c                    t                t        |t              st        d      t        |t              st        d      || _        || _        y)zConstructor.
        Args:
            pool: A `MySQLConnectionPool` instance.
            cnx: A `MySQLConnectionAbstract` subclass instance.
        z/pool must be an instance of MySQLConnectionPoolz,cnx should be an instance of MySQLConnectionN)r   r)   r&   r+   r   	_cnx_pool_cnx)selfr-   r   s      r/   __init__zPooledMySQLConnection.__init__Q  sE     	$ 34 !RSS#/ !OPP.2-0	rA   c                   K   | S wrl   r%   r   s    r/   
__aenter__z PooledMySQLConnection.__aenter__`  s     s   c                @   K   | j                          d {    y 7 wrl   )close)r   exc_type	exc_value	tracebacks       r/   	__aexit__zPooledMySQLConnection.__aexit__c  s      jjls   c                .    t        | j                  |      S )z0Calls attributes of the MySQLConnection instance)getattrr   )r   attrs     r/   __getattr__z!PooledMySQLConnection.__getattr__k  s    tyy$''rA   c                r  K   | j                   }	 | j                  j                  r0|j                          d{   r|j	                          d{    | j                  j                  |       d{    d| _         y7 G7 17 # | j                  j                  |       d{  7   d| _         w xY ww)a  Do not close, but adds connection back to pool.
        For a pooled connection, close() does not actually close it but returns it
        to the pool and makes it available for subsequent connection requests. If the
        pool configuration parameters are changed, a returned connection is closed
        and reopened with the new configuration before being returned from the pool
        again in response to a connection request.
        N)r   r   can_reset_sessionis_connectedreset_sessionadd_connectionr   r   s     r/   r   zPooledMySQLConnection.closeo  s      ii	~~//#:J:J:L4L4L'')))..//444DI	 5M)4$..//444DIs\   B7)B BB BB B74B5B7B B B7B4&B)'B44B7c                     t        d      )zConfiguration is done through the pool.
        For pooled connections, the `config()` method raises a `PoolError`
        exception. Configuration for pooled connections should be done
        using the pool object.
        zKConfiguration for pooled connections should be done through the pool itself)r   )r,   s    r/   rV   zPooledMySQLConnection.config  s     
 	
rA   c                .    | j                   j                  S )zHReturns the name of the connection pool to which the connection belongs.)r   r"   r   s    r/   r"   zPooledMySQLConnection.pool_name  s     ~~'''rA   N)r-   r&   r   r   returnNoner   r    )r   zType[BaseException]r   BaseExceptionr   r   r   r   )r   r   r   r   r   r   )r,   r   r   r   r   str)__name__
__module____qualname____doc__r   r   r   r   r   staticmethodrV   propertyr"   r%   rA   r/   r    r    B  sn    1% ! !	
 
(  	
 	
 ( (rA   c                      e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZddZedd       Zedd       Zedd       Z	ddZ
dd	Zdd
ZddZ	 d	 	 	 ddZddZddZddZy)r&   z*Class defining a pool of MySQL connectionsNc                    t                d| _        d| _        || _        | j	                  |       |r| j                  |       || _        t        j                  | j                        | _	        t               | _        y)a  Constructor.

        Initialize a MySQL connection pool with a maximum number of
        connections set to `pool_size`.

        NOTE: The coroutine `await cnxpool.initialize_pool(**dbconfig)` must be called
        after initializing this class to open up the pool of required number of database
        connections and making the instance of MySQLConnectionPool ready-to-use.
        Contents of `dbconfig` is described in [1].

        Args:
            pool_name: The pool name. If this argument is not given, Connector/Python
                       automatically generates the name, composed from whichever of
                       the host, port, user, and database connection arguments are
                       given in kwargs, in that order.
            pool_size:  The pool size. If this argument is not given, the default is 5.
            pool_reset_session: Whether to reset session variables when the connection
                                is returned to the pool.

        Examples:
            ```
            >>> dbconfig = {
            >>>     "database": "test",
            >>>     "user":     "joe",
            >>> }
            >>> # initialize the MySQLConnectionPool instance
            >>> cnxpool = mysql.connector.aio.pooling.MySQLConnectionPool(
            >>>             pool_name = "mypool",
            >>>             pool_size = 3,
            >>> )
            >>> # Open up the pool of connections
            >>> await cnxpool.initialize_pool(**dbconfig)
            >>> # cnxpool is ready to be used ...
            ```
        References:
            [1]: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
        N)r   
_pool_size
_pool_name_reset_session_set_pool_size_set_pool_name_cnx_configasyncioQueue
_cnx_queuer   _config_version)r   r#   r"   pool_reset_sessionr,   s        r/   r   zMySQLConnectionPool.__init__  sl    X 	)-)-$6I&	*+1BI--OOC
 &+WrA   c                  K   | j                   sCt        4 d{    | j                  t        di | j                         ddd      d{    | j                  rd | j
                  di | j                   d{    d}|| j                  k  r.| j                          d{    |dz  }|| j                  k  r-yyy7 7 w# 1 d{  7  sw Y   xY w7 ^7 7w)a  Opens the connection pool and fill with MySQL database connections.

        This coroutine must be called after initializing an instance of MySQLConnectionPool
        to make the build the pool of connections and make the instance ready to be used.

        Args:
            **kwargs: Connection arguments, as described in [1].

        References:
            [1]: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
        Nr   r   r%   )r   r(   r   r   r   
set_configr   r   )r   cnts     r/   r'   z#MySQLConnectionPool.initialize_pool  s      + L L##$6$J9I9I$JKL L!$//5D$4$4555C'))+++q ' L L L L L 6 ,sh   C CC %CC C/C =C>(C &C'C  C C CCCC C c                    | j                   S )z(Returns the name of the connection pool.)r   r   s    r/   r"   zMySQLConnectionPool.pool_name       rA   c                    | j                   S )z2Returns number of connections managed by the pool.)r   r   s    r/   r#   zMySQLConnectionPool.pool_size  r   rA   c                    | j                   S )z!Returns whether to reset session.)r   r   s    r/   r   z%MySQLConnectionPool.can_reset_session  s     """rA   c                N  K   |sy	 t        di | d{   }|j                          d{    t        4 d{    || _        t	               | _        ddd      d{    y7 R7 <7 /7 # 1 d{  7  sw Y   yxY w# t        $ r}t        d|       |d}~ww xY ww)a  Set the connection configuration for `MySQLConnectionAbstract` subclass instances.
        This method sets the configuration used for creating `MySQLConnectionAbstract`
        subclass instances such as `MySQLConnection`. See [1] for valid
        connection arguments.
        Args:
            **kwargs: Connection arguments - for a complete list of possible
                      arguments, see [1].
        Raises:
            PoolError: When a connection argument is not valid, missing
                       or not supported by `MySQLConnectionAbstract`.
        References:
            [1]: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
        Nz$Connection configuration not valid: r%   )rU   
disconnectr(   r   r   r   	Exceptionr   )r   r,   r   errs       r/   r   zMySQLConnectionPool.set_config  s      	S)&))C.."""+ / /#) ',w$/ / / *"/ / / / /  	SB3%HIsR	Ss   B%B A(B A*B A,B  A0B "A.#B 'B%(B *B ,B .B 0B6A97B>B B%B 	B"BB""B%c                R    |dk  s	|t         kD  rt        dt                || _        y)zSet the size of the pool
        This method sets the size of the pool but it will not resize the pool.
        Raises an AttributeError when the pool_size is not valid. Invalid size
        is 0, negative or higher than pooling.CNX_POOL_MAXSIZE.
        r   z8Pool size should be higher than 0 and lower or equal to N)CNX_POOL_MAXSIZEr+   r   )r   r#   s     r/   r   z"MySQLConnectionPool._set_pool_size  s7     >Y)99 J#$&  $rA   c                    t         j                  |      rt        d| d      t        |      t        kD  rt        d| d      || _        y)a  Set the name of the pool.
        This method checks the validity and sets the name of the pool.
        Raises an AttributeError when pool_name contains illegal characters
        ([^a-zA-Z0-9._\-*$#]) or is longer than pooling.CNX_POOL_MAXNAMESIZE.
        zPool name 'z' contains illegal charactersz' is too longN)CNX_POOL_NAMEREGEXsearchr+   rI   CNX_POOL_MAXNAMESIZEr   )r   r"   s     r/   r   z"MySQLConnectionPool._set_pool_name  sO     $$Y/ ;yk9V!WXXy>00 ;yk!GHH#rA   c                    t        |t              st        d      	 | j                  j	                  |       y# t
        j                  $ r}t        d      |d}~ww xY w)zPut connection back in the queue
        This method is putting a connection back in the queue. It will not
        acquire a lock as the methods using _queue_connection() will have it
        set.
        Raises `PoolError` on errors.
        ;Connection instance not subclass of MySQLConnectionAbstract'Failed adding connection; queue is fullN)r)   r   r   r   
put_nowaitr   	QueueFullr   r   r   s      r/   _queue_connectionz%MySQLConnectionPool._queue_connection'  s\     #/M 	POO&&s+   	PEFCO	Ps   9 AAAc                  K   | j                   st        d      | j                  j                         rt        d      |sit	        di | j                    d{   }	 | j
                  r-| j                   d   r|j                         dk  rt        d      | j                  |_
        nt        |t              st        d      | j                  |       y7 }# t        $ r Y Lw xY ww)	a  Adds a connection to the pool.
        This method instantiates a `MySQLConnection` using the configuration
        passed when initializing the `MySQLConnectionPool` instance or using
        the `set_config()` method.
        If cnx is a `MySQLConnection` instance, it will be added to the
        queue.
        Args:
            cnx: The `MySQLConnectionAbstract` subclass object to be added to
                 the pool. If this argument is missing (aka `None`), the pool
                 creates a new connection and adds it.
        Raises:
            PoolError: When no configuration is set, when no more
                       connection can be added (maximum reached) or when the connection
                       can not be instantiated.
        z&Connection configuration not availabler   Ncompress)      r   z^Pool reset session is not supported with compression for MySQL server version 5.7.2 or earlierr   r%   )r   r   r   fullrU   r   get_server_versionr   rE   r   pool_config_versionr)   r   r   r   s     r/   r   z"MySQLConnectionPool.add_connection8  s     $ DEE??!EFF3$"2"233C''((4..09<+%  '+&:&:C#c?3Q  	s#- 4  s7   AC(CC(9C A C(	C%"C($C%%C(c                  K   	 | j                   j                         }|j                          d{   r| j                  |j                  k7  rF	  |j                  di | j                   |j                          d{    | j                  |_        t        | |      S # t        j                  $ r}t	        d      |d}~ww xY w7 7 J# t        $ r | j                  |        w xY ww)a  Gets a connection from the pool.
        This method returns an PooledMySQLConnection instance which
        has a reference to the pool that created it, and the next available
        MySQL connection.
        When the MySQL connection is not connect, a reconnect is attempted.
        Returns:
            A `PooledMySQLConnection` instance.
        Raises:
            PoolError: On errors.
        z)Failed getting connection; pool exhaustedNr%   )r   
get_nowaitr   
QueueEmptyr   r   r   r   _set_connection_optionsr   	reconnectr   r   r    r   s      r/   r*   z"MySQLConnectionPool.get_connectioni  s     	R//,,.C
 &&(((##s'>'>>+++?d.>.>?mmo%% '+&:&:C#$T3// !! 	RGHcQ	R )
 &! &&s+s[   C+B! C+CC+/C ?C
 C C+!C4C  CC+
C C((C+c                (  K   d}| j                   }|j                         r?	 |j                         }|j                          d{    |dz  }|j                         r?|S 7 # t        j
                  $ r |cY S t        $ r  t        $ r Y ?w xY ww)a$  Close all connections
        This method closes all connections and returns the number of connections it closed.
        This method should be used internally while cleaning-up the connection pool by closing each
        and every active connection objects currently residing in the pool.

        Returns:
            An integer defining the number of open connections closed during clean-up.
        Raises:
            PoolError: On errors while fetching connections from the pool or while disconnecting
            an open connection.
        r   Nr   )r   qsizer   r   r   r   r   r   )r   r   cnxqr   s       r/   _remove_connectionsz'MySQLConnectionPool._remove_connections  s      jjl
oo'nn&&&q	 jjl 
 '%% 
  sL   B#A$ A"	A$ B B"A$ $B9B;BBBBc                >   K   | j                          d{   S 7 w)a  Cleans up the connection pool
        This public method gracefully shuts down the connection pool by disconnecting all of the
        open connections currently active in the pool.

        Returns:
            An integer defining the number of open connections closed while shutting down the pool.
        Raises:
            PoolError: On errors while fetching connections from the pool or while disconnecting
            an open connection.
        N)r   r   s    r/   
close_poolzMySQLConnectionPool.close_pool  s      --////s   )r   NT)
r#   rM   r"   zOptional[str]r   rr   r,   r   r   r   r   r   )r   rM   )r   rr   )r,   r   r   r   )r#   rM   r   r   )r"   r   r   r   )r   r   r   r   rl   )r   z!Optional[MySQLConnectionAbstract]r   r   r   )r   r   r   r   r   r'   r   r"   r#   r   r   r   r   r   r   r*   r   r   r%   rA   r/   r&   r&     s    4 #'#'	8-8- !8- !	8-
 8- 
8-t,     # #S6$
$P$ 8</$4/$	/$b0>:0rA   r&   )r,   r   r   r    )r,   r   r   5Union[PooledMySQLConnection, MySQLConnectionAbstract])r~   r   r,   r   r   r   r   ):r   
__future__r   r   r   rQ   rer   typesr   typingr   r   r   r   r	   r
   r   r   uuidr   r   mysql.connector.constantsr   dns.asyncresolverrt   dns.exceptionrs   ImportErrorerrorsr   r   r   r   r   poolingr   r   r   
connectionr   	abstractsr   Lockr(   r   r   compiler   r   __annotations__r   r0   rd   rU   r   r    r&   r%   rA   r/   <module>r      s  : < "  	  	 
  S S S  3 N  S R '2 $w||~   RZZ 78 2A1C. C46 1 6:XIXI:XIvppp:pf
L( L(^_0 _0C  Ns   C C&%C&