U
    4Je                    @  s  d Z ddlmZ ddlmZ zLddlZdZejejej	dZ
eedrLejneje
d< eed	odejZW n  ek
r   d
Zd
Zi Z
Y nX ddlZddlZddlZddlZddlZddl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mZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% zddl&Z'ddl(Z'W n ek
r<   d
Z)Y nX dZ)ddl*m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZDmEZEmFZFmGZGmHZHmIZI ddlJmKZKmLZLmMZM ddlNmNZN ddlOmPZP ddlQmRZRmSZSmTZTmUZUmVZV ddlWmXZXmYZYmZZZm[Z[m\Z\ ddl]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZh ddlmiZimjZjmkZkmlZl ejmnd ddlompZpmqZqmrZrmsZs ddltmuZu ddlvmwZwmxZx d d!d"d#Zyd$Zzd%Z{d&Z|d'Z}d(Z~d)Zd*Zed+Zd,Zd,Zd-Zd.Zd/Zd/Zd0Zd.Zeeeeeeeed1Zd2eiZed3Zed4ejZed5ejZed6Zd7d8d9d:d;d<gZed=d>d?d@dAdBdCdDdEdFdGdHdIdJdKg ZdLdMdNdOdPZdQdRdSdTdUZG dVdW dWZdXdXdYdZd[ZG d\d] d]eZG d^d_ d_ZG d`da daZG dbdc dceZG ddde deejZG dfdg dgZG dhdi diZG djdk dkZdMdldmdndoZdMdpdqdrdsZdpdRdtdudvZddpdwdRdxdydzZdpdRdtd{d|ZdpdRdtd}d~ZdpdRdtddZdLdLdpdddZdLdLdidddZdddkdddZdS )z4Implementation of communication for MySQL X servers.    )annotations)TracebackTypeNT)TLSv1TLSv1.1TLSv1.2PROTOCOL_TLSTLSv1.3HAS_TLSv1_3F)	AnyCallableDictListMappingOptionalTupleTypeUnion)datetime	timedeltawraps)JSONDecodeError)	parse_qslunquoteurlparse   )MySQL41AuthPluginPlainAuthPluginSha256MemoryAuthPlugin)COMPRESSION_ALGORITHMSDEPRECATED_TLS_VERSIONSOPENSSL_CS_NAMESSUPPORTED_TLS_VERSIONSTLS_CIPHER_SUITESAuthCompressionSSLModeSchema)InterfaceErrorNotSupportedErrorOperationalError	PoolErrorProgrammingErrorTimeoutError)escapeget_item_or_attriani_to_openssl_cs_name)logger)Protobuf)HAVE_LZ4	HAVE_ZSTDMessageReaderMessageWriterProtocol)
BaseResult	DocResultResult	RowResult	SqlResult)AddStatementDeleteStatementFindStatementInsertStatementModifyStatementReadStatementRemoveStatementSelectStatementSqlStatementUpdateStatementquote_identifier)
ColumnTypeMessageTypeResultBaseTypeStatementType..)DUPLICATED_IN_LIST_ERRORTLS_VER_NO_SUPPORTEDTLS_VERSION_DEPRECATED_ERRORTLS_VERSION_ERROR)linux_distribution)LICENSEVERSIONzThis session was closed because the connection has been idle for too long. Use 'mysqlx.getSession()' or 'mysqlx.getClient()' to create a new one.z<This session was closed because the server is shutting down.zThis session was closed because the connection has been killed in a different session. Use 'mysqlx.getSession()' or 'mysqlx.getClient()' to create a new one.)i    ia  i'  zDROP DATABASE IF EXISTS {}z CREATE DATABASE IF NOT EXISTS {}zLSELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{}'zSELECT @@versionc   x   z[^a-zA-Z0-9._:\-*$#]i  i@B <   i  iQ )z[WinError 10053]z
[Errno 32]z[WinError 10061]z[Errno 111]z[WinError 10060]z[Errno 11001]z
[Errno -2]zAccess deniedrU   z,(?![^\(\)]*\))z!^\(address=(.+),priority=(\d+)\)$z^\(address=(.+)[,]*\)$z"^([a-zA-Z][a-zA-Z0-9+\-.]+)://(.*)ssl-certssl-cassl-keyssl-crltls-versionstls-ciphersuitesuserpasswordschemahostportrouterssocketssl-modeauthuse-pureconnect-timeoutconnection-attributescompressioncompression-algorithmsdns-srvr
   str)kwargsreturnc               	   K  sP   g }dD ]0}z| t| |  W q tk
r6   Y qX q|sFtdd|S )ab  Generate a pool name.

    This function takes keyword arguments, usually the connection arguments and
    tries to generate a name for the pool.

    Args:
        **kwargs: Arbitrary keyword arguments with the connection arguments.

    Raises:
        PoolError: If the name can't be generated.

    Returns:
        str: The generated pool name.
    )rb   rc   r_   Zdatabase	client_idz.Failed generating pool name; specify pool_name_)appendrn   KeyErrorr,   join)ro   partskey rx   5/tmp/pip-unpacked-wheel-7_167w8m/mysqlx/connection.pygenerate_pool_name   s    rz   Mapping[str, Any]None)penalty_dictrp   c                 C  s   | rt | trt|  dS )zUpdate the timeout penalties directory.

    Update the timeout penalties by error dictionary used to deactivate a pool.
    Args:
        penalty_dict (dict): The dictionary with the new timeouts.
    N)
isinstancedict_TIMEOUT_PENALTIES_BY_ERR_NOupdate)r}   rx   rx   ry   !update_timeout_penalties_by_error   s    r   c                	   @  s   e Zd ZdZddddZefddddd	d
ZdddddZdddddZddddZ	ddddZ
dddddddddddZddddZdddd Zddd!d"Zddd#d$Zd%S )&SocketStreamzImplements a socket stream.r|   rp   c                 C  s   d | _ d| _d| _d | _d S )NF)_socket_is_ssl
_is_socket_hostselfrx   rx   ry   __init__  s    zSocketStream.__init__r   float)paramsconnect_timeoutrp   c                 C  s   |dk	r|d }zt ||| _|d | _W nd tk
r   z0t  t j| _| j| | j| d| _W n t	k
r   t
ddY nX Y nX | jd dS )zConnects to a TCP service.

        Args:
            params (tuple): The connection parameters.

        Raises:
            :class:`mysqlx.InterfaceError`: If Unix socket is not supported.
        N  r   TzUnix socket unsupported)re   create_connectionr   r   
ValueErrorAF_UNIX
settimeoutconnectr   AttributeErrorr)   )r   r   r   rx   rx   ry   r     s"    	 
zSocketStream.connectintbytes)countrp   c                 C  s\   | j dkrtdg }|dkrR| j |}|dkr:td|| |t|8 }qd|S )zReceive data from the socket.

        Args:
            count (int): Buffer size.

        Returns:
            bytes: The data received.
        NMySQLx Connection not availabler       zUnexpected connection close)r   r+   recvRuntimeErrorrs   lenru   )r   r   bufdatarx   rx   ry   read"  s    	

zSocketStream.read)r   rp   c              
   C  sZ   | j dkrtdz| j | W n2 tk
rT } ztd| |W 5 d}~X Y nX dS )z_Send data to the socket.

        Args:
            data (bytes): The data to be sent.
        Nr   zUnexpected socket error: )r   r+   sendallOSError)r   r   errrx   rx   ry   r   6  s    
zSocketStream.sendallc                 C  sF   | j s
dS z| j tj | j   W n tk
r:   Y nX d| _ dS )zClose the socket.N)r   shutdownre   	SHUT_RDWRcloser   r   rx   rx   ry   r   C  s    zSocketStream.closec                 C  s   |    d S Nr   r   rx   rx   ry   __del__O  s    zSocketStream.__del__	List[str]rn   )
ssl_protosssl_modessl_cassl_crlssl_certssl_keyssl_ciphersrp   c                 C  s  t s|   td|dks |sLt }|tjkr8d|_|tjkrtj	|_
n|jdd |d }	ts|	dkrt|dkr|d }	t|	 }
t|
}|	dkrd	|kr| jtjO  _d
|kr| jtjO  _d|kr| jtjO  _|rBz|| tj|_
W nB ttjfk
r@ } z|   td| |W 5 d}~X Y nX |rz|| tj|_W nB ttjfk
r } z|   td| |W 5 d}~X Y nX |rz||| W nB ttjfk
r } z|   td| |W 5 d}~X Y nX |r|dt|d | z|j| j | j!d| _ W n2 tj"k
rf } zt| |W 5 d}~X Y nX |tjkrNd|_g }t#j$dkr| j!dkrddg}t%&| j!}|'|d g|d   d}g }|D ]\}zt(| j ) | W n4 tj"k
r } z|*t+| W 5 d}~X Y nX d} q,q|sN|   tdd| d| _,| j - }	|	dkrd|	 d}t./|t0 dS )ax  Set SSL parameters.

        Args:
            ssl_protos (list): SSL protocol to use.
            ssl_mode (str): SSL mode.
            ssl_ca (str): The certification authority certificate.
            ssl_crl (str): The certification revocation lists.
            ssl_cert (str): The certificate.
            ssl_key (str): The certificate key.
            ssl_ciphers (list): SSL ciphersuites to use.

        Raises:
            :class:`mysqlx.RuntimeError`: If Python installation has no SSL
                                          support.
            :class:`mysqlx.InterfaceError`: If the parameters are invalid.
        z&Python installation has no SSL supportNFTreverser   r   r   r   r   r   zInvalid CA Certificate: zInvalid CRL: zInvalid Certificate/Key: :)server_hostnament)	localhost	127.0.0.1r   r   z"Unable to verify server identity: , )r   r   zThis connection is using zZ which is now deprecated and will be removed in a future release of MySQL Connector/Python)1SSL_AVAILABLEr   r   sslcreate_default_contextr&   VERIFY_IDENTITYcheck_hostnameREQUIRED	CERT_NONEverify_modesortTLS_V1_3_SUPPORTEDr   TLS_VERSIONS
SSLContextoptionsOP_NO_TLSv1_2OP_NO_TLSv1_1OP_NO_TLSv1load_verify_locationsCERT_REQUIREDIOErrorSSLErrorr)   VERIFY_CRL_CHECK_LEAFverify_flagsload_cert_chainset_ciphersru   r1   wrap_socketr   r   CertificateErrorosnamere   gethostbyaddrextendmatch_hostnamegetpeercertrs   rn   r   versionwarningswarnDeprecationWarning)r   r   r   r   r   r   r   r   contexttls_versionZssl_protocolr   Z	hostnamesaliasesZmatch_foundZerrshostnameZwarn_msgrx   rx   ry   set_sslR  s    





"
"" 



zSocketStream.set_sslboolc                 C  s   | j S )zpVerifies if SSL is being used.

        Returns:
            bool: Returns `True` if SSL is being used.
        )r   r   rx   rx   ry   is_ssl  s    zSocketStream.is_sslc                 C  s   | j S )zVerifies if socket connection is being used.

        Returns:
            bool: Returns `True` if socket connection is being used.
        )r   r   rx   rx   ry   	is_socket  s    zSocketStream.is_socketc                 C  s   | j p
| jS )zvVerifies if connection is secure.

        Returns:
            bool: Returns `True` if connection is secure.
        )r   r   r   rx   rx   ry   	is_secure  s    zSocketStream.is_securec                 C  s
   | j dk	S )zrVerifies if connection is open.

        Returns:
            bool: Returns `True` if connection is open.
        N)r   r   rx   rx   ry   is_open  s    zSocketStream.is_openN)__name__
__module____qualname____doc__r   _CONNECT_TIMEOUTr   r   r   r   r   r   r   r   r   r   rx   rx   rx   ry   r      s    r   r   )funcrp   c                   s$   t  ddddd fdd}|S )zDecorator used to catch OSError or RuntimeError.

    Raises:
        :class:`mysqlx.InterfaceError`: If `OSError` or `RuntimeError`
                                        is raised.
    r
   )r   argsro   rp   c           	        s  zt | ttfr$|  r$t|    | f||}t |tr| }|D ]T}|d tkrJt|d  }d|d  d| |d f}t | ttfr| 	|  qqJ|W S  tt
ttfk
r } zֈ jdkr|rt |d tr|d  }|r|d }t|d  }d|d  d| |d f}t | tr\| j  |d dkr\t | jt|  t | ttfrv| 	| |   t| ||    W 5 d}~X Y nX dS )	zWrapper function.codezConnection close: msgz: get_column_metadatar   rU   N)r~   
ConnectionPooledConnectionis_server_disconnectedr)   get_disconnected_reasonr9   Zget_warningsCONNECTION_CLOSED_ERRORset_server_disconnectedr   r   r.   r   r=   poolremove_connectionsPoolsManagerset_pool_unavailable
disconnect)	r   r   ro   resultZwarnsr   	error_msgreasonr   r   rx   ry   wrapper  s\    


 

z(catch_network_exception.<locals>.wrapperr   )r   r  rx   r   ry   catch_network_exception  s    2r  c                      sR   e Zd ZdZddd fddZddd	d
ZddddZddddZ  ZS )RouterzRepresents a set of connection parameters.

    Args:
       settings (dict): Dictionary with connection settings
    .. versionadded:: 8.0.20
    r{   r|   )connection_paramsrp   c                   s(   t    | | | dd| d< d S )N	availableT)superr   r   get)r   r  	__class__rx   ry   r   9  s    

zRouter.__init__r   r   c                 C  s   | d S )zVerifies if the Router is available to open connections.

        Returns:
            bool: True if this Router is available else False.
        r  rx   r   rx   rx   ry   r  >  s    zRouter.availablec                 C  s   d| d< dS )z1Sets this Router unavailable to open connections.Fr  Nrx   r   rx   rx   ry   set_unavailableF  s    zRouter.set_unavailablez%Union[str, Tuple[str, Optional[int]]]c                 C  s    d| kr| d S | d | d fS )zVerifies if the Router is available to open connections.

        Returns:
            tuple: host and port or socket information tuple.
        re   rb   rc   rx   r   rx   rx   ry   get_connection_paramsJ  s    zRouter.get_connection_params)	r   r   r   r   r   r  r
  r  __classcell__rx   rx   r  ry   r  1  s
   r  c                   @  sz   e Zd ZdZddddddZddd	d
ZdddddZdddddZddddZddddZ	ddddZ
dS )RouterManagerzManages the connection parameters of all the routers.

    Args:
        Routers (list): A list of Router objects.
        settings (dict): Dictionary with connection settings.
    .. versionadded:: 8.0.20
    zList[Router]Dict[str, Any]r|   )rd   settingsrp   c                 C  s0   || _ || _d| _d| _i | _g | _|   d S )Nr   T)_routers	_settings_cur_priority_idx_can_failover_routers_directoryrouters_priority_list_ensure_priorities)r   rd   r  rx   rx   ry   r   ^  s    zRouterManager.__init__r   c                 C  s   d}| j D ]<}|dd}|dkr4|d7 }d|d< q
|dkr
tddq
d|  k rbt| j k rpn n
tdd	| j jd
d dd | j D ]H}|d }|| jkrt|g| j|< | j| q| j| t| qdS )zuEnsure priorities.

        Raises:
            :class:`mysqlx.ProgrammingError`: If priorities are invalid.
        r   priorityNr   d   z(The priorities must be between 0 and 100  \You must either assign no priority to any of the routers or give a priority for every router  c                 S  s   | d S )Nr  rx   xrx   rx   ry   <lambda>  r   z2RouterManager._ensure_priorities.<locals>.<lambda>T)rw   r   )	r  r  r-   r   r   r  r  r  rs   )r   priority_countrouterr  rx   rx   ry   r  h  s(    



z RouterManager._ensure_prioritiesr   )r  rp   c                 C  s   | j | }dd |D }|S )zGet a list of the current available routers that shares the given priority.

        Returns:
            list: A list of the current available routers.
        c                 S  s   g | ]}|  r|qS rx   )r  ).0r   rx   rx   ry   
<listcomp>  s      z8RouterManager._get_available_routers.<locals>.<listcomp>r  )r   r  router_listrx   rx   ry   _get_available_routers  s    
z$RouterManager._get_available_routersr  c                 C  sF   |  |}|sdS t|dkr&|d S t|d }td|}|| S )z{Get a random router from the group with the given priority.

        Returns:
            Router: A random router.
        Nr   r   )r%  r   randomrandint)r   r  r$  lastindexrx   rx   ry   _get_random_connection_params  s    
z+RouterManager._get_random_connection_paramsr   c                 C  s   | j S )zReturns the next connection parameters.

        Returns:
            bool: True if there is more server to failover to else False.
        )r  r   rx   rx   ry   can_failover  s    zRouterManager.can_failoverc                 C  s   | j sBd| _| j }| jdd|d< | jdd|d< t|S | j| j }t| j}d}|r| 	|}|dk	s|| j|kr| j|d krt| 
|d	k rd| _q|  jd7  _| j|k r\| j| j }q\|S )
zvReturns the next connection parameters.

        Returns:
            Router: with the connection parameters.
        Frb   r   rc   $  TNr      )r  r  r  copyr  r  r  r  r   r*  r%  )r   Zrouter_settingscur_priorityZrouters_priority_lensearchr   rx   rx   ry   get_next_router  s,    



zRouterManager.get_next_routerzDict[int, List[Router]]c                 C  s   | j S )zReturns the directory containing all the routers managed.

        Returns:
            dict: Dictionary with priorities as connection settings.
        r#  r   rx   rx   ry   get_routers_directory  s    z#RouterManager.get_routers_directoryN)r   r   r   r   r   r  r%  r*  r+  r1  r2  rx   rx   rx   ry   r  U  s   
#
#r  c                   @  sH  e Zd ZdZdddddZdddd	Zd
ddddZddddZdddddZdjdddddddZ	ddddZ
ddddZddddZddd d!Zd"dd#d$d%Zdd&d'dd(d)d*Zdd&d'dd(d+d,Zed-d.d#d/d0Zed1d2d#d3d4Zed5d6d#d7d8Zed9d2d#d:d;Zed<d2d#d=d>Zedkddd?d@dAdBdCdDZed"dEdFdGdHZedddIdJdKdLZedIdMddNdOZed2dddPdQZed2dRddSdTZdEddUdVZd?ddWdXZdYddZd[d\Zd?dd]d^Z d_dd`daZ!dddbdcZ"dddddeZ#dddfdgZ$dddhdiZ%dS )lr   zkConnection to a MySQL Server.

    Args:
        settings (dict): Dictionary with connection settings.
    r  r|   r  rp   c                 C  s   || _ t | _d | _d | _|d| _|d| _|d| _d | _	|dg | _
d|kr|d r| j
|d|dd d t| j
|| _|dt| _| jd	krd | _d	| _g | _d
| _d| _d | _d S )Nr_   r`   ra   rd   rb   rc   rb   rc   ri   r   TF)r  r   streamprotocol	keep_openr  _user	_passwordZ_schema_active_resultr  rs   r  router_managerr   _connect_timeout_stmt_counter_prepared_stmt_ids_prepared_stmt_supported_server_disconnected_server_disconnected_reason)r   r  rx   rx   ry   r     s6    
 
zConnection.__init__r   c                 C  s   | j dk	r| j   d| _ dS )zFetch active result.N)r:  	fetch_allr   rx   rx   ry   fetch_active_result  s    

zConnection.fetch_active_resultrK   )r   rp   c                 C  s
   || _ dS )a  Set active result.

        Args:
            `Result`: It can be :class:`mysqlx.Result`,
                      :class:`mysqlx.BufferingResult`,
                      :class:`mysqlx.RowResult`, :class:`mysqlx.SqlResult` or
                      :class:`mysqlx.DocResult`.
        N)r:  r   r   rx   rx   ry   set_active_result  s    	zConnection.set_active_resultc              
   C  s  d}| j  r&z| j  }| j| | j t| j}t| j}t	||| _
| j
 j}|rndd |D ni }| | d| jkr| jd }| j
j|d | jdtj}| jd}	|tjkrdn| |||	}
|   | j
|
 W dS  ttfk
r" } z|}|  W 5 d}~X Y qX q|dk	rrt|tjrrt| jdkr`td	| j d
td| j dt| jdkrt d| t dddS )a  Attempt to connect to the MySQL server.

        Raises:
            :class:`mysqlx.InterfaceError`: If fails to connect to the MySQL
                                            server.
            :class:`mysqlx.TimeoutError`: If connect timeout was exceeded.
        Nc                 S  s   i | ]}t |d  |qS r   )r0   lower)r!  caprx   rx   ry   
<dictcomp>)  s      z&Connection.connect.<locals>.<dictcomp>
attributesZsession_connect_attrsrk   rl   r   z9Connection attempt to the server was aborted. Timeout of z ms was exceededz8All server connection attempts were aborted. Timeout of z) ms was exceeded for each selected serverzCannot connect to host: ,Unable to connect to any of the target hostsi  )!r;  r+  r1  r5  r   r  r<  r6   r7   r8   r6  Zget_capabilitesZcapabilities_set_tls_capabilitiesr  set_capabilitiesr  r%   Z	PREFERREDDISABLED_set_compression_capabilities_authenticateZset_compressionr   r   r
  r~   re   timeoutr   r  r.   r)   )r   errorr   readerwriterZ	caps_datacaps
conn_attrsrk   
algorithms	algorithmr   rx   rx   ry   r     s^    	
 




  zConnection.connect)rV  rp   c                 C  sP  | j dtjkrdS | j r:| j dr6td dS d|krR|   t	dd}t
 dkrt \}}}zd|ko|d	d
 dk}W n tk
r   d}Y nX tjdk r|s|   td| jjdd | j| j dd| j dtj| j d| j d| j d| j d| j d d| j krL| j d }| jj|d dS )a  Set the TLS capabilities.

        Args:
            caps (dict): Dictionary with the server capabilities.

        Raises:
            :class:`mysqlx.OperationalError`: If SSL is not enabled at the
                                             server.
            :class:`mysqlx.RuntimeError`: If support for SSL is not available
                                          in Python.

        .. versionadded:: 8.0.21
        rf   Nz(SSL not required when using Unix socket.tlszSSL not enabled at serverFLinuxzOracle Linux.r   7)r-     	   z<The support for SSL is not available for this Python versionT)rZ  r]   rZ   r\   rY   r[   r^   rJ  rK  )r  r  r&   rO  r5  r   r2   warningclose_connectionr+   platformsystemrR   split
IndexErrorsysversion_infor   r6  rN  r   r   )r   rV  Zis_ol7distnamer   rr   rW  rx   rx   ry   rM  Y  sD    







	
z Connection._set_tls_capabilitiesNrn   zOptional[List[str]]Optional[str])rV  rk   rX  rp   c                   s  | d}|dkr6d}|tjkr(t|t| dS i }t|tr~|d d d D ]&}dd |d d	 d D ||d
 < qTn*|jj	j
D ]}dd |jjjD ||j< q| dg  d}|rdd |D }	 fdd|	D }
|
rt |
d }n|tjkrtdndS |dkrFtr,d kr,d}ntrBd krBd}nd}| krvd}|tjkrht|t| dS | jjd|id |S )a  Set the compression capabilities.

        If compression is available, negociates client and server algorithms.
        By trying to find an algorithm from the requested compression
        algorithms list, which is supported by the server.

        If no compression algorithms list is provided, the following priority
        is used:

        1) zstd_stream
        2) lz4_message
        3) deflate_stream

        Args:
            caps (dict): Dictionary with the server capabilities.
            compression (str): The compression connection setting.
            algorithms (list): List of requested compression algorithms.

        Returns:
            str: The compression algorithm.

        .. versionadded:: 8.0.21
        .. versionchanged:: 8.0.22
        rk   Nz8Compression requested but the server does not support itvalueobjfldc                 S  s"   g | ]}|d  d d  dqS )scalarv_stringrj  utf-8)decoder!  rj  rx   rx   ry   r"    s   z<Connection._set_compression_capabilities.<locals>.<listcomp>arrayrw   c                 S  s   g | ]}|j jjd qS )ro  )rm  rn  rj  rp  rq  rx   rx   ry   r"    s   rY  c                 S  s   g | ]}|t krt | qS rx   )r   r!  itemrx   rx   ry   r"    s   c                   s   g | ]}| kr|qS rx   rx   rs  Zserver_algorithmsrx   ry   r"    s      r   zmThe connection compression is set as required, but none of the provided compression algorithms are supported.Zzstd_streamZlz4_messageZdeflate_streamzFCompression requested but the compression algorithm negotiation failed)rk   )r  r%   r   r*   r2   r`  r~   r   rj  rk  rl  rr  rw   r   r)   r5   r4   r6  rN  )r   rV  rk   rX  Zcompression_datar   Zcompression_dictrl  rY  Zclient_algorithmsmatchedrx   ru  ry   rP    s\    






z(Connection._set_compression_capabilitiesc              
   C  s   | j d}|rL|tjkr$|   q|tjkr8|   q|tjkr|   nz| j	
 r`|   nfz|   W n tk
r   Y nX dS z|   W n2 tk
r } ztd| |W 5 d}~X Y nX dS )z#Authenticate with the MySQL server.rg   NzrAuthentication failed using MYSQL41 and SHA256_MEMORY, check username and password or try a secure connection err:)r  r  r$   ZPLAIN_authenticate_plainZSHA256_MEMORY_authenticate_sha256_memoryZMYSQL41_authenticate_mysql41r5  r   r)   )r   rg   r   rx   rx   ry   rQ    s.    







zConnection._authenticatec                 C  sH   t | j| j}| j|  | j }| j|| | j	  dS )z=Authenticate with the MySQL server using `MySQL41AuthPlugin`.N)
r   r8  r9  r6  send_auth_start	auth_nameread_auth_continuesend_auth_continue	auth_dataread_auth_okr   plugin
extra_datarx   rx   ry   ry    s
    
z Connection._authenticate_mysql41c                 C  sF   | j  stdt| j| j}| jj| |	 d | j
  dS )z;Authenticate with the MySQL server using `PlainAuthPlugin`.z>PLAIN authentication is not allowed via unencrypted connection)r~  N)r5  r   r)   r   r8  r9  r6  rz  r{  r~  r  )r   r  rx   rx   ry   rw    s    
zConnection._authenticate_plainc                 C  sH   t | j| j}| j|  | j }| j|| | j	  dS )zBAuthenticate with the MySQL server using `Sha256MemoryAuthPlugin`.N)
r   r8  r9  r6  rz  r{  r|  r}  r~  r  r  rx   rx   ry   rx  #  s
    
z&Connection._authenticate_sha256_memoryrL   )	statementrp   c                 C  s,   |j r(| j|j | j|j d|_ dS )zrDeallocates statement.

        Args:
            statement (Statement): A `Statement` based type object.
        FN)preparedr6  send_prepare_deallocatestmt_idr>  remove)r   r  rx   rx   ry   _deallocate_statement+  s    z Connection._deallocate_statementrJ   zgUnion[FindStatement, DeleteStatement, ModifyStatement, ReadStatement, RemoveStatement, UpdateStatement])msg_typer   r  rp   c                 C  sR   z|    | j||| W n tk
r8   d| _Y dS X | j|j d|_dS )zPrepares a statement.

        Args:
            msg_type (str): Message ID string.
            msg (mysqlx.protobuf.Message): MySQL X Protobuf Message.
            statement (Statement): A `Statement` based type object.
        FNT)	rC  r6  Zsend_prepare_preparer*   r?  r>  rs   r  r  r   r  r   r  rx   rx   ry   _prepare_statement6  s    zConnection._prepare_statementc                 C  s\  | j s| j||| dS |jrr| | | ||| | j sR| j||| dS | j||| d|_|  n|jr|j	s| j||| n|j	r|j
s| | | j||| d|_	|  n|j	s|j
s|js| ||| | j s| j||| dS | j||| n8|j	rP|j
rP| | | j||| d|_	|  |  dS )zExecutes the prepared statement pipeline.

        Args:
            msg_type (str): Message ID string.
            msg (mysqlx.protobuf.Message): MySQL X Protobuf Message.
            statement (Statement): A `Statement` based type object.
        NF)r?  r6  send_msg_without_psZdeallocate_prepare_executer  r  Zsend_prepare_executeZreset_exec_counterr  changedZrepeatedZincrement_exec_counterr  rx   rx   ry   _execute_prepared_pipelineS  s@    




z%Connection._execute_prepared_pipelinerF   r=   c                 C  sT   |j }| jdkrtdt|ts*td| jd|\}}| j||| t| S )zExecute a SQL statement.

        Args:
            sql (str): The SQL statement.

        Raises:
            :class:`mysqlx.ProgrammingError`: If the SQL statement is not a
                                              valid string.
        Nr   z'The SQL statement is not a valid stringsql)	r  r6  r+   r~   rn   r-   build_execute_statementr  r=   )r   r  r  r  r   rx   rx   ry   send_sql  s    

zConnection.send_sqlz$Union[AddStatement, InsertStatement]r;   c                 C  sN   | j dkrtd| j |\}}| j || d}t|trD|j}t| |S )a  Send an insert statement.

        Args:
            statement (`Statement`): It can be :class:`mysqlx.InsertStatement`
                                     or :class:`mysqlx.AddStatement`.

        Returns:
            :class:`mysqlx.Result`: A result object.
        Nr   )r6  r+   Zbuild_insertsend_msgr~   r>   idsr;   )r   r  r  r   r  rx   rx   ry   send_insert  s    

zConnection.send_insertz%Union[FindStatement, SelectStatement]zUnion[DocResult, RowResult]c                 C  s6   | j |\}}| ||| | r.t| S t| S )aD  Send an find statement.

        Args:
            statement (`Statement`): It can be :class:`mysqlx.SelectStatement`
                                     or :class:`mysqlx.FindStatement`.

        Returns:
            `Result`: It can be class:`mysqlx.DocResult` or
                      :class:`mysqlx.RowResult`.
        )r6  Z
build_findr  Zis_doc_basedr:   r<   r   r  r  r   rx   rx   ry   	send_find  s    zConnection.send_findz'Union[DeleteStatement, RemoveStatement]c                 C  s&   | j |\}}| ||| t| S )a  Send an delete statement.

        Args:
            statement (`Statement`): It can be :class:`mysqlx.RemoveStatement`
                                     or :class:`mysqlx.DeleteStatement`.

        Returns:
            :class:`mysqlx.Result`: The result object.
        )r6  build_deleter  r;   r  rx   rx   ry   send_delete  s    zConnection.send_deletez'Union[ModifyStatement, UpdateStatement]c                 C  s&   | j |\}}| ||| t| S )a  Send an delete statement.

        Args:
            statement (`Statement`): It can be :class:`mysqlx.ModifyStatement`
                                     or :class:`mysqlx.UpdateStatement`.

        Returns:
            :class:`mysqlx.Result`: The result object.
        )r6  Zbuild_updater  r;   r  rx   rx   ry   send_update  s    zConnection.send_updater   Optional[Dict[str, Any]]zOptional[Result])	namespacecmdraise_on_failfieldsrp   c                 C  sL   z,| j |||\}}| j || t| W S  tk
rF   |rB Y nX dS )a  Execute a non query command.

        Args:
            namespace (str): The namespace.
            cmd (str): The command.
            raise_on_fail (bool): `True` to raise on fail.
            fields (Optional[dict]): The message fields.

        Raises:
            :class:`mysqlx.OperationalError`: On errors.

        Returns:
            :class:`mysqlx.Result`: The result object.
        N)r6  r  r  r;   r+   )r   r  r  r  r  r  r   rx   rx   ry   execute_nonquery  s      
zConnection.execute_nonqueryr   r  rp   c                 C  sN   | j d|\}}| j || t| }|  |jdkrBtd|d d S )zExecute a SQL scalar.

        Args:
            sql (str): The SQL statement.

        Raises:
            :class:`mysqlx.InterfaceError`: If no data found.

        Returns:
            :class:`mysqlx.Result`: The result.
        r  r   zNo data found)r6  r  r  r<   rB  r   r)   )r   r  r  r   r   rx   rx   ry   execute_sql_scalar
  s    
zConnection.execute_sql_scalarr<   )r  r  rp   c                 C  s*   | j d||\}}| j || t| S )zReturns the row result.

        Args:
            cmd (str): The command.
            fields (dict): The message fields.

        Returns:
            :class:`mysqlx.RowResult`: The result object.
        mysqlx)r6  r  r  r<   )r   r  r  r  r   rx   rx   ry   get_row_result  s    zConnection.get_row_resultzOptional[MessageType]c                 C  s   | j |S )zdRead row.

        Args:
            result (:class:`mysqlx.RowResult`): The result object.
        )r6  read_rowrD  rx   rx   ry   r  .  s    zConnection.read_rowc                 C  s   | j | dS )zeClose result.

        Args:
            result (:class:`mysqlx.Result`): The result object.
        N)r6  close_resultrD  rx   rx   ry   r  7  s    zConnection.close_resultzList[ColumnType]c                 C  s   | j |S )zlGet column metadata.

        Args:
            result (:class:`mysqlx.Result`): The result object.
        )r6  r   rD  rx   rx   ry   r   @  s    zConnection.get_column_metadatac                 C  s   |  j d7  _ | j S )z|Returns the next statement ID.

        Returns:
            int: A statement ID.

        .. versionadded:: 8.0.16
        r   )r=  r   rx   rx   ry   get_next_statement_idI  s    z Connection.get_next_statement_idc                 C  s
   | j  S )zgCheck if connection is open.

        Returns:
            bool: `True` if connection is open.
        )r5  r   r   rx   rx   ry   r   T  s    zConnection.is_openzUnion[str, Tuple[str, int]])r   rp   c                 C  s   d| _ || _dS )zSet the disconnection message from the server.

        Args:
            reason (str): disconnection reason from the server.
        TN)r@  rA  )r   r   rx   rx   ry   r   \  s    z"Connection.set_server_disconnectedc                 C  s   | j S )zVerify if the session has been disconnect from the server.

        Returns:
            bool: `True` if the connection has been closed from the server
                  otherwise `False`.
        )r@  r   rx   rx   ry   r   e  s    z!Connection.is_server_disconnectedz%Optional[Union[str, Tuple[str, int]]]c                 C  s   | j S )zGet the disconnection message sent by the server.

        Returns:
            string: disconnection reason from the server.
        )rA  r   rx   rx   ry   r   n  s    z"Connection.get_disconnected_reasonc                 C  s   |   sdS | j  dS )zDisconnect from server.N)r   r5  r   r   rx   rx   ry   r   v  s    zConnection.disconnectc              
   C  s   |   sdS z~zD|   | jr<| jD ]}| j| q$d| _| j	  | j
  W n4 tttfk
r } ztd| W 5 d}~X Y nX W 5 | j  X dS )z*Close a sucessfully authenticated session.Nr   zGWarning: An error occurred while attempting to close the connection: %s)r   r5  r   rC  r?  r>  r6  r  r=  Z
send_closeread_okr)   r+   r   r2   r`  )r   r  r   rx   rx   ry   close_session|  s     

zConnection.close_sessionc              
   C  sl   |   sdS | jdk	r | j  z| j| j| _W n2 ttfk
rf } zt	d| W 5 d}~X Y nX dS )z*Reset a sucessfully authenticated session.NzDWarning: An error occurred while attempting to reset the session: %s)
r   r:  rB  r6  Z
send_resetr7  r)   r+   r2   r`  )r   r   rx   rx   ry   reset_session  s    

zConnection.reset_sessionc                 C  sB   |   sdS | jdk	r | j  | j  | j  | j  dS )zAnnounce to the server that the client wants to close the
        connection. Discards any session state of the server.
        N)r   r:  rB  r6  Zsend_connection_closer  r5  r   r   rx   rx   ry   ra    s    



zConnection.close_connection)N)N)&r   r   r   r   r   rC  rE  r   rM  rP  rQ  ry  rw  rx  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r   r   r   r   r   r  r  ra  rx   rx   rx   ry   r     s^   "F: c
>  		r   c                      st   e Zd ZdZddd fddZdd fdd	Zddd
dZddddZddddZdddddZ	  Z
S )r   a  Class to hold :class:`Connection` instances in a pool.

    PooledConnection is used by :class:`ConnectionPool` to facilitate the
    connection to return to the pool once is not required, more specifically
    once the close_session() method is invoked. It works like a normal
    Connection except for methods like close() and sql().

    The close_session() method will add the connection back to the pool rather
    than disconnecting from the MySQL server.

    The sql() method is used to execute sql statements.

    Args:
        pool (ConnectionPool): The pool where this connection must return.

    .. versionadded:: 8.0.13
    ConnectionPoolr|   )r   rp   c                   sB   t |tstdt |j || _|jd | _|jd | _d S )Nz&pool should be a ConnectionPool objectrb   rc   )	r~   r  r   r  r   
cnx_configr   rb   rc   )r   r   r  rx   ry   r     s    
zPooledConnection.__init__r   c                   s   t    dS )zGCloses the connection.

        This method closes the socket.
        N)r  r  r   r  rx   ry   ra    s    z!PooledConnection.close_connectionc                 C  s   | j |  dS )a  Do not close, but add connection back to pool.

        The close_session() method does not close the connection with the
        MySQL server. The connection is added back to the pool so it
        can be reused.

        When the pool is configured to reset the session, the session
        state will be cleared by re-authenticating the user once the connection
        is get from the pool.
        N)r   add_connectionr   rx   rx   ry   r    s    zPooledConnection.close_sessionc                 C  s    | j dk	r| j   |   dS )zReconnect this connection.N)r:  rB  rQ  r   rx   rx   ry   	reconnect  s    

zPooledConnection.reconnectc                 C  s   |    dS )zQReset the connection.

        Resets the connection by re-authenticate.
        N)r  r   rx   rx   ry   reset  s    zPooledConnection.resetrn   rF   r  c                 C  s
   t | |S a  Creates a :class:`mysqlx.SqlStatement` object to allow running the
        SQL statement on the target MySQL Server.

        Args:
            sql (string): The SQL statement to be executed.

        Returns:
            mysqlx.SqlStatement: SqlStatement object.
        )rF   r   r  rx   rx   ry   r    s    
zPooledConnection.sql)r   r   r   r   r   ra  r  r  r  r  r  rx   rx   r  ry   r     s   r   c                   @  s   e Zd ZdZddddddZdddd	d
ZeddddZd.dddddZddddZ	d/dddddZ
dddddZdddddZddddZd dd!d"Zd0ddd$d%d&Zddd'd(Zd)dd*d+Zddd,d-ZdS )1r  a  This class represents a pool of connections.

    Initializes the Pool with the given name and settings.

    Args:
        name (str): The name of the pool, used to track a single pool per
                    combination of host and user.
        **kwargs:
            max_size (int): The maximun number of connections to hold in
                            the pool.
            reset_session (bool): If the connection should be reseted when
                                  is taken from the pool.
            max_idle_time (int): The maximum number of milliseconds to allow
                                 a connection to be idle in the queue before
                                 being closed. Zero value means infinite.
            queue_timeout (int): The maximum number of milliseconds a
                                 request will wait for a connection to
                                 become available. A zero value means
                                 infinite.
            priority (int): The router priority, to choose this pool over
                            other with lower priority.

    Raises:
        :class:`mysqlx.PoolError` on errors.

    .. versionadded:: 8.0.13
    rn   r
   r|   )r   ro   rp   c                 K  s   |  | d| _g | _d| _d| _t | _|dd| _	t
j| | j	 |dd| _|dd| _|| _|dd| _|dd| _|| _|d	 | _|d
 | _d S )Nr   Tmax_size   r  max_idle_timequeue_timeoutr  rb   rc   )_set_pool_nameZ_open_sessions_connections_openned
_available_timeoutr   now_timeout_stampr  pool_max_sizequeueQueuer   r  r  r  r  r  r  rb   rc   )r   r   ro   rx   rx   ry   r     s     


zConnectionPool.__init__)	pool_namerp   c                 C  s@   t |rtd| dt|tkr6td| d|| _dS )a  Set the name of the pool.

        This method checks the validity and sets the name of the pool.

        Args:
            pool_name (str): The pool name.

        Raises:
            AttributeError: If the pool_name contains illegal characters
                            ([^a-zA-Z0-9._\-*$#]) or is longer than
                            connection._CNX_POOL_MAX_NAME_SIZE.
        zPool name 'z' contains illegal charactersz' is too longN)_CNX_POOL_NAME_REGEXr0  r   r   _CNX_POOL_MAX_NAME_SIZEr   )r   r  rx   rx   ry   r  ,  s
    
zConnectionPool._set_pool_namer   r   c                 C  s
   t | jS )zDReturns the number of open connections that can return to this pool.)r   r  r   rx   rx   ry   open_connections?  s    zConnectionPool.open_connectionsNzOptional[PooledConnection]cnxrp   c                 C  s   | j | dS )zwRemoves a connection from this pool.

        Args:
            cnx (PooledConnection): The connection object.
        N)r  r  r   r  rx   rx   ry   remove_connectionD  s    z ConnectionPool.remove_connectionc              
   C  sx   |   dkrtz| jd| jd}W n tjk
r6   Y q X z,z|  W n ttt	fk
r`   Y nX W 5 | | X q dS )z*Removes all the connections from the pool.r   TblockrR  N)
qsizer  r  r  Emptyr  ra  r   r   r)   r  rx   rx   ry   r   L  s    
z!ConnectionPool.remove_connectionsc                 C  s   | j std|  rtd|st| }|t  d d }tdd |	dd 	dD dkr|d	| j
   | j| n*t|tstd
| r|   |  | | dS )a=  Adds a connection to this pool.

        This method instantiates a Connection using the configuration passed
        when initializing the ConnectionPool instance or using the set_config()
        method.
        If cnx is a Connection instance, it will be added to the queue.

        Args:
            cnx (PooledConnection): The connection object.

        Raises:
            PoolError: If no configuration is set, if no more connection can
                       be added (maximum reached) or if the connection can not
                       be instantiated.
        z&Connection configuration not available'Failed adding connection; queue is fullr   c                 s  s   | ]}t |V  qd S r   r   r!  nrx   rx   ry   	<genexpr>u  s     z0ConnectionPool.add_connection.<locals>.<genexpr>-r\     r   
   set mysqlx_wait_timeout = z1Connection instance not subclass of PooledSessionN)r  r,   fullr   r  _SELECT_VERSION_QUERYexecuterB  tuplerd  r  r  rs   r~   r   r   r   queue_connection)r   r  verrx   rx   ry   r  [  s     &
zConnectionPool.add_connectionr   c              
   C  sf   t |tstd| jr |  z| j|dd W n. tjk
r` } ztd|W 5 d}~X Y nX dS )aG  Put 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.

        Args:
            PooledConnection: The connection object.

        Raises:
            PoolError: On errors.
        z2Connection instance not subclass of PooledSession.F)r  r  N)r~   r   r,   r  putr  Full)r   r  r   rx   rx   ry   r    s    
zConnectionPool.queue_connection)
connectionrp   c                 C  s   | j | dS )zETracks connection in order of close it when client.close() is invoke.N)r  rs   )r   r  rx   rx   ry   track_connection  s    zConnectionPool.track_connectionc                 C  s   | j S r   rF  r   rx   rx   ry   __str__  s    zConnectionPool.__str__r   c                 C  s   | j S )zReturns if this pool is available for pool connections from it.

        Returns:
            bool: True if this pool is available else False.
        .. versionadded:: 8.0.20
        )r  r   rx   rx   ry   r    s    zConnectionPool.available)time_outrp   c                 C  s.   | j r*td| | d| _ t | _|| _dS )zhSets this pool unavailable for a period of time (in seconds).

        .. versionadded:: 8.0.20
        z4ConnectionPool.set_unavailable pool: %s time_out: %sFN)r  r2   r`  r   r  r  r  )r   r  rx   rx   ry   r
    s    
zConnectionPool.set_unavailablec                 C  s   d| _ t | _dS )zaSets this pool available for pool connections from it.

        .. versionadded:: 8.0.20
        TN)r  r   r  r  r   rx   rx   ry   set_available  s    zConnectionPool.set_availablezTuple[int, datetime]c                 C  s   | j | jfS )zReturns the penalized time (timeout) and the time at the penalty.

        Returns:
            tuple: penalty seconds (int), timestamp at penalty (datetime object)
        .. versionadded:: 8.0.20
        )r  r  r   rx   rx   ry   get_timeout_stamp  s    z ConnectionPool.get_timeout_stampc                 C  s   | j D ]}|  qdS )zEmpty this ConnectionPool.N)r  ra  r  rx   rx   ry   r     s    
zConnectionPool.close)N)N)r  )r   r   r   r   r   r  propertyr  r  r   r  r  r  r  r  r
  r  r  r   rx   rx   rx   ry   r    s    *		r  c                   @  s  e Zd ZU dZdZd ed< i Zded< d dddZd	d	d
dddZdddddZ	e
dddddZdddddZe
dddddZe
dddddd d!Zdddd"d#d$Ze
d5dd%dd"d&d'Zd6dd(dd)d*d+Zdd,dd-d.Zdddd/d0Ze
dd1dd2d3d4ZdS )7r   zManages a pool of connections for a host or hosts in routers.

    This class handles all the pools of Connections.

    .. versionadded:: 8.0.13
    N_PoolsManager__instancer  _PoolsManager__poolsr   c                 C  s"   t jd krt| t _i t _t jS r   )r   r  object__new__r  )clsrx   rx   ry   r    s    
zPoolsManager.__new__rn   r   )rq   r  rp   c                 C  s,   | j |g }|D ]}|j|kr dS qdS )zVerifies if a pool exists with the given name.

        Args:
            client_id (str): The client id.
            pool_name (str): The name of the pool.

        Returns:
            bool: Returns `True` if the pool exists otherwise `False`.
        TF)r  r  r   )r   rq   r  poolsr   rx   rx   ry   _pool_exists  s
    

zPoolsManager._pool_existsr   r3  c                 C  s^   g }g }|  |}|D ]\}}|| q| j|ddg D ]}|j|kr@|| q@|S )zRetrieves a list of pools that shares the given settings.

        Args:
            settings (dict): the configuration of the pool.

        Returns:
            list: A list of pools that shares the given settings.
        rq   No id)_get_connections_settingsrs   r  r  r   )r   r  Zavailable_poolsZ
pool_namesconnections_settingsrouter_namerr   r   rx   rx   ry   
_get_pools  s    	

zPoolsManager._get_poolsz List[Tuple[str, Dict[str, Any]]]c                 C  s   |   }|dg }g }d|kr*|d d|krVd|krV|dd|d |d d |jdd d	 |D ]T}|  }|d |d< |d |d< |d
 |d
< |dd|d< |tf ||f qj|S )aH  Generates a list of separated connection settings for each host.

        Gets a list of connection settings for each host or router found in the
        given settings.

        Args:
            settings (dict): The configuration for the connections.

        Returns:
            list: A list of connections settings
        rd   rb   rc   r  r   )r  weightrb   rc   c                 S  s   | d |  dd fS )Nr  r  r   )r  r  rx   rx   ry   r  )  r   z8PoolsManager._get_connections_settings.<locals>.<lambda>)rw   r  r  )r.  r  poprs   r   rz   )r  Zpool_settingsrd   r  r   Zconnection_settingsrx   rx   ry   r    s4    
	z&PoolsManager._get_connections_settingsr|   )cnx_settingsrp   c                 C  s~   |  |}|dd| jkr.g | j|dd< |D ]F\}}| |dd|rPq2| j|ddg }|t|f| q2dS )a#  Creates a `ConnectionPool` instance to hold the connections.

        Creates a `ConnectionPool` instance to hold the connections only if
        no other pool exists with the same configuration.

        Args:
            cnx_settings (dict): The configuration for the connections.
        rq   r  N)r  r  r  r  rs   r  )r   r  r  r  r  r   rx   rx   ry   create_pool8  s    	
zPoolsManager.create_poolzList[ConnectionPool]r  )	pool_listrp   c                 C  s<   | sdS t | dkr| d S t | d }td|}| | S )zGet a random router from the group with the given priority.

        Returns:
            Router: a random router.

        .. versionadded:: 8.0.20
        Nr   r   )r   r&  r'  )r  r(  r)  rx   rx   ry   _get_random_poolN  s    	zPoolsManager._get_random_poolr   )r  r)  r/  rp   c                 C  sZ   g }d }|t | k rV| | j}||krB| |  rB|| |  n
||krLqV|d7 }q|S )Nr   )r   r  r  rs   )r  r)  r/  ZsublistZnext_priorityrx   rx   ry   _get_sublist`  s    

zPoolsManager._get_sublist)r  r/  rp   c                 C  sb   d}|D ]"}|  r"||jkr" q,|d7 }qg }|sX|t|k rX| |||}|d7 }q0| |S )Nr   r   )r  r  r   r  r  )r   r  r/  r)  r   Zsubpoolrx   rx   ry   _get_next_poolo  s    

zPoolsManager._get_next_poolOptional[int]c                 C  s@   |d kr| r| d j S | D ]}| r|j }|  S q| d j S )Nr   )r  r  )r  r/  Zt_poolrx   rx   ry   _get_next_priority}  s    

zPoolsManager._get_next_priorityzOptional[bool])r  reviverp   c                 C  sT   |  |}|D ]@}| rq| \}}|r0|}t |t|d kr|  qd S )N)seconds)r  r  r  r   r  r   r  )r   r  r  r  r   rR  Ztimeout_stamprx   rx   ry   _check_unavailable_pools  s    
z%PoolsManager._check_unavailable_poolsr   c           
        s
  ddd fdd}|  |}|dd}g }| | | ||}|dkrTtd||d< | || t } dk	rz  d	kr| z jd
 j	d}W n  t
jk
r   tddY nX z,| r܈   |js|  || W nv tttfk
rl   z.z|  W n tttfk
r8   Y nX W 5  | X   d	krz jd
 j	d}W n t
jk
r   Y n>X z.z|  W n tttfk
r   Y nX W 5  | X qJzHz&t } | |  || W n tttfk
r
   Y nX W 5   d	krfz& jd
 j	d}|   | W n tttfk
r`   Y nX qX Y nX |W  5 Q R  W S Q R X n j jk rt } | |  || |W S |^ z4 jd
 j	d}|  || |W W  5 Q R  W S  t
jk
r   tddY nX W 5 Q R X W qp tttfk
r } z|d  d|  t|trp d n|  | | | | ||  dkr| ||}||d< | ||  dkrd|}	td|	 d|W Y qpW 5 d}~X Y qpX qptddS )a  Get a connection from the pool.

        This method returns an `PooledConnection` instance which has a reference
        to the pool that created it, and can be used as a normal Connection.

        When the MySQL connection is not connected, a reconnect is attempted.

        Raises:
            :class:`PoolError`: On errors.

        Returns:
            PooledConnection: A pooled connection object.
        r   r|   r  c                   sZ   |  t  d d }tdd |dd dD dkrV|  d j   d S )Nr   c                 s  s   | ]}t |V  qd S r   r  r  rx   rx   ry   r    s     zOPoolsManager.get_connection.<locals>.set_mysqlx_wait_timeout.<locals>.<genexpr>r  r\  r  r  )r  r  r  rB  r  rd  r  )r  r  r   rx   ry   set_mysqlx_wait_timeout  s    &z<PoolsManager.get_connection.<locals>.set_mysqlx_wait_timeoutr/  NzBUnable to connect to any of the target hosts. No pool is availabler   Tr  z)Failed getting connection; pool exhaustedzpool max size has been reachedzpool: z error: r-  z
  z2Unable to connect to any of the target hosts: [
  z
]rL  ) r  r  r  r  r,   r  	threadingRLockr  r  r  r  r   r   r7  r  r   r   r)   r  ra  r   r  r   r  r  r.   rs   r~   r
  r   ru   )
r   r  r  r  r/  Z
error_listlockr  r   r   rx   r  ry   get_connection  s    




 









zPoolsManager.get_connectionc                 C  sX   |  |}|D ]@}|  |dddk	r| j|d}||kr|| qt|S )zjCloses the connections in the pools

        Returns:
            int: The number of closed pools
        rq   N)r  r   r  r  r  r   )r   r  r  r   Zclient_poolsrx   rx   ry   
close_pool+  s    
zPoolsManager.close_poolz#Union[InterfaceError, TimeoutError])r   r   rp   c              	   C  sv   d}z|j }t| }W n ttfk
r.   Y nX |sX|j}t D ]\}}||krB|}qB|rh| | n
| d dS )a\  Sets a pool as unavailable.

        The time a pool is set unavailable depends on the given error message
        or the error number.

        Args:
            pool (ConnectionPool): The pool to set unavailable.
            err (Exception): The raised exception raised by a connection belonging
                             to the pool.
        Ni )errnor   r   rt   r   _TIMEOUT_PENALTIESitemsr
  )r   r   ZpenaltyZerr_noerr_msgrw   rj  rx   rx   ry   r   ;  s    z!PoolsManager.set_pool_unavailable)N)N)r   r   r   r   r  __annotations__r  r  r  r  staticmethodr  r  r  r  r  r  r  r  r  r   rx   rx   rx   ry   r     s0   
,   r   c                   @  sh  e Zd ZdZdddddZd ddd	Zd
ddddddZddddZeddddZ	e	j
dddddZ	ddddZdddddZdddd Zd!dd"d#Zdd$d%d&d'Zd(dd)d*Zddd%d+d,Zdd$d%d-d.Zddd/d0Zddd1d2Zddd3d4ZdAd6dd%d7d8Zddd%d9d:Zddd%d;d<Zddd=d>Zddd?d@Zd5S )BSessiona*  Enables interaction with a X Protocol enabled MySQL Product.

    The functionality includes:

    - Accessing available schemas.
    - Schema management operations.
    - Retrieval of connection information.

    Args:
        settings (dict): Connection data used to connect to the database.
    r  r|   r3  c              
   C  s  | dtj| _|| _| dr| drts6tdztj|d d}W n< tj	j
k
r } ztd|d  d|W 5 d }~X Y nX g | jd< |D ].}| jd |jjd	d
|j|j|jd qd| jks| jd dk	ri | jd< |   d|kr6|d r6t | t || _| jd krLtdnt| j| _| j  | j d}|rz| dt|   W nP tk
r } z0|jdkr|jn
d| d}t||j|W 5 d }~X Y nX d S )Nrh   rb   rm   ztMySQL host configuration requested DNS SRV. This requires the Python dnspython module. Please refer to documentationZSRVz Unable to locate any hosts for ''rd   T)Zomit_final_dot)rb   rc   r  r  rj   FrJ  poolingz+Connection could not be retrieved from poolra   zUSE i  Default schema '' does not exists)r  r3   use_purer  HAVE_DNSPYTHONr)   dnsresolverquery	exceptionZDNSExceptionrs   targetZto_textrc   r  r  _init_attributesr   r  r  _connectionr,   r   r   r  rH   r  r+   r  r   )r   r  Zsrv_recordsr   Zsrvra   errmsgrx   rx   ry   r   h  s^    







zSession.__init__r   c                 C  s   | S r   rx   r   rx   rx   ry   	__enter__  s    zSession.__enter__Type[BaseException]BaseExceptionr   exc_type	exc_value	tracebackrp   c                 C  s   |    d S r   r   r   r  r  r  rx   rx   ry   __exit__  s    zSession.__exit__c                 C  s  t jdkrRdt d kr d}ndt d kr6d}nt }dt d  }n<t }t d	krzd
t d  }ndt	 dd }t
d}|d dkrd}nd}tt  ||t dddd tdd D |d}| jd | d| jkr| jd D ]}| jd | }t|ts:td| dt|dkrXtd| d|drrtd| t|tstd| d| d t|d!krtd| d"| d#|| jd |< qd$S )%z5Setup default and user defined connection-attributes.r   Z64r   x86_64Z32i386zWindows-r   DarwinzmacOS-r  r-   ZGPLv2zGPL-2.0Z
Commercialzmysql-connector-pythonr\  c                 S  s   g | ]}t |qS rx   )rn   )r!  r  rx   rx   ry   r"    s     z,Session._init_attributes.<locals>.<listcomp>   )Z_pid	_platform_osZ_source_hostZ_client_nameZ_client_versionZ_client_licenserJ  rj   Attribute name '' must be a string type    "' exceeds 32 characters limit sizerr   zHKey names in 'session-connect-attributes' cannot start with '_', found: z	' value 'z'  must be a string type   
' value: '$' exceeds 1024 characters limit sizeN)r   r   rb  architecture	win32_vermachinerc  mac_verru   rR   rS   rd  rn   getpidre   gethostnamerT   r  r   r~   r)   r   
startswith)r   Zplatform_archZos_verZlicense_chunksZclient_licenseZdefault_attributes	attr_name
attr_valuerx   rx   ry   r    s`    




zSession._init_attributesr   c                 C  s   t jS )z8bool: `True` to use pure Python Protobuf implementation.)r3   r  r   rx   rx   ry   r    s    zSession.use_pure)rj  rp   c                 C  s    t |tstdt| d S )Nz)'use_pure' option should be True or False)r~   r   r-   r3   Zset_use_pure)r   rj  rx   rx   ry   r   	  s    
c                 C  s   | j j S )zzReturns `True` if the session is open.

        Returns:
            bool: Returns `True` if the session is open.
        )r  r5  r   r   rx   rx   ry   r   	  s    zSession.is_openrn   rF   r  c                 C  s   t | j|S r  )rF   r  r  rx   rx   ry   r  	  s    
zSession.sqlr   c                 C  s   | j S )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r  r   rx   rx   ry   r  	  s    zSession.get_connectionr   c                 C  s    |  d }dd | D S )zReturns the list of schemas in the current session.

        Returns:
            `list`: The list of schemas in the current session.

        .. versionadded:: 8.0.12
        zSHOW DATABASESc                 S  s   g | ]}|d  qS )r   rx   )r!  rowrx   rx   ry   r"  +	  s     z'Session.get_schemas.<locals>.<listcomp>)r  r  rB  rD  rx   rx   ry   get_schemas"	  s    zSession.get_schemasr(   )r   rp   c                 C  s
   t | |S )zRetrieves a Schema object from the current session by it's name.

        Args:
            name (string): The name of the Schema object to be retrieved.

        Returns:
            mysqlx.Schema: The Schema object with the given name.
        r'   r   r   rx   rx   ry   
get_schema-	  s    	zSession.get_schemazOptional[Schema]c                 C  sz   | j jd}|rv| tt|  }z |d d |krLt	| |W S W n& t
k
rt   td| ddY nX dS )a  Retrieves a Schema object from the current session by the schema
        name configured in the connection settings.

        Returns:
            mysqlx.Schema: The Schema object with the given name at connect
                           time.
            None: In case the default schema was not provided with the
                  initialization data.

        Raises:
            :class:`mysqlx.ProgrammingError`: If the provided default schema
                                              does not exists.
        ra   r   r  r  N)r  r  r  r  _SELECT_SCHEMA_NAME_QUERYformatr/   r  rB  r(   re  r-   )r   ra   resrx   rx   ry   get_default_schema8	  s    
zSession.get_default_schemac                 C  s   | j dtt|d dS )zDrops the schema with the specified name.

        Args:
            name (string): The name of the Schema object to be retrieved.
        r  TN)r  r  _DROP_DATABASE_QUERYr>  rH   r;  rx   rx   ry   drop_schemaV	  s
      zSession.drop_schemac                 C  s$   | j dtt|d t| |S )zCreates a schema on the database and returns the corresponding
        object.

        Args:
            name (string): A string value indicating the schema name.
        r  T)r  r  _CREATE_DATABASE_QUERYr>  rH   r(   r;  rx   rx   ry   create_schema`	  s      zSession.create_schemac                 C  s   | j ddd dS )z+Starts a transaction context on the server.r  zSTART TRANSACTIONTNr  r  r   rx   rx   ry   start_transactionl	  s    zSession.start_transactionc                 C  s   | j ddd dS )zXCommits all the operations executed after a call to
        startTransaction().
        r  ZCOMMITTNrE  r   rx   rx   ry   commitp	  s    zSession.commitc                 C  s   | j ddd dS )zYDiscards all the operations executed after a call to
        startTransaction().
        r  ZROLLBACKTNrE  r   rx   rx   ry   rollbackv	  s    zSession.rollbackNri  c                 C  sT   |dkrt   }n"t|tr.t| dkr6td| jddt	| d |S )a  Creates a transaction savepoint.

        If a name is not provided, one will be generated using the uuid.uuid1()
        function.

        Args:
            name (Optional[string]): The savepoint name.

        Returns:
            string: The savepoint name.
        Nr   Invalid SAVEPOINT namer  z
SAVEPOINT T)
uuidZuuid1r~   rn   r   stripr-   r  r  rH   r;  rx   rx   ry   set_savepoint|	  s      zSession.set_savepointc                 C  s@   t |trt| dkr"td| jddt| d dS )zRollback to a transaction savepoint with the given name.

        Args:
            name (string): The savepoint name.
        r   rI  r  zROLLBACK TO SAVEPOINT TNr~   rn   r   rK  r-   r  r  rH   r;  rx   rx   ry   rollback_to	  s    zSession.rollback_toc                 C  s@   t |trt| dkr"td| jddt| d dS )z{Release a transaction savepoint with the given name.

        Args:
            name (string): The savepoint name.
        r   rI  r  zRELEASE SAVEPOINT TNrM  r;  rx   rx   ry   release_savepoint	  s    zSession.release_savepointc                 C  s   | j   t| j| _ dS )zCloses the session.N)r  r  r   r  r   rx   rx   ry   r   	  s    
zSession.closec                 C  s   | j   dS )z8Closes all underliying connections as pooled connectionsN)r  ra  r   rx   rx   ry   close_connections	  s    zSession.close_connections)N)r   r   r   r   r   r  r!  r  r  r  setterr   r  r  r:  r<  r@  rB  rD  rF  rG  rH  rL  rN  rO  r   rP  rx   rx   rx   ry   r
  [  s2   ;M
r
  c                   @  s   e Zd ZdZd%ddddddZd d	d
dZdddddddZdddddZdddddZdddddZ	dddddZ
d d	d!d"Zdd	d#d$ZdS )&Clienta(  Class defining a client, it stores a connection configuration.

    Args:
        connection_dict (dict): The connection information to connect to a
                                MySQL server.
        options_dict (dict): The options to configure this client.

    .. versionadded:: 8.0.13
    Nr  r  r|   )connection_dictoptions_dictrp   c                 C  s   || _ |d kri }g | _t | _| |dd | |dd | |dd | 	|dd | j
| j d< | j| j d< | j| j d	< d S )
Nr  r  r  r   r  enabledTr  rq   )r  sessionsrJ  Zuuid4rq   _set_pool_sizer  _set_max_idle_time_set_queue_timeout_set_pool_enabledpooling_enabledr  )r   rS  rT  rx   rx   ry   r   	  s    
zClient.__init__r   c                 C  s   | S r   rx   r   rx   rx   ry   r  	  s    zClient.__enter__r  r  r   r  c                 C  s   |    d S r   r   r   rx   rx   ry   r!  	  s    zClient.__exit__r   )	pool_sizerp   c                 C  sB   t |tst |tr|dks,td| d|dkr8tn|| _dS )a  Set the size of the pool.

        This method sets the size of the pool but it will not resize the pool.

        Args:
            pool_size (int): An integer equal or greater than 0 indicating
                             the pool size.

        Raises:
            :class:`AttributeError`: If the pool_size value is not an integer
                                     greater or equal to 0.
        r   zGPool max_size value must be an integer greater than 0, the given value  is not validN)r~   r   r   r   _CNX_POOL_MAXSIZEr  )r   r\  rx   rx   ry   rW  	  s    
zClient._set_pool_size)r  rp   c                 C  sT   t |tst |tr|dks,td| d|| _|dkr>tn
t|d | jd< dS )a}  Set the max idle time.

        This method sets the max idle time.

        Args:
            max_idle_time (int): An integer equal or greater than 0 indicating
                                 the max idle time.

        Raises:
            :class:`AttributeError`: If the max_idle_time value is not an
                                     integer greater or equal to 0.
        r  zYConnection max_idle_time value must be an integer greater or equal to 0, the given value r]  r   r   r  N)r~   r   r   r   r  _CNX_POOL_MAX_IDLE_TIMEr  )r   r  rx   rx   ry   rX  	  s    
zClient._set_max_idle_timer   )rU  rp   c                 C  s   t |tstd|| _dS )a  Set if the pool is enabled.

        This method sets if the pool is enabled.

        Args:
            enabled (bool): True if to enabling the pool.

        Raises:
            :class:`AttributeError`: If the value of enabled is not a bool type.
        z*The enabled value should be True or False.N)r~   r   r   r[  )r   rU  rx   rx   ry   rZ  
  s    
zClient._set_pool_enabled)r  rp   c                 C  sj   t |tst |tr|dks,td| d|| _|dkr>tn
t|d | jd< d| jkrf| j| jd< dS )	a}  Set the queue timeout.

        This method sets the queue timeout.

        Args:
            queue_timeout (int): An integer equal or greater than 0 indicating
                                 the queue timeout.

        Raises:
            :class:`AttributeError`: If the queue_timeout value is not an
                                     integer greater or equal to 0.
        r  zYConnection queue_timeout value must be an integer greater or equal to 0, the given value r]  r   r   r  ri   N)r~   r   r   r   r  _CNX_POOL_QUEUE_TIMEOUTr  )r   r  rx   rx   ry   rY  '
  s    

zClient._set_queue_timeoutr
  c                 C  s   t | j}| j| |S )z~Creates a Session instance using the provided connection data.

        Returns:
            Session: Session object.
        )r
  r  rV  rs   r   sessionrx   rx   ry   get_sessionG
  s    
zClient.get_sessionc                 C  s&   t  | j | jD ]}|  qdS )z*Closes the sessions opened by this client.N)r   r  r  rV  rP  ra  rx   rx   ry   r   Q
  s    
zClient.close)N)r   r   r   r   r   r  r!  rW  rX  rZ  rY  rc  r   rx   rx   rx   ry   rR  	  s     
rR  z"Union[Dict[str, List[Dict]], Dict])pathrp   c           	      C  s  |  dd} d| ko.| ddko.| ddk oD| doD| d}g }t|r^| dd n| }d	}|D ]}i }t|}|r|d}t	|d
|d< |d7 }n t
|}|r|d}d|d< td| }|jstd| z|j|j|jd W n6 tk
r6 } ztd| d|W 5 d}~X Y nX || qld	|  k r`t|k rnn n
tdd|r|d|iS |d	 S )zParses a list of host, port pairs.

    Args:
        path: String containing a list of routers or just router

    Returns:
        Returns a dict with parsed values of host, port and priority if
        specified.
    r%   ,r   r   []r  r   r-  r  r  z//zInvalid address: r4  zInvalid URI: i  Nr  r  rd   )replacer   r6  endswith	_SPLIT_RErd  _PRIORITY_REmatchgroupr   
_ROUTER_REr   r   r)   r   rc   r   r-   rs   r   )	rd  rr  rd   Zaddress_listr  addressr   rm  r   rx   rx   ry   _parse_address_listX
  sD    
&




$ rq  r  )urirp   c                 C  s  ddi}t | }|r| nd| f\}} |dkrBtd| d|dkrRd|d	< | d
ddd \}}|dddd \}}|d}||d ddkr|dkr|dd\}|d< |d}|r|rd|krtd|  d|	dd\}	}
t
|	t
|
 |d< |d< |dr,t
||d< n$|drBtdn|t| d}t|dD ]\}}|dd }||krtd | d|tkrt
|d||< n8| }|d!krd||< n|d"krd#||< n|||< q^|S )$aq  Parses the connection string and returns a dictionary with the
    connection settings.

    Args:
        uri: mysqlx URI scheme to connect to a MySQL server/farm.

    Returns:
        Returns a dict with parsed values of credentials and address of the
        MySQL server/farm.

    Raises:
        :class:`mysqlx.InterfaceError`: If contains a invalid option.
    ra   re  r  )r  
mysqlx+srvzScheme 'z' is not validrs  Trm   @Nr-  ?/)r  r   r   z()r   zMalformed URI 'r  r_   r`   )rv  rM   r\  re   z\.zWindows Pipe is not supported)r_   r`   rm   rr   r  zInvalid option: ')1true)0falseF)_URI_SCHEME_RErm  groupsr)   	partitionrfindfindrsplitrK  rd  r   r6  r   rq  r   ri  rG  	_SSL_OPTS)rr  r  rm  schemeuserinfotmprb   Z	query_strposr_   r`   Zinvalid_optionsrw   valoptZval_strrx   rx   ry   _parse_connection_uri
  sH    









r  r3  c           	   
   C  s   t |  t}|r0d|}td| dd| krR| d D ]}t|d q@nd| krbt|  d| kr| d }z&tt|t	r|
  n|| d< W n< ttfk
r } ztd| d  d|W 5 d	}~X Y nX d
| kr| d tjtjfkrtdd| krd
| krtdd| kr2d| kr2tdd
| kr`| dtjtjtjfkr`tdd| kr| d }z(tt|t	r|
  n|| d< W n> ttfk
r } ztd| d  d|W 5 d	}~X Y nX d| krT| d }z(tt|t	r|
  n|| d< W n> ttfk
rR } ztd| d  d|W 5 d	}~X Y nX d| krt| d t	r| d  d}|r|d| d< nd	| d< nt| d ttfstd| dtjkrd	| d< d| krt|  d| krZzFt| d t	rt| d | d< t| d tr2| d dk r6tW n  tk
rX   tdd	Y nX d| krt| d ts|td | d!rtd"| d#rtd$| drtd%nd| kr| d#sd| d#< d&| krt|  d'| krt|  d	S )(an  Validates the settings to be passed to a Session object
    the port values are converted to int if specified or set to 33060
    otherwise. The priority values for each router is converted to int
    if specified.

    Args:
        settings: dict containing connection settings.

    Raises:
        :class:`mysqlx.InterfaceError`: On any configuration issue.
    z', 'zInvalid option(s): 'r  rd   r,  rb   rf   zInvalid SSL Mode 'NrZ   zCannot verify Server without CAr\   zCA Certificate not providedr[   rY   zClient Certificate not providedz$Must verify Server if CA is providedrg   zInvalid Auth 'rk   zpThe connection property 'compression' acceptable values are: 'preferred', 'required', or 'disabled'. The value 'z' is not acceptablerl   z[]rf  z@Invalid type of the connection property 'compression-algorithms'rj   ri   r   zEThe connection timeout value must be a positive integer (including 0)rm   z(The value of 'dns-srv' must be a booleanre   z<Using Unix domain sockets with DNS SRV lookup is not allowedrc   z;Specifying a port number with DNS SRV lookup is not allowedzASpecifying multiple hostnames with DNS SRV look up is not allowedr]   r^   )setkeys
difference
_SESS_OPTSru   r)   _validate_hostsr&   r~   rn   rG  rK  r   r   r   Z	VERIFY_CAr  rO  r$   r%   rd  listr  _validate_connection_attributesr   	TypeErrorr   _validate_tls_versions_validate_tls_ciphersuites)	r  Zinvalid_optsZinvalid_opts_listr   r   r   rg   rk   Zcompression_algorithmsrx   rx   ry   _validate_settings
  s    
(
(








r  r  )r  default_portrp   c                 C  s   d| kr| d rz6t | d | d< | d dk s:| d dkrDtddW nH tk
rf   tdddY n* tk
r   td| d  ddY nX d	| kr| d	 rzt | d	 | d	< W q tk
r   td
dY qX nd| kr|r|| d	< dS )zValidate hosts.

    Args:
        settings (dict): Settings dictionary.
        default_port (int): Default connection port.

    Raises:
        :class:`mysqlx.InterfaceError`: If priority or port are invalid.
    r  r   r  z1Invalid priority value, must be between 0 and 100r  zInvalid priorityNzInvalid priority: rc   zInvalid portrb   )r   r-   	NameErrorr   r)   )r  r  rx   rx   ry   r  S  s0     r  c           	      C  s  i }d| krdS | d }t |tr|dkr6i | d< dS |drJ|dsb|dkrbtd| d|dkr|d	kr|d
| d< ni | d< dS |dd d}|D ]X}|dkrq|d}|d }t|dkr|d nd}||krtd| d|||< qn$t |tr:|D ]*}|| }t |ts,t|}|||< qnt |t	sP|dkrl|r`i | d< nd
| d< dS t |t
r|D ]}d||< q|nt |tr|D ]b}|dkrq|d}|d }t|dkr|d nd}||krtd| d|||< qnt |t	s td| d|r| D ]\}}t |tsRtd| dt|dkrptd| d|drtd| dt |tstd| d| dt|dkr.td| d| dq.|| d< dS )zValidate connection-attributes.

    Args:
        settings (dict): Settings dictionary.

    Raises:
        :class:`mysqlx.InterfaceError`: If attribute name or value exceeds size.
    rj   Nre  rg  rh  )Falser{  Truery  z]The value of 'connection-attributes' must be a boolean or a list of key-value pairs, found: 'r  )r  r{  Fr   r  rf  =r   zDuplicate key 'z' used in connection-attributes)r   r   zLconnection-attributes must be Boolean or a list of key-value pairs, found: 'r)  r*  r+  r,  rr   zBKey names in connection-attributes cannot start with '_', found: 'zAttribute 'r.  r-  r/  )r~   rn   r6  rj  r)   rd  r   r   reprr   r  r  r  )	r  rJ  rW  Zconn_attributesattrZattr_name_valr7  Zattr_valr8  rx   rx   ry   r  w  s    	













r  c           	      C  s  g }d| krdS | d }t |tr|dr6|dsFtd| d|dd d	}|D ]:}| }|d
krrq\||krttjd|d|	| q\nt |t
r|std|D ](}||krttjd|d|	| qn>t |tr|D ]}|	| qntddt d| d|s,tdg }g }g }|D ]:}|tkrT|	| |tkrj|	| n
|	| q<|r|dgkrtstt|t|  || d< n.|rtt|tn|rtt|tdS )zValidate tls-versions.

    Args:
        settings (dict): Settings dictionary.

    Raises:
        :class:`mysqlx.InterfaceError`: If tls-versions name is not valid.
    r]   Nrg  rh  z%tls-versions must be a list, found: 'r  r   r  rf  re  tls_versionsr  rj  zKAt least one TLS protocol version must be specified in 'tls-versions' list.z>tls-versions should be a list with one or more of versions in r   z
. found: 'r   )r~   rn   r6  rj  r)   rd  rK  rN   r>  rs   r  r  ru   r"   r    r   r*   rO   r   rP   rQ   )	r  r  Ztls_versions_settingsZtls_verstls_verr   Zuse_tls_versionsZdeprecated_tls_versionsZnot_tls_versionsrx   rx   ry   r    s    	

 





 r  c                 C  s  g }d| krdS | d }t |tr|dr6|dsFtd| d|dd d	}|sdtd
|D ]}|  }|rh|| qhn.t |t	t
frdd |D }ntd| d| dddkrtdd n| d dd }|jdd |d }g }i }g }	tdt|d  D ]"}
|t|
  |	t|
  q|D ]p}d|krf||	krf|| nJ||kr|| }||krttjd|d|| ntd| dqB|std
|| d< dS )zValidate tls-ciphersuites.

    Args:
        settings (dict): Settings dictionary.

    Raises:
        :class:`mysqlx.InterfaceError`: If tls-ciphersuites name is not valid.
    r^   Nrg  rh  z)tls-ciphersuites must be a list, found: 'r  r   r  rf  z:No valid cipher suite found in the 'tls-ciphersuites' listc                 S  s   g | ]}|r|qS rx   rx   )r!  tls_csrx   rx   ry   r"  d  s      z._validate_tls_ciphersuites.<locals>.<listcomp>zItls-ciphersuites should be a list with one or more ciphersuites. Found: 'r]   Tr   r   r  tls_ciphersuitesr  zThe value 'z.' in cipher suites is not a valid cipher suite)r~   rn   r6  rj  r)   rd  rK  upperrs   r  r  r  r"   r   r)  r   r#   r   r!   r   rN   r>  )r  r  Ztls_ciphersuites_settingsZtls_cssr  r  Znewer_tls_verZtranslated_namesZiani_cipher_suites_namesZossl_cipher_suites_namesr  r   Ztranslated_namerx   rx   ry   r  B  sz    	





 
r  )r   ro   rp   c                  O  s   i }| rZt | d tr$t| d }qt | d tr| d  D ]\}}|||dd< q>n&|r| D ]\}}|||dd< qf|stdt| |S )aZ  Parses the connection string and returns a dictionary with the
    connection settings.

    Args:
        *args: Variable length argument list with the connection data used
               to connect to the database. It can be a dictionary or a
               connection string.
        **kwargs: Arbitrary keyword arguments with connection data used to
                  connect to the database.

    Returns:
        mysqlx.Session: Session object.

    Raises:
        TypeError: If connection timeout is not a positive integer.
        :class:`mysqlx.InterfaceError`: If settings not provided.
    r   rr   r  zSettings not provided)r~   rn   r  r   r  ri  r)   r  )r   ro   r  rw   r  rx   rx   ry   _get_connection_settings  s    r  c                  O  s   t | |}t|S )a  Creates a Session instance using the provided connection data.

    Args:
        *args: Variable length argument list with the connection data used
               to connect to a MySQL server. It can be a dictionary or a
               connection string.
        **kwargs: Arbitrary keyword arguments with connection data used to
                  connect to the database.

    Returns:
        mysqlx.Session: Session object.
    )r  r
  )r   ro   r  rx   rx   ry   rc    s    
rc  zUnion[str, Dict[str, Any]])connection_stringoptions_stringrp   c           	   
   C  sd  t | ttfstdt| }t |ttfs4tdt |tr|zt|}W q tk
rx } ztd|W 5 d}~X Y qX n&i }| D ]\}}|||	dd< qt |tstdi }d|krZ|
d}t |tstd|
d	d
|d	< |
dd|d< |
dd|d< |
dd|d< t|dkr:td| t|dkrZtd|  t||S )a8  Creates a Client instance with the provided connection data and settings.

    Args:
        connection_string: A string or a dict type object to indicate the             connection data used to connect to a MySQL server.

            The string must have the following uri format::

                cnx_str = 'mysqlx://{user}:{pwd}@{host}:{port}'
                cnx_str = ('mysqlx://{user}:{pwd}@['
                           '    (address={host}:{port}, priority=n),'
                           '    (address={host}:{port}, priority=n), ...]'
                           '       ?[option=value]')

            And the dictionary::

                cnx_dict = {
                    'host': 'The host where the MySQL product is running',
                    'port': '(int) the port number configured for X protocol',
                    'user': 'The user name account',
                    'password': 'The password for the given user account',
                    'ssl-mode': 'The flags for ssl mode in mysqlx.SSLMode.FLAG',
                    'ssl-ca': 'The path to the ca.cert'
                    "connect-timeout": '(int) milliseconds to wait on timeout'
                }

        options_string: A string in the form of a document or a dictionary             type with configuration for the client.

            Current options include::

                options = {
                    'pooling': {
                        'enabled': (bool), # [True | False], True by default
                        'max_size': (int), # Maximum connections per pool
                        "max_idle_time": (int), # milliseconds that a
                            # connection will remain active while not in use.
                            # By default 0, means infinite.
                        "queue_timeout": (int), # milliseconds a request will
                            # wait for a connection to become available.
                            # By default 0, means infinite.
                    }
                }

    Returns:
        mysqlx.Client: Client object.

    .. versionadded:: 8.0.13
    z(connection_data must be a string or dictz+connection_options must be a string or dictzA'pooling' options must be given in the form of a document or dictNr  rr   r  z<'pooling' options must be given in the form document or dictrU  Tr  r  r  r   r  zUnrecognized pooling options: z!Unrecognized connection options: )r~   rn   r   r)   r  jsonloadsr   r  ri  r  r   r  rR  )	r  r  Zsettings_dictrT  r   rw   rj  Zpooling_options_dictZpooling_optionsrx   rx   ry   
get_client  sN    5




r  )N)r   
__future__r   typesr   r   r   PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2r   hasattrr   PROTOCOL_SSLv23r	   r   ImportErrorr  r   rb  r  r&  rere   rf  r  rJ  r   typingr
   r   r   r   r   r   r   r   r   Zdns.exceptionr  Zdns.resolverr  r   r   	functoolsr   Zjson.decoderr   urllib.parser   r   r   Zauthenticationr   r   r   	constantsr   r    r!   r"   r#   r$   r%   r&   Zcrudr(   errorsr)   r*   r+   r,   r-   r.   Zhelpersr/   r0   r1   r2   Zprotobufr3   r6  r4   r5   r6   r7   r8   r   r9   r:   r;   r<   r=   r  r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rd  rs   Zmysql.connector.abstractsrN   rO   rP   rQ   Zmysql.connector.utilsrR   Zmysql.connector.versionrS   rT   r   r   rA  rC  r=  r  r^  r  compiler  r_  r`  Z_PENALTY_SERVER_OFFLINEZ_PENALTY_MAXED_OUTZ_PENALTY_NO_ADD_INFOZ_PENALTY_CONN_TIMEOUTZ_PENALTY_WRONG_PASSWZ_PENALTY_RESTARTINGr  r   rk  VERBOSErl  ro  r|  r  r  rz   r   r   r  r   r  r  r   r   r  r  r   r
  rR  rq  r  r  r  r  r  r  r  rc  r  rx   rx   rx   ry   <module>   s0  
,
(
 4



 u>$      _I X     _ !7?  $p[Y$