U
    fwb                 	   @   s*  d Z z\ddlZdZejejejdZeedr:ejed< n
ej	ed< eedrZej
rZdZndZW n   dZd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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!m"Z"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZF ejGHd ddlImJZJ ddlKmLZLmMZM dZNdZOdZPdZQdZRdZSdZTeUdZVd ZWd ZXd!ZYd"ZZd#Z[d#Z\d$Z]d"Z^eZeZeYeYe\e[e[e]d%Z_d&e^iZ`d'd(d)d*Zaebd+Zcd,d- Zdd.d/ ZeG d0d1 d1efZgd2d3 ZhG d4d5 d5eiZjG d6d7 d7ZkG d8d9 d9efZlG d:d; d;elZmG d<d= d=ejnZoG d>d? d?efZpG d@dA dAefZqG dBdC dCefZrdS )Dz4Implementation of communication for MySQL X servers.    NT)TLSv1TLSv1.1TLSv1.2PROTOCOL_TLSTLSv1.3HAS_TLSv1_3F)datetime	timedeltawraps   )MySQL41AuthPluginPlainAuthPluginSha256MemoryAuthPlugin)InterfaceErrorNotSupportedErrorOperationalError	PoolErrorProgrammingErrorTimeoutErrorSchema)SSLModeAuthCOMPRESSION_ALGORITHMS)escapeget_item_or_attriani_to_openssl_cs_name)ProtocolMessageReaderMessageWriterHAVE_LZ4	HAVE_ZSTD)
BaseResultResult	RowResult	SqlResult	DocResult)SqlStatementAddStatementquote_identifier)Protobufz..)linux_distribution)VERSIONLICENSEi'  zDROP DATABASE IF EXISTS {0}z!CREATE DATABASE IF NOT EXISTS {0}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 denied  zThis 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  r2   ia  mysqlxc               	   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.
    )hostportuserZdatabase	client_idz.Failed generating pool name; specify pool_name_)appendstrKeyErrorr   join)kwargspartskey r@   5/tmp/pip-unpacked-wheel-mzf9r1ws/mysqlx/connection.pygenerate_pool_name   s    rB   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)Zpenalty_dictr@   r@   rA   !update_timeout_penalties_by_error   s    rG   c                   @   sl   e Zd ZdZdd ZefddZdd Zdd	 Zd
d Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )SocketStreamzImplements a socket stream.c                 C   s   d | _ d| _d| _d | _d S )NF)_socket_is_ssl
_is_socket_hostselfr@   r@   rA   __init__   s    zSocketStream.__init__c                 C   s   |dk	r|d }zt ||| _|d | _W nb tk
r   z0t  t j| _| j| | j| d| _W n t	k
r   t
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)socketcreate_connectionrI   rL   
ValueErrorAF_UNIX
settimeoutconnectrK   AttributeErrorr   )rN   paramsconnect_timeoutr@   r@   rA   rV      s    	
zSocketStream.connectc                 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)rI   r   recvRuntimeErrorr9   lenr<   )rN   countbufdatar@   r@   rA   read   s    	

zSocketStream.readc              
   C   sZ   | j dkrtdz| j | W n2 tj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.
        NrZ   zUnexpected socket error: {})rI   r   sendallrQ   errorformat)rN   ra   errr@   r@   rA   rc      s    
zSocketStream.sendallc                 C   sH   | j s
dS z| j tj | j   W n tjk
r<   Y nX d| _ dS )zClose the socket.N)rI   shutdownrQ   	SHUT_RDWRcloserd   rM   r@   r@   rA   ri      s    zSocketStream.closec                 C   s   |    d S Nri   rM   r@   r@   rA   __del__  s    zSocketStream.__del__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  _|r@z|| tj|_
W n@ ttjfk
r> } z|   td|W 5 d}~X Y nX |rz|| tj|_W n@ ttjfk
r } z|   td|W 5 d}~X Y nX |rz||| W n@ 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
r` } ztt$|W 5 d}~X Y nX |tjkrTd|_g }t%j&dkr| j"dks| 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} q2q|sT|   tdd|d| _-| j!. }	|	dkrd|	 d}t/0|t1 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	localhostz	127.0.0.1z$Unable to verify server identity: {}z, )r   r   zThis connection is using zZ which is now deprecated and will be removed in a future release of MySQL Connector/Python)2SSL_AVAILABLEri   r]   sslcreate_default_contextr   Z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   re   VERIFY_CRL_CHECK_LEAFverify_flagsload_cert_chainset_ciphersr<   r   wrap_socketrI   rL   CertificateErrorr:   osnamerQ   gethostbyaddrextendmatch_hostnamegetpeercertr9   rJ   versionwarningswarnDeprecationWarning)rN   Z
ssl_protosZssl_modeZssl_caZssl_crlZssl_certZssl_keyZssl_cipherscontextZtls_versionZssl_protocolrf   Z	hostnamesaliasesZmatch_foundZerrshostnameZwarn_msgr@   r@   rA   set_ssl  s    





 
   



zSocketStream.set_sslc                 C   s   | j S )zpVerifies if SSL is being used.

        Returns:
            bool: Returns `True` if SSL is being used.
        )rJ   rM   r@   r@   rA   is_sslv  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.
        )rK   rM   r@   r@   rA   	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.
        )rJ   rK   rM   r@   r@   rA   	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)rI   rM   r@   r@   rA   is_open  s    zSocketStream.is_openN)__name__
__module____qualname____doc__rO   _CONNECT_TIMEOUTrV   rb   rc   ri   rl   r   r   r   r   r   r@   r@   r@   rA   rH      s   prH   c                    s   t   fdd}|S )zDecorator used to catch socket.error or RuntimeError.

    Raises:
        :class:`mysqlx.InterfaceError`: If `socket.Error` or `RuntimeError`
                                        is raised.
    c           	         s  zt | ttfr$|  r$t|    | f||}t |tr| }|D ]P}|d tkrJt|d  }d	|d ||d f}t | ttfr| 
|  qqJ|W S  tjtttttfk
r } zވ jdkr|rt |d tr|d  }|r|d }t|d  }d	|d ||d f}t | trZ| j  |d dkrZt | jt|  t | ttfrt| 
| |   t| n
|    n
|    W 5 d}~X Y nX dS )zWrapper function.codezConnection close: {}: {}msgget_column_metadatar   r2   N)rC   
ConnectionPooledConnectionis_server_disconnectedr   get_disconnected_reasonr#   Zget_warningsCONNECTION_CLOSED_ERRORre   set_server_disconnectedrQ   rd   ConnectionResetErrorConnectionAbortedErrorr]   r   r   r&   poolremove_connectionsPoolsManagerset_pool_unavailable
disconnect)	rN   argsr=   resultr   warning	error_msgreasonrf   funcr@   rA   wrapper  sd    
 
  


z(catch_network_exception.<locals>.wrapperr
   )r   r   r@   r   rA   catch_network_exception  s    +r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )RouterzRepresents a set of connection parameters.

    Args:
       settings (dict): Dictionary with connection settings
    .. versionadded:: 8.0.20
    c                 C   s   |  | | dd| d< d S )N	availableT)rF   get)rN   Zconnection_paramsr@   r@   rA   rO     s    
zRouter.__init__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   r@   rM   r@   r@   rA   r     s    zRouter.availablec                 C   s   d| d< dS )z:Sets this Router unavailable to open connections.
        Fr   Nr@   rM   r@   r@   rA   set_unavailable  s    zRouter.set_unavailablec                 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.
        rQ   r4   r5   r@   rM   r@   r@   rA   get_connection_params  s    zRouter.get_connection_paramsN)r   r   r   r   rO   r   r   r   r@   r@   r@   rA   r     s
   r   c                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	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
    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)rN   routerssettingsr@   r@   rA   rO     s    zRouterManager.__init__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 ]L}|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 100i  z\You must either assign no priority to any of the routers or give a priority for every routeri  c                 S   s   | d S )Nr   r@   xr@   r@   rA   <lambda>  r[   z2RouterManager._ensure_priorities.<locals>.<lambda>T)r?   rm   )
r   r   r   r^   ry   r   keysr   r   r9   )rN   Zpriority_countrouterr   r@   r@   rA   r     s*    


z RouterManager._ensure_prioritiesc                 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 r@   )r   ).0r   r@   r@   rA   
<listcomp>*  s      z8RouterManager._get_available_routers.<locals>.<listcomp>r   )rN   r   router_listr@   r@   rA   _get_available_routers#  s    
z$RouterManager._get_available_routersc                 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)rN   r   r   lastindexr@   r@   rA   _get_random_connection_params-  s    
z+RouterManager._get_random_connection_paramsc                 C   s   | j S )zReturns the next connection parameters.

        Returns:
            bool: True if there is more server to failover to else False.
        )r   rM   r@   r@   rA   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.
        Fr4   rq   r5   i$  TNr      )r   r   r   copyr   r   r   r   r^   r   r   )rN   Zrouter_settingscur_priorityZrouters_priority_lensearchr   r@   r@   rA   get_next_routerE  s.    



zRouterManager.get_next_routerc                 C   s   | j S )zReturns the directory containing all the routers managed.

        Returns:
            dict: Dictionary with priorities as connection settings.
        r   rM   r@   r@   rA   get_routers_directoryg  s    z#RouterManager.get_routers_directoryN)r   r   r   r   rO   r   r   r   r   r   r   r@   r@   r@   rA   r     s   
!
"r   c                   @   sH  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdEddZ	dd Z
d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ed!d" Zed#d$ Zed%d& ZedFd'd(Zed)d* Zed+d, Zed-d. Zed/d0 Zed1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Z d;d< Z!d=d> Z"d?d@ Z#dAdB Z$dCdD Z%dS )Gr   zkConnection to a MySQL Server.

    Args:
        settings (dict): Dictionary with connection settings.
    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 )Nr6   passwordschemar   r4   r5   )r4   r5   connect-timeoutr   TF)r   rH   streamprotocol	keep_openr   _user	_passwordZ_schema_active_resultr   r9   r   router_managerr   _connect_timeout_stmt_counter_prepared_stmt_ids_prepared_stmt_supported_server_disconnected_server_disconnected_reason)rN   r   r@   r@   rA   rO   v  s2    

zConnection.__init__c                 C   s   | j dk	r| j   d| _ dS )zFetch active result.N)r   	fetch_allrM   r@   r@   rA   fetch_active_result  s    

zConnection.fetch_active_resultc                 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   rN   r   r@   r@   rA   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d}| jd}	|d	krdn| |||	}
|   | j
|
 W dS  tjtfk
r  } z|}|  W 5 d}~X Y qX q|dk	rlt|tjrlt| jd
kr\td| jtd| j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   )r   lower)r   capr@   r@   rA   
<dictcomp>  s   z&Connection.connect.<locals>.<dictcomp>
attributesZsession_connect_attrscompression	preferredzcompression-algorithmsdisabledr   zLConnection attempt to the server was aborted. Timeout of {0} ms was exceededzdAll server connection attempts were aborted. Timeout of {0} ms was exceeded for each selected serverzCannot connect to host: {0},Unable to connect to any of the target hostsi  )r   r   r   r   rV   r   r   r   r    r   r   Zget_capabilitesZcapabilities_set_tls_capabilitiesr   set_capabilitiesr   _set_compression_capabilities_authenticateZset_compressionrQ   rd   r]   r   rC   timeoutr^   r   r   re   r   )rN   rd   r   readerwriterZ	caps_datacaps
conn_attrsr   
algorithms	algorithmrf   r@   r@   rA   rV     sd    	





zConnection.connectc                 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
        zssl-modeNz(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)r  ztls-versionszssl-cazssl-crlzssl-certzssl-keyztls-ciphersuitesr   r   )r   r   r   ZDISABLEDr   r   _LOGGERr   close_connectionr   platformsystemr,   split
IndexErrorsysversion_infor]   r   r  r   rv   )rN   r  Zis_ol7distnamer   r8   r  r@   r@   rA   r     sB    








z Connection._set_tls_capabilitiesNc                    s  | d}|dkr4d}|dkr&t|t| dS i }t|tr||d d d D ]&}dd	 |d d
 d D ||d < qRn*|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|dkrtdndS |dkrBtr(d kr(d}ntr>d kr>d}nd}| krpd}|dkrbt|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
        r   Nz8Compression requested but the server does not support itrequiredvalueobjfldc                 S   s"   g | ]}|d  d d  dqS )scalarv_stringr  utf-8)decoder   r  r@   r@   rA   r   ?  s   z<Connection._set_compression_capabilities.<locals>.<listcomp>arrayr?   c                 S   s   g | ]}|j jjd qS )r   )r  r  r  r!  r"  r@   r@   rA   r   E  s   r
  c                 S   s   g | ]}|t krt | qS r@   )r   r   itemr@   r@   rA   r   Q  s   c                    s   g | ]}| kr|qS r@   r@   r$  Zserver_algorithmsr@   rA   r   U  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)r   )r   r   r  r   rC   rD   r  r  r  r#  r?   r   r   r"   r!   r   r  )rN   r  r   r	  Zcompression_datar   Zcompression_dictr  r
  Zclient_algorithmsmatchedr@   r&  rA   r    sZ    









z(Connection._set_compression_capabilitiesc              
   C   s   | j d}|rL|tjkr$|   q|tjkr8|   q|tjkr|   nx| j	
 r`|   ndz|   W n tk
r   Y nX dS z|   W n0 tk
r } ztd| W 5 d}~X Y nX dS )z#Authenticate with the MySQL server.authNzrAuthentication 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_mysql41r   r   r   )rN   r(  rf   r@   r@   rA   r  w  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   r   r   r   send_auth_start	auth_nameread_auth_continuesend_auth_continue	auth_dataread_auth_okrN   plugin
extra_datar@   r@   rA   r+    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)r0  N)r   r   r   r   r   r   r   r,  r-  r0  r1  )rN   r3  r@   r@   rA   r)    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   r   r   r   r,  r-  r.  r/  r0  r1  r2  r@   r@   rA   r*    s
    
z&Connection._authenticate_sha256_memoryc                 C   s,   |j r(| j|j | j|j d|_ dS )zrDeallocates statement.

        Args:
            statement (Statement): A `Statement` based type object.
        FN)preparedr   send_prepare_deallocatestmt_idr   remove)rN   	statementr@   r@   rA   _deallocate_statement  s    z Connection._deallocate_statementc                 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)	r   r   Zsend_prepare_preparer   r   r   r9   r7  r5  rN   msg_typer   r9  r@   r@   rA   _prepare_statement  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   r   send_msg_without_psZdeallocate_prepare_executer:  r=  Zsend_prepare_executeZreset_exec_counterr5  changedZrepeatedZincrement_exec_counterr;  r@   r@   rA   _execute_prepared_pipeline  s@    	




z%Connection._execute_prepared_pipelinec                 C   sV   |j }| jdkrtdt|ts,tdn| 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.
        NrZ   z'The SQL statement is not a valid stringsql)	rA  r   r   rC   r:   r   build_execute_statementr>  r&   )rN   r9  rA  r<  r   r@   r@   rA   send_sql  s    


 zConnection.send_sqlc                 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.
        NrZ   )r   r   Zbuild_insertsend_msgrC   r)   idsr$   )rN   r9  r<  r   rE  r@   r@   rA   send_insert  s    

zConnection.send_insertc                 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`.
        )r   Z
build_findr@  Zis_doc_basedr'   r%   rN   r9  r<  r   r@   r@   rA   	send_find&  s    zConnection.send_findc                 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.
        )r   build_deleter@  r$   rG  r@   r@   rA   send_delete6  s    zConnection.send_deletec                 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.
        )r   Zbuild_updater@  r$   rG  r@   r@   rA   send_updateE  s    zConnection.send_updatec                 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)r   rB  rD  r$   r   )rN   	namespacecmdZraise_on_failfieldsr<  r   r@   r@   rA   execute_nonqueryT  s    
zConnection.execute_nonqueryc                 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.
        rA  r   zNo data found)r   rB  rD  r%   r   r_   r   )rN   rA  r<  r   r   r@   r@   rA   execute_sql_scalarm  s    
zConnection.execute_sql_scalarc                 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.
        r3   )r   rB  rD  r%   )rN   rM  rN  r<  r   r@   r@   rA   get_row_result  s    zConnection.get_row_resultc                 C   s   | j |S )zdRead row.

        Args:
            result (:class:`mysqlx.RowResult`): The result object.
        )r   read_rowr   r@   r@   rA   rR    s    zConnection.read_rowc                 C   s   | j | dS )zeClose result.

        Args:
            result (:class:`mysqlx.Result`): The result object.
        N)r   close_resultr   r@   r@   rA   rS    s    zConnection.close_resultc                 C   s   | j |S )zlGet column metadata.

        Args:
            result (:class:`mysqlx.Result`): The result object.
        )r   r   r   r@   r@   rA   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   rM   r@   r@   rA   get_next_statement_id  s    z Connection.get_next_statement_idc                 C   s
   | j  S )zgCheck if connection is open.

        Returns:
            bool: `True` if connection is open.
        )r   r   rM   r@   r@   rA   r     s    zConnection.is_openc                 C   s   d| _ || _dS )zSet the disconnection message from the server.

        Args:
            reason (str): disconnection reason from the server.
        TN)r   r   )rN   r   r@   r@   rA   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   rM   r@   r@   rA   r     s    z!Connection.is_server_disconnectedc                 C   s   | j S )zGet the disconnection message sent by the server.

        Returns:
            string: disconnection reason from the server.
        )r   rM   r@   r@   rA   r     s    z"Connection.get_disconnected_reasonc                 C   s   |   sdS | j  dS )zDisconnect from server.N)r   r   ri   rM   r@   r@   rA   r     s    zConnection.disconnectc              
   C   s   |   sdS zzD|   | jr<| jD ]}| j| q$d| _| j	  | j
  W n8 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: {})r   r   ri   r   r   r   r   r6  r   Z
send_closeread_okr   r   OSErrorr  r   re   )rN   r7  rf   r@   r@   rA   close_session  s    

zConnection.close_sessionc              
   C   sp   |   sdS | jdk	r | j  z| j| j| _W n6 ttfk
rj } 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: {})r   r   r   r   Z
send_resetr   r   r   r  r   re   )rN   rf   r@   r@   rA   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   r   r   Zsend_connection_closerU  r   ri   rM   r@   r@   rA   r    s    



zConnection.close_connection)N)N)&r   r   r   r   rO   r   r   rV   r   r  r  r+  r)  r*  r:  r=  r@  r   rC  rF  rH  rJ  rK  rO  rP  rQ  rR  rS  r   rT  r   r   r   r   r   rW  rX  r  r@   r@   r@   rA   r   p  s\   @5 
]
2









		r   c                       sL   e Zd ZdZ fddZ fddZdd Zdd	 Zd
d Z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
    c                    sF   t |tstdtt| |j || _|jd | _|jd | _	d S )Nz&pool should be a ConnectionPool objectr4   r5   )
rC   ConnectionPoolrW   superr   rO   
cnx_configr   r4   r5   )rN   r   	__class__r@   rA   rO   #  s    
zPooledConnection.__init__c                    s   t t|   dS )zGCloses the connection.

        This method closes the socket.
        N)rZ  r   rW  rM   r\  r@   rA   r  +  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_connectionrM   r@   r@   rA   rW  2  s    zPooledConnection.close_sessionc                 C   s    | j dk	r| j   |   dS )z#Reconnect this connection.
        N)r   r   r  rM   r@   r@   rA   	reconnect?  s    

zPooledConnection.reconnectc                 C   s   |    dS )zQReset the connection.

        Resets the connection by re-authenticate.
        N)r_  rM   r@   r@   rA   resetF  s    zPooledConnection.resetc                 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.
        )r(   rN   rA  r@   r@   rA   rA  M  s    
zPooledConnection.sql)r   r   r   r   rO   r  rW  r_  r`  rA  __classcell__r@   r@   r\  rA   r     s   r   c                   @   s   e Zd ZdZdd Zdd Zedd Zd d	d
Zdd Z	d!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dS )#rY  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
    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   rX  max_idle_timequeue_timeoutr   r4   r5   )_set_pool_nameZ_open_sessions_connections_openned
_available_timeoutr   now_timeout_stampr   pool_max_sizequeueQueuerO   rX  rf  r   rg  r   r[  r4   r5   )rN   r   r=   r@   r@   rA   rO   v  s     


zConnectionPool.__init__c                 C   s<   t |rtd|t|tkr2t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 '{0}' contains illegal characterszPool name '{0}' is too longN)_CNX_POOL_NAME_REGEXr   rW   re   r^   _CNX_POOL_MAX_NAME_SIZEr   )rN   	pool_namer@   r@   rA   rh    s    
zConnectionPool._set_pool_namec                 C   s
   t | jS )zMReturns the number of open connections that can return to this pool.
        )r^   ri  rM   r@   r@   rA   open_connections  s    zConnectionPool.open_connectionsNc                 C   s   | j | dS )zwRemoves a connection from this pool.

        Args:
            cnx (PooledConnection): The connection object.
        N)ri  r8  rN   cnxr@   r@   rA   remove_connection  s    z ConnectionPool.remove_connectionc              
   C   sz   |   dkrvz| jd| jd}W n tjk
r6   Y q X z.z|  W n ttj	t
fk
rb   Y nX W 5 | | X q dS )z*Removes all the connections from the pool.r   Tblockr  N)qsizer   rg  ro  Emptyrw  r  r]   rQ   rd   r   ru  r@   r@   rA   r     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   g | ]}t |qS r@   intr   nr@   r@   rA   r     s     z1ConnectionPool.add_connection.<locals>.<listcomp>-r     r   
   set mysqlx_wait_timeout = {}2Connection instance not subclass of PooledSession.N)r[  r   fullr   rA  _SELECT_VERSION_QUERYexecuter   tupler  re   rf  ri  r9   rC   r   r   ri   queue_connection)rN   rv  verr@   r@   rA   r^    s,     

zConnectionPool.add_connectionc                 C   sV   t |tstd| jr |  z| j|dd W n tjk
rP   td 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.
        r  F)ry  r|  N)rC   r   r   rX  putro  Fullru  r@   r@   rA   r    s    
zConnectionPool.queue_connectionc                 C   s   | j | dS )zNTracks connection in order of close it when client.close() is invoke.
        N)ri  r9   )rN   
connectionr@   r@   rA   track_connection  s    zConnectionPool.track_connectionc                 C   s   | j S rj   r   rM   r@   r@   rA   __str__  s    zConnectionPool.__str__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
        )rj  rM   r@   r@   rA   r     s    zConnectionPool.availablec                 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)rj  r  r   r   rl  rm  rk  )rN   Ztime_outr@   r@   rA   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)rj  r   rl  rm  rM   r@   r@   rA   set_available  s    zConnectionPool.set_availablec                 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
        )rk  rm  rM   r@   r@   rA   get_timeout_stamp#  s    z ConnectionPool.get_timeout_stampc                 C   s   | j D ]}|  qdS )z#Empty this ConnectionPool.
        N)ri  r  ru  r@   r@   rA   ri   ,  s    
zConnectionPool.close)N)N)r  )r   r   r   r   rO   rh  propertyrt  rw  r   r^  r  r  r  r   r   r  r  ri   r@   r@   r@   rA   rY  Z  s    


)	
	rY  c                   @   s   e Zd ZdZdZi Zdd Zdd Zdd Zd	d
 Z	dd Z
dd Zdd Zdd ZdddZdddZdd Zdd Zdd ZdS )r   zManages a pool of connections for a host or hosts in routers.

    This class handles all the pools of Connections.

    .. versionadded:: 8.0.13
    Nc                 C   s"   t jd krt| t _i t _t jS rj   )r   _PoolsManager__instanceobject__new___PoolsManager__pools)clsr@   r@   rA   r  =  s    
zPoolsManager.__new__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   )rN   r7   rs  poolsr   r@   r@   rA   _pool_existsC  s
    

zPoolsManager._pool_existsc                 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.
        r7   No id)_get_connections_settingsr9   r  r   r   )rN   r   Zavailable_poolsZ
pool_namesconnections_settingsrouter_namer8   r   r@   r@   rA   
_get_poolsS  s    	

zPoolsManager._get_poolsc                 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
        r   r4   r5   r   r   )r   weightr4   r5   c                 S   s   | d |  dd fS )Nr   r  r   )r   r   r@   r@   rA   r     r[   z8PoolsManager._get_connections_settings.<locals>.<lambda>)r?   r   r  )r   r   popr9   ry   rB   )rN   r   Zpool_settingsr   r  r   Zconnection_settingsr@   r@   rA   r  j  s0    
z&PoolsManager._get_connections_settingsc                 C   s   |  |}|dd| jkr.g | j|dd< |D ]H\}}| |dd|rRq2q2| 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.
        r7   r  N)r  r   r  r  r9   rY  )rN   cnx_settingsr  r  r   r   r@   r@   rA   create_pool  s    	
zPoolsManager.create_poolc                 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   )rN   Z	pool_listr   r   r@   r@   rA   _get_random_pool  s    zPoolsManager._get_random_poolc                 C   sZ   g }d }|t |k rV|| j}||krB||  rB|||  n
||krLqV|d7 }q|S )Nr   )r^   r   r   r9   )rN   r  r   r   ZsublistZnext_priorityr@   r@   rA   get_sublist  s    

zPoolsManager.get_sublistc                 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  )rN   r  r   r   r   Zsubpoolr@   r@   rA   _get_next_pool  s    

zPoolsManager._get_next_poolc                 C   s@   |d kr|r|d j S |D ]}| r|j }|  S q|d j S )Nr   )r   r   )rN   r  r   Zt_poolr@   r@   rA   _get_next_priority  s    

zPoolsManager._get_next_priorityc                 C   sT   |  |}|D ]@}| rq| \}}|r0|}t |t|d kr|  qd S )N)seconds)r  r   r  r   rl  r	   r  )rN   r   Zreviver  r   r  Ztimeout_stampr@   r@   rA   _check_unavailable_pools  s    
z%PoolsManager._check_unavailable_poolsc           	         s    fdd}|  |}|dd}g }| | | ||}|dkrLtd||d< | ||  dk	rz  dkrt  z jd j	d}W n t
jk
r   td	Y nX z,| rΈ   |js|  || W n ttjtfk
rh   z0z|  W n ttjtfk
r.   Y nX W 5  | X   dkrz jd j	d}W n t
jk
rz   Y n@X z0z|  W n ttjtfk
r   Y nX W 5  | X q@zJz&t } | |  || W n ttjtfk
r   Y nX W 5   dkrbz& jd j	d}|   | W n ttj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 t \ z4 jd j	d}|  || |W W  5 Q R  W S  t
jk
r   td
Y nX W 5 Q R X W q` tttfk
r } z|d | t|trj d n|   | | | | ||  dkr| ||}||d< | ||  dkrd!|}td|W Y q`W 5 d}~X Y q`X q`t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.
        c                    sZ   |  t  d d }tdd |dd dD dkrV|  d j  d S )Nr   c                 S   s   g | ]}t |qS r@   r}  r  r@   r@   rA   r     s     zPPoolsManager.get_connection.<locals>.set_mysqlx_wait_timeout.<locals>.<listcomp>r  r  r  r  )rA  r  r  r   r  r  re   rf  )rv  r  r   r@   rA   set_mysqlx_wait_timeout  s    z<PoolsManager.get_connection.<locals>.set_mysqlx_wait_timeoutr   NzCUnable to connect to any of the target hosts. No pool is available.r   Trx  z)Failed getting connection; pool exhaustedzpool max size has been reachedzpool: {} error: {}r   z
  z6Unable to connect to any of the target hosts: [
  {}
]r   )"r  r   r  r  r   r  rz  	threadingRLockrg  ro  r{  r   r   r   r`  r]   rQ   rd   r   rw  r  r   r  rV   rt  rn  r   r9   re   rC   r   r   r<   )	rN   r   r  r  r   Z
error_listrv  rf   r   r@   r  rA   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
        r7   N)r  ri   r   r  r8  r^   )rN   r  r  r   Zclient_poolsr@   r@   rA   
close_poolp  s    
zPoolsManager.close_poolc              	   C   sr   d}z|j }t| }W n ttfk
r.   Y nX |sT|j}tD ]}||kr>t| }q>|rd|| 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 )errnorE   rW   r;   r   _TIMEOUT_PENALTIESr   )rN   r   rf   ZpenaltyZerr_noerr_msgZtimeout_penaltyr@   r@   rA   r     s    
z!PoolsManager.set_pool_unavailable)N)N)r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r@   r@   r@   rA   r   3  s"   #

 r   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zed
d Z	e	j
dd Z	dd Zdd Zdd Zdd Zdd Zdd Z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d,d- Zd#S )/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.
    c              
   C   s  | dtj| _|| _| dr| drts6tdztj|d d}W n* tj	j
k
rv   td|d 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r$|d r$t | t || _| jd kr:tdnt| j| _| j  | j d}|rz| dt|  W nL tk
r } z,|jdkr|jnd|}t||jW 5 d }~X Y nX d S )Nzuse-purer4   zdns-srvztMySQL host configuration requested DNS SRV. This requires the Python dnspython module. Please refer to documentationZSRVz$Unable to locate any hosts for '{0}'r   T)Zomit_final_dot)r4   r5   r   r  connection-attributesFr   poolingz+Connection could not be retrieved from poolr   zUSE {}i  #Default schema '{}' does not exists) r   r+   use_purer   HAVE_DNSPYTHONr   dnsresolverquery	exceptionZDNSExceptionre   r9   targetZto_textr5   r   r  _init_attributesr   r  r  _connectionr   r   rV   rA  r*   r  r   r  r   )rN   r   Zsrv_recordsZsrvr   rf   errmsgr@   r@   rA   rO     sP    






zSession.__init__c                 C   s   | S rj   r@   rM   r@   r@   rA   	__enter__  s    zSession.__enter__c                 C   s   |    d S rj   rk   rN   exc_type	exc_value	tracebackr@   r@   rA   __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r|d
d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|t|dkrVtd||drptd|t|tstd||t|d krtd!|||| jd |< qd"S )#z5Setup default and user defined connection-attributes.rp   Z64r   x86_64Z32i386z
Windows-{}r   Darwinz{}-{}macOSr  r    ZGPLv2zGPL-2.0Z
Commercialzmysql-connector-pythonr  c                 S   s   g | ]}t |qS r@   )r:   )r   r   r@   r@   rA   r     s     z,Session._init_attributes.<locals>.<listcomp>   )Z_pid	_platform_osZ_source_hostZ_client_nameZ_client_versionZ_client_licenser   r  z)Attribute name '{}' must be a string type    z4Attribute name '{}' exceeds 32 characters limit sizer8   zJKey names in 'session-connect-attributes' cannot start with '_', found: {}z4Attribute name '{}' value '{}' must be a string typei   zBAttribute name '{}' value: '{}' exceeds 1024 characters limit sizeN)r   r   r  architecturere   	win32_vermachiner  mac_verr<   r,   r.   r  r:   getpidrQ   gethostnamer-   r   rF   rC   r   r^   
startswith)rN   Zplatform_archZos_verZlicense_chunksZclient_licenseZdefault_attributes	attr_name
attr_valuer@   r@   rA   r    sd    


  zSession._init_attributesc                 C   s   t jS )zAbool: `True` to use pure Python Protobuf implementation.
        )r+   r  rM   r@   r@   rA   r  (  s    zSession.use_purec                 C   s    t |tstdt| d S )Nz)'use_pure' option should be True or False)rC   boolr   r+   Zset_use_pure)rN   r  r@   r@   rA   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  r   r   rM   r@   r@   rA   r   4  s    zSession.is_openc                 C   s   t | j|S ra  )r(   r  rb  r@   r@   rA   rA  <  s    
zSession.sqlc                 C   s   | j S )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r  rM   r@   r@   rA   r  H  s    zSession.get_connectionc                 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   r@   )r   rowr@   r@   rA   r   Y  s     z'Session.get_schemas.<locals>.<listcomp>)rA  r  r   r   r@   r@   rA   get_schemasP  s    zSession.get_schemasc                 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   rN   r   r@   r@   rA   
get_schema[  s    	zSession.get_schemac                 C   sv   | j jd}|rr| tt|  }z |d d |krLt	| |W S W n" t
k
rp   t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.
        r   r   r  N)r  r   r   rA  _SELECT_SCHEMA_NAME_QUERYre   r   r  r   r   r  r   )rN   r   resr@   r@   rA   get_default_schemaf  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.
        rA  TN)r  rO  _DROP_DATABASE_QUERYre   r*   r  r@   r@   rA   drop_schema  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.
        rA  T)r  rO  _CREATE_DATABASE_QUERYre   r*   r   r  r@   r@   rA   create_schema  s      zSession.create_schemac                 C   s   | j ddd dS )z+Starts a transaction context on the server.rA  zSTART TRANSACTIONTNr  rO  rM   r@   r@   rA   start_transaction  s    zSession.start_transactionc                 C   s   | j ddd dS )zXCommits all the operations executed after a call to
        startTransaction().
        rA  ZCOMMITTNr  rM   r@   r@   rA   commit  s    zSession.commitc                 C   s   | j ddd dS )zYDiscards all the operations executed after a call to
        startTransaction().
        rA  ZROLLBACKTNr  rM   r@   r@   rA   rollback  s    zSession.rollbackNc                 C   sX   |dkrd t }n"t|tr2t| dkr:t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.
        Nz{0}r   Invalid SAVEPOINT namerA  zSAVEPOINT {0}T)re   uuidZuuid1rC   r:   r^   stripr   r  rO  r*   r  r@   r@   rA   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   r  rA  zROLLBACK TO SAVEPOINT {0}TN	rC   r:   r^   r  r   r  rO  re   r*   r  r@   r@   rA   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   r  rA  zRELEASE SAVEPOINT {0}TNr  r  r@   r@   rA   release_savepoint  s    zSession.release_savepointc                 C   s   | j   t| j| _ dS )zCloses the session.N)r  rW  r   r   rM   r@   r@   rA   ri     s    
zSession.closec                 C   s   | j   dS )z8Closes all underliying connections as pooled connectionsN)r  r  rM   r@   r@   rA   close_connections  s    zSession.close_connections)N)r   r   r   r   rO   r  r  r  r  r  setterr   rA  r  r  r  r  r  r  r  r  r  r  r  r  ri   r  r@   r@   r@   rA   r    s2   1H

	
r  c                   @   sZ   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd ZdS )Clienta7  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
    Nc                 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 )
Nrd  re  rf  r   rg  enabledTr  r7   )r   sessionsr  Zuuid4r7   _set_pool_sizer   _set_max_idle_time_set_queue_timeout_set_pool_enabledpooling_enabledrd  )rN   Zconnection_dictZoptions_dictr@   r@   rA   rO     s    
zClient.__init__c                 C   s   | S rj   r@   rM   r@   r@   rA   r    s    zClient.__enter__c                 C   s   |    d S rj   rk   r  r@   r@   rA   r    s    zClient.__exit__c                 C   s@   t |tst |tr|dks*td||dkr6t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   zWPool max_size value must be an integer greater than 0, the given value {} is not valid.N)rC   r  r~  rW   re   _CNX_POOL_MAXSIZErd  )rN   Z	pool_sizer@   r@   rA   r    s    zClient._set_pool_sizec                 C   sR   t |tst |tr|dks*t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  ziConnection max_idle_time value must be an integer greater or equal to 0, the given value {} is not valid.r   rP   rf  N)rC   r  r~  rW   re   rf  _CNX_POOL_MAX_IDLE_TIMEr   )rN   rf  r@   r@   rA   r  	  s    

zClient._set_max_idle_timec                 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)rC   r  rW   r  )rN   r  r@   r@   rA   r  *	  s    
zClient._set_pool_enabledc                 C   sh   t |tst |tr|dks*td||| _|dkr<tn
t|d | jd< d| jkrd| 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  ziConnection queue_timeout value must be an integer greater or equal to 0, the given value {} is not valid.r   rP   rg  r   N)rC   r  r~  rW   re   rg  _CNX_POOL_QUEUE_TIMEOUTr   )rN   rg  r@   r@   rA   r  9	  s    


zClient._set_queue_timeoutc                 C   s   t | j}| j| |S )z~Creates a Session instance using the provided connection data.

        Returns:
            Session: Session object.
        )r  r   r  r9   rN   sessionr@   r@   rA   get_sessionT	  s    
zClient.get_sessionc                 C   s&   t  | j | jD ]}|  qdS )z3Closes the sessions opened by this client.
        N)r   r  r   r  r  r  r@   r@   rA   ri   ^	  s    
zClient.close)N)r   r   r   r   rO   r  r  r  r  r  r  r  ri   r@   r@   r@   rA   r    s   	

r  )sr   rs   rr   PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2r{   hasattrr   PROTOCOL_SSLv23r   rz   r  rQ   loggingr  r  ro  r   r   rer  r   Zdns.resolverr  Zdns.exceptionImportErrorr  r   r	   	functoolsr   Zauthenticationr   r   r   errorsr   r   r   r   r   r   Zcrudr   	constantsr   r   r   Zhelpersr   r   r   r   r   r   r    r!   r"   r   r#   r$   r%   r&   r'   r9  r(   r)   r*   Zprotobufr+   pathr9   Zmysql.connector.utilsr,   Zmysql.connector.versionr-   r.   r   r  r  r  r  r  rr  compilerq  r  r  Z_PENALTY_SERVER_OFFLINEZ_PENALTY_MAXED_OUTZ_PENALTY_NO_ADD_INFOZ_PENALTY_CONN_TIMEOUTZ_PENALTY_WRONG_PASSWZ_PENALTY_RESTARTINGr  rE   r   	getLoggerr  rB   rG   r  rH   r   rD   r   r   r   r   rp  rY  r   r  r  r@   r@   r@   rA   <module>   s   



 
 	

 b6#      &I Z  k  C