3
S^u             
   @   s  d Z yddlZdZW n   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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mZmZmZ dd
lmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2 ej3j4d ddl5m6Z6 ddl7m8Z8m9Z9 dZ:dZ;dZ<dZ=dZ>dZ?e	j@dZAdZBdZCejDdZEdd ZFG dd  d eGZHd!d" ZIG d#d$ d$eGZJG d%d& d&eJZKG d'd( d(ejLZMG d)d* d*eGZNG d+d, d,eGZOG d-d. d.eGZPdS )/z4Implementation of communication for MySQL X servers.    NTF)wraps   )MySQL41AuthPluginPlainAuthPluginSha256MemoryAuthPlugin)InterfaceErrorNotSupportedErrorOperationalError	PoolErrorProgrammingErrorTimeoutError)PY3STRING_TYPESUNICODE_TYPESqueue)Schema)SSLModeAuth)escapeget_item_or_attr)ProtocolMessageReaderWriter)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 = '{}'c   x   z[^a-zA-Z0-9._:\-*$#]i  Zmysqlxc              K   sT   g }x8dD ]0}y|j t| |  W q
 tk
r8   Y q
X q
W |sJtddj|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userdatabase	client_idz.Failed generating pool name; specify pool_name_)r%   r&   r'   r(   r)   )appendstrKeyErrorr
   join)kwargspartskey r2   C/tmp/pip-build-8app2_gc/mysql-connector-python/mysqlx/connection.pygenerate_pool_nameS   s    

r4   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)selfr2   r2   r3   __init__q   s    zSocketStream.__init__c             C   s   |dk	r|d }yt j||| _|d | _W nb tk
r   y0t j t j| _| jj| | jj| d| _W n t	k
r   t
dY nX Y nX dS )zConnects to a TCP service.

        Args:
            params (tuple): The connection parameters.

        Raises:
            :class:`mysqlx.InterfaceError`: If Unix socket is not supported.
        Ni  r   TzUnix socket unsupported)socketcreate_connectionr6   r9   
ValueErrorAF_UNIX
settimeoutconnectr8   AttributeErrorr   )r:   paramsconnect_timeoutr2   r2   r3   rA   w   s    	
zSocketStream.connectc             C   s`   | j dkrtdg }x>|dkrT| j j|}|dkr<td|j| |t|8 }qW dj|S )zReceive data from the socket.

        Args:
            count (int): Buffer size.

        Returns:
            bytes: The data received.
        NzMySQLx Connection not availabler       zUnexpected connection close)r6   r	   recvRuntimeErrorr+   lenr.   )r:   countbufdatar2   r2   r3   read   s    	


zSocketStream.readc             C   s"   | j dkrtd| j j| dS )z_Send data to the socket.

        Args:
            data (bytes): The data to be sent.
        NzMySQLx Connection not available)r6   r	   sendall)r:   rK   r2   r2   r3   rM      s    
zSocketStream.sendallc             C   sH   | j s
dS y| j jtj | j j  W n tjk
r<   Y nX d| _ dS )zClose the socket.N)r6   shutdownr<   	SHUT_RDWRcloseerror)r:   r2   r2   r3   rP      s    zSocketStream.closec             C   s   | j   d S )N)rP   )r:   r2   r2   r3   __del__   s    zSocketStream.__del__c          ;   C   sJ  t s| j  tdttdr&tj}ntj}tj|}|j  |ry|j	| tj
|_W n> ttjfk
r } z| j  tdj|W Y dd}~X nX |ry|j	| tj|_W n> ttjfk
r } z| j  tdj|W Y dd}~X nX |rJy|j|| W n@ ttjfk
rH } z| j  tdj|W Y dd}~X nX |j| j| _|tjkr@g }	tjdkr| jdks| jd	krdd	g}	tj| j}
|	j|
d
 g|
d   d}g }x\|	D ]T}ytj| jj | W n0 tjk
r } z|j | W Y dd}~X nX d}P qW |s@| j  tdjdj!|d| _"dS )a  Set SSL parameters.

        Args:
            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.

        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 supportPROTOCOL_TLSzInvalid CA Certificate: {}NzInvalid CRL: {}zInvalid Certificate/Key: {}nt	localhostz	127.0.0.1r   r   FTz$Unable to verify server identity: {}z, )#SSL_AVAILABLErP   rG   hasattrsslrS   PROTOCOL_TLSv1
SSLContextload_default_certsload_verify_locationsCERT_REQUIREDverify_modeIOErrorSSLErrorr   formatVERIFY_CRL_CHECK_LEAFverify_flagsload_cert_chainwrap_socketr6   r   ZVERIFY_IDENTITYosnamer9   r<   gethostbyaddrextendmatch_hostnamegetpeercertCertificateErrorr+   r.   r7   )r:   Zssl_modeZssl_caZssl_crlZssl_certZssl_keyprotocolcontexterrZ	hostnamesaliasesZmatch_foundZerrshostnamer2   r2   r3   set_ssl   sd    


 
  
zSocketStream.set_sslc             C   s   | j S )zpVerifies if SSL is being used.

        Returns:
            bool: Returns `True` if SSL is being used.
        )r7   )r:   r2   r2   r3   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.
        )r8   )r:   r2   r2   r3   	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.
        )r7   r8   )r:   r2   r2   r3   	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)r6   )r:   r2   r2   r3   is_open  s    zSocketStream.is_openN)__name__
__module____qualname____doc__r;   _CONNECT_TIMEOUTrA   rL   rM   rP   rR   rr   rs   rt   ru   rv   r2   r2   r2   r3   r5   o   s   
Kr5   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@   y | f||S  t jtfk
r:   | j  tdY nX dS )zWrapper function.zCannot connect to hostN)r<   rQ   rG   
disconnectr   )r:   argsr/   )funcr2   r3   wrapper.  s
    z(catch_network_exception.<locals>.wrapper)r   )r~   r   r2   )r~   r3   catch_network_exception'  s    r   c               @   s4  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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d(d) Zed*d+ Zed,d- Zed.d/ Zed0d1 Zed2d3 Zd4d5 Zd6d7 Zd8d9 Z d:d; Z!d<d= Z"d>d? Z#d@S )A
ConnectionzkConnection to a MySQL Server.

    Args:
        settings (dict): Dictionary with connection settings.
    c             C   s   || _ t | _d | _d | _d | _|jd| _|jd| _|jd| _	d | _
|jdg | _d|kr|d r| jj|jd|jdd d d| _d	| _| j  | jjd
d d	d |jdt| _| jdkrd | _d| _g | _d	| _d S )Nr'   passwordschemaroutersr%   r&   )r%   r&   r   Tc             S   s   | d S )Npriorityr2   )xr2   r2   r3   <lambda>T  s    z%Connection.__init__.<locals>.<lambda>)r1   reversezconnect-timeoutr   )settingsr5   streamreader_writerrm   	keep_openget_user	_passwordZ_schema_active_result_routersr+   _cur_router_can_failover_ensure_prioritiessortr{   _connect_timeout_stmt_counter_prepared_stmt_ids_prepared_stmt_supported)r:   r   r2   r2   r3   r;   ?  s2    
zConnection.__init__c             C   s   | j dk	r| j j  d| _ dS )zFetch active result.N)r   	fetch_all)r:   r2   r2   r3   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   )r:   resultr2   r2   r3   set_active_resultf  s    	zConnection.set_active_resultc             C   s   d}d}xN| j D ]D}|jdd}|dkr:|d7 }||d< n|dkrLtdd|d8 }qW d|  k opt| j k n  rtdd	dS )
zuEnsure priorities.

        Raises:
            :class:`mysqlx.ProgrammingError`: If priorities are invalid.
        r   d   r   Nr   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  )r   r   r   rH   )r:   Zpriority_countr   routerprir2   r2   r3   r   q  s    
zConnection._ensure_prioritiesc             C   s   | j sFd| _d| jkr.| jd | jjddfS d| jkrB| jd S dS | j sX| jdkr|d| _d| _x| j D ]}d|d	< qlW |  jd7  _| j | j d }| j | j d }| jd
krd| j | jd  d	< | jt| j d krd| _||fS )zkReturns the connection parameters.

        Returns:
            tuple: The connection parameters.
        Fr%   r&   $  r<   rU   r   T	availabler   )rU   r   r   r   )r   r   r   r   r   rH   )r:   r   r%   r&   r2   r2   r3   _get_connection_params  s(    



z!Connection._get_connection_paramsc             C   s   d}xt| j rxy@| jj| j | j t| j| _t| j| _| j	  | j
  dS  tjk
rt } z
|}W Y dd}~X qX qW |dk	rt|tjs|jd
krt rt| jdkrtdj| jtdj| jt| jdkrtdj|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.
        N   s   r   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}z'Failed to connect to any of the routersi  )r   r   )r   r   rA   r   r   r   r   r   rm   _handle_capabilities_authenticater<   rQ   
isinstancetimeouterrnor   rH   r   r   ra   r   )r:   rQ   ro   r2   r2   r3   rA     s,    	

zConnection.connectc             C   s^  | j jdtjkrdS | jj r:| j jdr6tjd dS | jj	 j
}|r`t|d dj dkndst| j  tdd}tj d	krt \}}}yd
|ko|jdd dk}W n tk
r   d}Y nX tjdk r| r| j  td| jjdd | jj| j jdtj| j jd| j jd| j jd| j jd d| j krZ| j d }| jj|d dS )a1  Handle 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.
        zssl-modeNz(SSL not required when using Unix socket.r   rg   tlsFzSSL not enabled at serverLinuxzOracle Linux.7      	   z<The support for SSL is not available for this Python versionT)r   zssl-cazssl-crlzssl-certzssl-key
attributes)Zsession_connect_attrs)r   r   r   )r   r   r   ZDISABLEDr   rt   _LOGGERwarningrm   Zget_capabilitesZcapabilitiesr   lowerclose_connectionr	   platformsystemr    split
IndexErrorsysversion_inforG   Zset_capabilitiesrr   ZREQUIRED)r:   rK   Zis_ol7distnameversionr*   Z
conn_attrsr2   r2   r3   r     s<    	






zConnection._handle_capabilitiesc             C   s   | j jd}|rL|tjkr$| j  q|tjkr8| j  q|tjkr| j  nd| j	j
 r`| j  nPy| j  W n tk
r   Y nX dS y| j  W n tk
r   tdY nX dS )z#Authenticate with the MySQL server.authNzmAuthentication failed using MYSQL41 and SHA256_MEMORY, check username and password or try a secure connection)r   r   r   ZPLAIN_authenticate_plainZSHA256_MEMORY_authenticate_sha256_memoryZMYSQL41_authenticate_mysql41r   ru   r   )r:   r   r2   r2   r3   r     s&    







zConnection._authenticatec             C   sH   t | j| j}| jj|j  | jj }| jj|j| | jj	  dS )z=Authenticate with the MySQL server using `MySQL41AuthPlugin`.N)
r   r   r   rm   send_auth_start	auth_nameread_auth_continuesend_auth_continue	auth_dataread_auth_ok)r:   plugin
extra_datar2   r2   r3   r     s
    
z Connection._authenticate_mysql41c             C   sF   | j j stdt| j| j}| jj|j |j	 d | jj
  dS )z;Authenticate with the MySQL server using `PlainAuthPlugin`.z>PLAIN authentication is not allowed via unencrypted connection)r   N)r   ru   r   r   r   r   rm   r   r   r   r   )r:   r   r2   r2   r3   r   "  s    
zConnection._authenticate_plainc             C   sH   t | j| j}| jj|j  | jj }| jj|j| | jj	  dS )zBAuthenticate with the MySQL server using `Sha256MemoryAuthPlugin`.N)
r   r   r   rm   r   r   r   r   r   r   )r:   r   r   r2   r2   r3   r   ,  s
    
z&Connection._authenticate_sha256_memoryc             C   s,   |j r(| jj|j | jj|j d|_ dS )zrDeallocates statement.

        Args:
            statement (Statement): A `Statement` based type object.
        FN)preparedrm   send_prepare_deallocatestmt_idr   remove)r:   	statementr2   r2   r3   _deallocate_statement4  s    z Connection._deallocate_statementc             C   sP   y| j   | jj||| W n tk
r6   d| _dS X | j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   rm   Zsend_prepare_preparer   r   r   r+   r   r   )r:   msg_typemsgr   r2   r2   r3   _prepare_statement?  s    zConnection._prepare_statementc             C   sb  | j s| jj||| dS |jrr| j| | j||| | j sR| jj||| dS | jj||| d|_|j  n|jr|j	 r| jj||| n|j	r|j
 r| j| | jj||| d|_	|j  n|j	 o|j
 r|js| j||| | j s| jj||| dS | jj||| n8|j	rV|j
rV| j| | jj||| d|_	|j  |j  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   rm   send_msg_without_psZdeallocate_prepare_executer   r   Zsend_prepare_executeZreset_exec_counterr   changedZrepeatedZincrement_exec_counter)r:   r   r   r   r2   r2   r3   _execute_prepared_pipelineP  s@    	




z%Connection._execute_prepared_pipelinec             G   s   |j }| jdkrtdt|ts*tdt rZt|trZ| jjdt	t
|d|\}}n| jjd||\}}| jj||| t| S )a  Execute a SQL statement.

        Args:
            sql (str): The SQL statement.
            *args: Arbitrary arguments.

        Raises:
            :class:`mysqlx.ProgrammingError`: If the SQL statement is not a
                                              valid string.
        NzMySQLx Connection not availablez'The SQL statement is not a valid stringsqlzutf-8)r   rm   r	   r   r   r   r   r   build_execute_statementbytes	bytearrayr   r   )r:   r   r}   r   r   r   r2   r2   r3   send_sql  s    

zConnection.send_sqlc             C   sN   | j dkrtd| j j|\}}| 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.
        NzMySQLx Connection not available)rm   r	   Zbuild_insertsend_msgr   r   idsr   )r:   r   r   r   r   r2   r2   r3   send_insert  s    

zConnection.send_insertc             C   s6   | j j|\}}| j||| |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`.
        )rm   Z
build_findr   Zis_doc_basedr   r   )r:   r   r   r   r2   r2   r3   	send_find  s    zConnection.send_findc             C   s&   | j j|\}}| 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.
        )rm   build_deleter   r   )r:   r   r   r   r2   r2   r3   send_delete  s    zConnection.send_deletec             C   s&   | j j|\}}| 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.
        )rm   Zbuild_updater   r   )r:   r   r   r   r2   r2   r3   send_update  s    zConnection.send_updatec             G   sJ   y*| j j|||\}}| j j|| t| S  tk
rD   |r@ Y nX dS )az  Execute a non query command.

        Args:
            namespace (str): The namespace.
            cmd (str): The command.
            raise_on_fail (bool): `True` to raise on fail.
            *args: Arbitrary arguments.

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

        Returns:
            :class:`mysqlx.Result`: The result object.
        N)rm   r   r   r   r	   )r:   	namespacecmdZraise_on_failr}   r   r   r2   r2   r3   execute_nonquery  s    zConnection.execute_nonqueryc             G   sP   | j jd||\}}| j j|| t| }|j  |jdkrDtd|d d S )a  Execute a SQL scalar.

        Args:
            sql (str): The SQL statement.
            *args: Arbitrary arguments.

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

        Returns:
            :class:`mysqlx.Result`: The result.
        r   r   zNo data found)rm   r   r   r   r   rI   r   )r:   r   r}   r   r   r   r2   r2   r3   execute_sql_scalar  s    
zConnection.execute_sql_scalarc             G   s*   | j jd||\}}| j j|| t| S )zReturns the row result.

        Args:
            cmd (str): The command.
            *args: Arbitrary arguments.

        Returns:
            :class:`mysqlx.RowResult`: The result object.
        Zxplugin)rm   r   r   r   )r:   r   r}   r   r   r2   r2   r3   get_row_result  s    zConnection.get_row_resultc             C   s   | j j|S )zdRead row.

        Args:
            result (:class:`mysqlx.RowResult`): The result object.
        )rm   read_row)r:   r   r2   r2   r3   r     s    zConnection.read_rowc             C   s   | j j| dS )zeClose result.

        Args:
            result (:class:`mysqlx.Result`): The result object.
        N)rm   close_result)r:   r   r2   r2   r3   r   &  s    zConnection.close_resultc             C   s   | j j|S )zlGet column metadata.

        Args:
            result (:class:`mysqlx.Result`): The result object.
        )rm   get_column_metadata)r:   r   r2   r2   r3   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:   r2   r2   r3   get_next_statement_id8  s    z Connection.get_next_statement_idc             C   s
   | j j S )zgCheck if connection is open.

        Returns:
            bool: `True` if connection is open.
        )r   rv   )r:   r2   r2   r3   rv   C  s    zConnection.is_openc             C   s   | j  sdS | jj  dS )zDisconnect from server.N)rv   r   rP   )r:   r2   r2   r3   r|   K  s    zConnection.disconnectc             C   s   | j  sdS zyH| j  | jr@x| jD ]}| jj| q&W d| _| jj  | jj  W n6 t	t
fk
r } ztjdj| W Y dd}~X nX W d| jj  X dS )z*Close a sucessfully authenticated session.Nr   zGWarning: An error occurred while attempting to close the connection: {})rv   r   r   r   rm   r   r   Z
send_closeread_okr   r	   r   r   ra   r   rP   )r:   r   ro   r2   r2   r3   close_sessionQ  s    
zConnection.close_sessionc             C   sp   | j  sdS | jdk	r | jj  y| jj| j| _W n6 ttfk
rj } ztj	dj
| W Y dd}~X nX dS )z*Reset a sucessfully authenticated session.NzDWarning: An error occurred while attempting to reset the session: {})rv   r   r   rm   Z
send_resetr   r   r	   r   r   ra   )r:   ro   r2   r2   r3   reset_sessioni  s    

zConnection.reset_sessionc             C   sB   | j  sdS | jdk	r | jj  | jj  | 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)rv   r   r   rm   Zsend_connection_closer   r   rP   )r:   r2   r2   r3   r   u  s    



zConnection.close_connectionN)$rw   rx   ry   rz   r;   r   r   r   r   rA   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r|   r   r   r   r2   r2   r2   r3   r   9  s@   ! &.
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 )PooledConnectiona  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 || _|jd | _|jd | _	d S )Nz&pool should be a ConnectionPool objectr%   r&   )
r   ConnectionPoolrB   superr   r;   
cnx_configpoolr%   r&   )r:   r   )	__class__r2   r3   r;     s    
zPooledConnection.__init__c                s   t t| j  dS )zGCloses the connection.

        This method closes the socket.
        N)r   r   r   )r:   )r   r2   r3   r     s    z!PooledConnection.close_connectionc             C   s   | j 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_connection)r:   r2   r2   r3   r     s    zPooledConnection.close_sessionc             C   s    | j dk	r| j j  | j  dS )z#Reconnect this connection.
        N)r   r   r   )r:   r2   r2   r3   	reconnect  s    

zPooledConnection.reconnectc             C   s   | j   dS )zQReset the connection.

        Resets the connection by re-authenticate.
        N)r   )r:   r2   r2   r3   reset  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   )r:   r   r2   r2   r3   r     s    
zPooledConnection.sql)rw   rx   ry   rz   r;   r   r   r   r   r   __classcell__r2   r2   )r   r3   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dZ	dd Z
dd Zdd Zdd ZdS )r   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   | j | d| _g | _|jdd| _tjj| | j |jdd| _|jdd| _	|| _
|jdd| _|jdd| _|| _|d	 | _|d
 | _d S )Nr   max_size   r   Tmax_idle_timequeue_timeoutr   r%   r&   )_set_pool_nameZ_open_sessions_connections_opennedr   pool_max_sizer   Queuer;   r   r   r   r   Z	_priorityr   r%   r&   )r:   rg   r/   r2   r2   r3   r;     s    

zConnectionPool.__init__c             C   s<   t j|rtdj|t|tkr2tdj||| _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_REGEXsearchrB   ra   rH   _CNX_POOL_MAX_NAME_SIZErg   )r:   	pool_namer2   r2   r3   r     s    
zConnectionPool._set_pool_namec             C   s
   t | jS )zMReturns the number of open connections that can return to this pool.
        )rH   r   )r:   r2   r2   r3   open_connections  s    zConnectionPool.open_connectionsNc             C   s   | j j| dS )zuRemoves a connection to this pool.

        Args:
            cnx (PooledConnection): The connection object.
        N)r   r   )r:   cnxr2   r2   r3   remove_connection  s    z ConnectionPool.remove_connectionc             C   s   | j std| j rtd|st| }|jdj j d d }tdd |jdd jd	D dkr|jdj	| j
j  | jj| nt|tstd| j| 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 availablez'Failed adding connection; queue is fullzshow variables like "version"r   r   c             S   s   g | ]}t |qS r2   )int).0nr2   r2   r3   
<listcomp>5  s    z1ConnectionPool.add_connection.<locals>.<listcomp>-r      
   zset mysqlx_wait_timeout = {}z2Connection instance not subclass of PooledSession.N)r  r   r  )r   r
   fullr   r   executer   tupler   ra   r   r   r+   r   queue_connection)r:   r  verr2   r2   r3   r     s"    
 
zConnectionPool.add_connectionc             C   sV   t |tstd| jr |j  y| 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.
        z2Connection instance not subclass of PooledSession.F)blockz'Failed adding connection; queue is fullN)r   r   r
   r   putr   Full)r:   r  r2   r2   r3   r  A  s    
zConnectionPool.queue_connectionc             C   s   | j j| dS )zNTracks connection in order of close it when client.close() is invoke.
        N)r   r+   )r:   
connectionr2   r2   r3   track_connectionZ  s    zConnectionPool.track_connectionc             C   s   | j S )N)rg   )r:   r2   r2   r3   __str___  s    zConnectionPool.__str__c             C   s   x| j D ]}|j  qW dS )z#Empty this ConnectionPool.
        N)r   r   )r:   r  r2   r2   r3   rP   b  s    zConnectionPool.close)N)N)rw   rx   ry   rz   r;   r   propertyr  r  r   r  r  r  rP   r2   r2   r2   r3   r     s   

'r   c               @   sP   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S )PoolsManagerzManages 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j| t _i t _t jS )N)r  _PoolsManager__instanceobject__new___PoolsManager__pools)clsr2   r2   r3   r  s  s    
zPoolsManager.__new__c             C   s.   | j j|g }x|D ]}|j|krdS qW 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   rg   )r:   r)   r  poolsr   r2   r2   r3   _pool_existsy  s
    


zPoolsManager._pool_existsc             C   sf   g }g }| j |}x|D ]\}}|j| qW x2| jj|jddg D ]}|j|krF|j| qFW |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.
        r)   zNo id)_get_connections_settingsr+   r   r   rg   )r:   r   Zavailable_poolsZ
pool_namesconnections_settingsrouter_namer*   r   r2   r2   r3   
_get_pools  s    	

zPoolsManager._get_poolsc             C   s   |j  }|jdg }g }d|kr*|jd d|krTd|krT|jd|d |d d |jdd dd	 xL|D ]D}|j  }|d |d< |d |d< |d
 |d
< |jtf ||f qlW |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   r%   r&   r   )r   r%   r&   c             S   s   | d S )Nr   r2   )r   r2   r2   r3   r     s    z8PoolsManager._get_connections_settings.<locals>.<lambda>T)r1   r   r   )copyr   popr+   r   r4   )r:   r   Zpool_settingsr   r%  r   Zconnection_settingsr2   r2   r3   r$    s&    

z&PoolsManager._get_connections_settingsc             C   s   | j |}|jdd| jkr.g | j|jdd< xP|D ]H\}}| j|jdd|rTq4q4| jj|jddg }|jt|f| q4W d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.
        r)   zNo idN)r$  r   r   r#  r+   r   )r:   cnx_settingsr%  r&  r   r   r2   r2   r3   create_pool  s    	
zPoolsManager.create_poolc          /   C   s  | j |}t|}xt|D ]}|| }y|j dkrtj 4 y|jd|jd}W n tj	k
r|   t
dY nX y,|js|j  |jdj j d d }W n ttjtfk
r8   z.y|j  W n ttjtfk
r   Y nX W d|j| X t|}|j| |j  |jdj j d d }Y nX tdd	 |jd
d jdD dkrx|jdj|jj  |S Q R X n.|j|jk r
t|}|j| |j  |jdj j d d }tdd	 |jd
d jdD dkr|jdj|jj  |S tj  yt|jd|jd}|j  |jdj j d d }tdd	 |jd
d jdD dkr|jdj|jj  |S  tj	k
r   t
dY nX W dQ R X W q ttfk
r   ||d krނ nwY qX qW 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   T)r  r   z)Failed getting connection; pool exhaustedzshow variables like "version"r   Nc             S   s   g | ]}t |qS r2   )r	  )r
  r  r2   r2   r3   r    s    z/PoolsManager.get_connection.<locals>.<listcomp>r  r   r  r  zset mysqlx_wait_timeout = {}c             S   s   g | ]}t |qS r2   )r	  )r
  r  r2   r2   r3   r    s    c             S   s   g | ]}t |qS r2   )r	  )r
  r  r2   r2   r3   r  )  s    zpool max size has been reached)r  r   r  )r  r   r  )r  r   r  ) r'  rH   rangeqsize	threadingRLockr   r   r   Emptyr
   r   r   r   r  r   rG   r<   rQ   r   r   r  r   r  rA   r  r   ra   r   r  r   r   )r:   r   r"  	num_poolsZpool_numberr   r  r  r2   r2   r3   get_connection  s    


 

 


zPoolsManager.get_connectionc             C   s\   | j |}xH|D ]@}|j  |jdddk	r| jj|jd}||kr|j| qW t|S )zjCloses the connections in the pools

        Returns:
            int: The number of closed pools
        r)   N)r'  rP   r   r   r   rH   )r:   r*  r"  r   Zclient_poolsr2   r2   r3   
close_pool8  s    

zPoolsManager.close_pool)rw   rx   ry   rz   r  r   r  r#  r'  r$  r+  r2  r3  r2   r2   r2   r3   r  i  s   !^r  c               @   s   e Zd Z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 )+SessionaW  Enables interaction with a X Protocol enabled MySQL Product.

    The functionality includes:

    - Accessing available schemas.
    - Schema management operations.
    - Enabling/disabling warning generation.
    - Retrieval of connection information.

    Args:
        settings (dict): Connection data used to connect to the database.
    c             C   s  |j dtj| _|| _d| jks.| jd dkr@i | jd< | j  d|kr|d rt j| t j|| _| jd krt	d|dnt
| j| _| jj  | jj d}|ry| jd	jt|j  W nJ tk
r } z,|jd
kr|jndj|}t||jW Y d d }~X nX d S )Nzuse-purezconnection-attributesFr   poolingz.connection could not be retrieve from pool. %s)valuesr   zUSE {}i  z#Default schema '{}' does not exists)r   r   use_pure	_settings_init_attributesr  r+  r2  _connectionr
   r   rA   r   ra   r   r  r	   r   r   r   )r:   r   r   ro   errmsgr2   r2   r3   r;   W  s,    





zSession.__init__c          
   C   s  t jdkrRdtj d kr d}ndtj d kr6d}ntj }djtj d }n>tj }tj d	kr|d
jdtj d }ndj	t
 dd }tjd}|d dkrd}nd}tt j ||tj ddj	dd tdd D |d}| jd j| d| jkrx| jd D ]}| jd | }t|ts<tdj|t|dkrXtdj||jdrrtdj|t|tstdj||t|d krtd!j|||| jd |< qW d"S )#z5Setup default and user defined connection-attributes.rT   Z64r   x86_64Z32i386z
Windows-{}r   ZDarwinz{}-{}macOSr  r    ZGPLv2zGPL-2.0Z
Commercialzmysql-connector-pythonr   c             S   s   g | ]}t |qS r2   )r,   )r
  r   r2   r2   r3   r    s    z,Session._init_attributes.<locals>.<listcomp>   )Z_pid	_platform_osZ_source_hostZ_client_nameZ_client_versionZ_client_licenser   zconnection-attributesz)Attribute name '{}' must be a string type    z4Attribute name '{}' exceeds 32 characters limit sizer*   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)rf   rg   r   architecturera   	win32_vermachiner   mac_verr.   r    r"   r   r,   getpidr<   gethostnamer!   r8  updater   r   r   rH   
startswith)r:   Zplatform_archZos_verZlicense_chunksZclient_licenseZdefault_attributes	attr_name
attr_valuer2   r2   r3   r9  u  sT    




zSession._init_attributesc             C   s   t jS )zAbool: `True` to use pure Python Protobuf implementation.
        )r   r7  )r:   r2   r2   r3   r7    s    zSession.use_purec             C   s    t |tstdtj| d S )Nz)'use_pure' option should be True or False)r   boolr   r   Zset_use_pure)r:   valuer2   r2   r3   r7    s    
c             C   s   | j jj S )zzReturns `True` if the session is open.

        Returns:
            bool: Returns `True` if the session is open.
        )r:  r   rv   )r:   r2   r2   r3   rv     s    zSession.is_openc             C   s   t | j|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   r:  )r:   r   r2   r2   r3   r     s    
zSession.sqlc             C   s   | j S )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r:  )r:   r2   r2   r3   r2    s    zSession.get_connectionc             C   s    | j dj }dd |j 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   r2   )r
  rowr2   r2   r3   r    s    z'Session.get_schemas.<locals>.<listcomp>)r   r  r   )r:   r   r2   r2   r3   get_schemas  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   )r:   rg   r2   r2   r3   
get_schema  s    	zSession.get_schemac             C   st   | j jjd}|rp| jtjt|j j }y|d d |krJt	| |S W n" t
k
rn   tdj|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   z#Default schema '{}' does not existsN)r:  r   r   r   _SELECT_SCHEMA_NAME_QUERYra   r   r  r   r   r   r   )r:   r   resr2   r2   r3   get_default_schema  s    zSession.get_default_schemac             C   s   | j jdtj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_QUERYra   r   )r:   rg   r2   r2   r3   drop_schema  s    zSession.drop_schemac             C   s$   | j jdtj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_QUERYra   r   r   )r:   rg   r2   r2   r3   create_schema  s    zSession.create_schemac             C   s   | j jddd dS )z+Starts a transaction context on the server.r   zSTART TRANSACTIONTN)r:  r   )r:   r2   r2   r3   start_transaction*  s    zSession.start_transactionc             C   s   | j jddd dS )zXCommits all the operations executed after a call to
        startTransaction().
        r   ZCOMMITTN)r:  r   )r:   r2   r2   r3   commit.  s    zSession.commitc             C   s   | j jddd dS )zYDiscards all the operations executed after a call to
        startTransaction().
        r   ZROLLBACKTN)r:  r   )r:   r2   r2   r3   rollback4  s    zSession.rollbackNc             C   sZ   |dkrdj tj }n$t|t s4t|j dkr<td| jj	ddj 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   zInvalid SAVEPOINT namer   zSAVEPOINT {0}T)ra   uuiduuid1r   r   rH   stripr   r:  r   r   )r:   rg   r2   r2   r3   set_savepoint:  s    zSession.set_savepointc             C   sB   t |t st|j dkr$td| jjddjt|d dS )zRollback to a transaction savepoint with the given name.

        Args:
            name (string): The savepoint name.
        r   zInvalid SAVEPOINT namer   zROLLBACK TO SAVEPOINT {0}TN)	r   r   rH   r_  r   r:  r   ra   r   )r:   rg   r2   r2   r3   rollback_toO  s
    zSession.rollback_toc             C   sB   t |t st|j dkr$td| jjddjt|d dS )z{Release a transaction savepoint with the given name.

        Args:
            name (string): The savepoint name.
        r   zInvalid SAVEPOINT namer   zRELEASE SAVEPOINT {0}TN)	r   r   rH   r_  r   r:  r   ra   r   )r:   rg   r2   r2   r3   release_savepoint[  s
    zSession.release_savepointc             C   s   | j j  t| j| _ dS )zCloses the session.N)r:  r   r   r8  )r:   r2   r2   r3   rP   g  s    
zSession.closec             C   s   | j j  dS )z8Closes all underliying connections as pooled connectionsN)r:  r   )r:   r2   r2   r3   close_connectionsm  s    zSession.close_connections)N)rw   rx   ry   rz   r;   r9  r  r7  setterrv   r   r2  rQ  rR  rU  rW  rY  rZ  r[  r\  r`  ra  rb  rP   rc  r2   r2   r2   r3   r4  I  s*   H	
r4  c               @   sJ   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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j | _| j|jdd | j|jdd | j|jdd | j	|jdd | j
| j d< | j| j d< | j| j d	< d S )
Nr   r   r   r   r   enabledTr5  r)   )r   sessionsr]  uuid4r)   _set_pool_sizer   _set_max_idle_time_set_queue_timeout_set_pool_enabledpooling_enabledr   )r:   Zconnection_dictZoptions_dictr2   r2   r3   r;   |  s    
zClient.__init__c             C   sD   t |ts t |t s |dk r.tdj||dkr:t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)r   rN  r	  rB   ra   _CNX_POOL_MAXSIZEr   )r:   Z	pool_sizer2   r2   r3   ri    s
    
zClient._set_pool_sizec             C   sV   t |ts t |t s |dk r.tdj||| _|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   i  r   Nr   )r   rN  r	  rB   ra   r   _CNX_POOL_MAX_IDLE_TIMEr   )r:   r   r2   r2   r3   rj    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)r   rN  rB   rm  )r:   rf  r2   r2   r3   rl    s    
zClient._set_pool_enabledc             C   sl   t |ts t |t s |dk r.tdj||| _|dkr@tn
t|d | jd< d| jkrh| 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   i  r   zconnect-timeoutNr   )r   rN  r	  rB   ra   r   _CNX_POOL_QUEUE_TIMEOUTr   )r:   r   r2   r2   r3   rk    s    

zClient._set_queue_timeoutc             C   s   t | j}| jj| |S )z~Creates a Session instance using the provided connection data.

        Returns:
            Session: Session object.
        )r4  r   rg  r+   )r:   sessionr2   r2   r3   get_session  s    
zClient.get_sessionc             C   s*   t  j| j x| jD ]}|j  qW dS )z3Closes the sessions opened by this client.
        N)r  r3  r   rg  rc  )r:   rq  r2   r2   r3   rP     s    zClient.close)N)rw   rx   ry   rz   r;   ri  rj  rl  rk  rr  rP   r2   r2   r2   r3   re  r  s   	

re  )Qrz   rX   rV   r   r<   loggingr]  r   rf   rer.  	functoolsr   Zauthenticationr   r   r   errorsr   r   r	   r
   r   r   compatr   r   r   r   Zcrudr   	constantsr   r   helpersr   r   rm   r   r   r   r   r   r   r   r   r   r   r   Zprotobufr   pathr+   Zmysql.connector.utilsr    Zmysql.connector.versionr!   r"   r{   rV  rX  rS  rn  r  compiler  ro  rp  	getLoggerr   r4   r  r5   r   r   r   r  r   r  r4  re  r2   r2   r2   r3   <module>   sn   
 

 9    MI  a  +