3
(h                 @   s  d Z ddlmZmZmZ ddlZddlZddlZddlZdZ	y ddl
Z
ee
drZe
jrZdZ	W n   Y nX ddlmZmZmZ dd	lmZ dd
lmZmZmZmZmZmZmZ ddlmZ ddlmZ ej Z dZ!dZ"dZ#eeG dd de$Z%eeG dd de$Z&dS )z*Module gathering all abstract base classes    )ABCMetaabstractmethodabstractpropertyNFHAS_TLSv1_3T   )make_abc
BYTE_TYPESSTRING_TYPES)MySQLConverterBase)
ClientFlagCharacterSetCONN_ATTRS_DNDEFAULT_CONFIGURATIONOPENSSL_CS_NAMESTLS_CIPHER_SUITESTLS_VERSIONS)MySQLOptionsParser)errorszVThe '{list}' list must not contain repeated values, the value '{value}' is duplicated.zdThe given tls_version: '{}' is not recognized as a valid TLS protocol version (should be one of {}).zINo supported TLS protocol version found in the 'tls-versions' list '{}'. c               @   s"  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
edd Zedd Zedd Zedd Zedd Zejdd Zedd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zed'd( Zd)d* Zd+d, Zed-d. Zejd/d. Zed0d1 Zejd2d1 Zed3d4 Zdd6d7Z dd9d:Z!ed;d< Z"e"jd=d< Z"ed>d? Z#e#jd@d? Z#edAdB Z$e$jdCdB Z$edDdE Z%e%jdFdE Z%edGdH Z&edIdJ Z'ddKdLZ(edMdN Z)edOdP Z*edQdR Z+dSdT Z,edUdV Z-e-Z.dWdX Z/dd[d\Z0ed]d^ Z1edd`daZ2edbdc Z3eddddeZ4edfdg Z5edhdi Z6ddjdkZ7ddldmZ8dndo Z9eddpdqZ:drds Z;ddtduZ<dvdw Z=dxdy Z>dzd{ Z?dd|d}Z@d~d ZAdd ZBdd ZCdd ZDdd ZEdddZFdd ZGf f dZfddZHdd ZIdd ZJdd ZKdd ZLd5S )MySQLConnectionAbstractz7Abstract class for classes connecting to a MySQL serverc             K   s   t j | _d| _d| _d| _d| _d| _d| _i | _	d| _
d| _d| _d| _d| _d| _d| _d| _i | _td | _d| _d	| _d| _d| _td
 | _d| _d| _d| _d| _d| _td | _td | _ d| _!d| _"d| _#d| _$d| _%d| _&d| _'d| _(dS )Z
Initialize-   NF z	127.0.0.1i  r   ssl_disabledTconnect_timeoutallow_local_infileallow_local_infile_in_path))r   get_default_client_flags_charset_id	_sql_mode
_time_zone_autocommit_server_version
_handshake_conn_attrs_user	_password	_database_host_port_unix_socketZ_client_hostZ_client_port_sslr   _ssl_disabledZ_force_ipv6_use_unicode_get_warnings_raise_on_warningsZ_connection_timeoutZ	_buffered_unread_resultZ_have_next_result_rawZ_in_transaction_allow_local_infile_allow_local_infile_in_pathZ_prepared_statementsZ_ssl_active_auth_pluginZ_pool_config_version	converter_converter_class	_compress_consume_results)selfkwargs r:   M/tmp/pip-install-q3hcpn_q/mysql-connector-python/mysql/connector/abstracts.py__init__G   sL    




z MySQLConnectionAbstract.__init__c             C   s   | S )Nr:   )r8   r:   r:   r;   	__enter__v   s    z!MySQLConnectionAbstract.__enter__c             C   s   | j   d S )N)close)r8   exc_type	exc_value	tracebackr:   r:   r;   __exit__y   s    z MySQLConnectionAbstract.__exit__c             C   s   | S )zReturn self for weakref.proxy

        This method is used when the original object is needed when using
        weakref.proxy.
        r:   )r8   r:   r:   r;   	_get_self|   s    z!MySQLConnectionAbstract._get_selfc       	      C   s  d|kry.t |d tr(|d g|d< |d }|d= W n tk
rT   ddg}Y nX t |d trr|d g|d< tt|d dd}|d= |j| }i }x|D ]}yx|| j D ]t\}}y<|dkrd}t|  ||ks|| d	 |d	 kr|||< W q tk
r&   |dkr"td
j	|Y qX qW W q tk
rF   wY qX qW x\|j D ]P\}}||krVyt
|d ||< W n& ttfk
r   |d ||< Y nX qVW |S )z
        Read option files for connection parameters.

        Checks if connection arguments contain option file arguments, and then
        reads option files accordingly.
        option_filesoption_groupsclientZconnector_pythonF)Zkeep_dashessocketunix_socketr   zUnsupported argument '{0}'r   )
isinstancestrKeyErrorr   listZ get_groups_as_dict_with_priorityitemsr   AttributeErrorformateval	NameErrorSyntaxError)	r8   configgroupsZoption_parserZconfig_from_fileZconfig_optionsgroupoptionvaluer:   r:   r;   _read_option_files   sN    




z*MySQLConnectionAbstract._read_option_filesc             C   sv  g }| j d }t|tr|jdo*|jds<tdj|q|dd jd}|sZtdxx|D ]}|j j	 }|r`|j
| q`W nPt|trdd	 |D }n6t|trx*|D ]}|r|j
| qW ntd
j|| j jdddkrtdd n| j d dd }|jdd |d }g g g}i }g }	x<tdtj|d  D ]"}
|jt|
  |	jt|
  q@W x|D ]}d|kr||	kr|td kr|d j
| n|d j
| nt||kr|| }||krttjd|dn4|td kr|d j
||  n|d j
||  ntdj|qlW |d  rL|d  rLtddj|d dj|d g}|| j d< dS )z/Validates the tls_ciphersuites option.
        tls_ciphersuites[]z,tls_ciphersuites must be a list, found: '{}'r   ,z7No valid cipher suite found in 'tls_ciphersuites' list.c             S   s   g | ]}|r|qS r:   r:   ).0tls_csr:   r:   r;   
<listcomp>   s    zFMySQLConnectionAbstract._validate_tls_ciphersuites.<locals>.<listcomp>zLtls_ciphersuites should be a list with one or more ciphersuites. Found: '{}'tls_versionsNT)reverser   -zTLSv1.3)rL   rW   z>The value '{}' in tls_ciphersuites is not a valid cipher suitez;No valid cipher suite found in the 'tls_ciphersuites' list.:)r*   rI   r	   
startswithendswithrN   rO   splitstripupperappendrL   setgetr   sortindexupdater   extendr   DUPLICATED_IN_LIST_ERRORjoin)r8   rY   r^   Ztls_cssZ_tls_csr`   Znewer_tls_verZtranslated_namesZiani_cipher_suites_namesZossl_cipher_suites_namestls_vernameZtranslated_namer:   r:   r;   _validate_tls_ciphersuites   sr    








$


z2MySQLConnectionAbstract._validate_tls_ciphersuitesc             C   s  g }| j d }t|tr|jdo*|jds<tdj|n|dd jd}x^|D ]V}|j }|dkrlqTn4|t	krtt
j|t	n||krttjd|d|j| qTW |d	gkrt rttj|t	nt|tr<|std
x|D ]H}|t	krtt
j|t	q||kr,ttjd|dq|j| qW nXt|tr~xJ|D ]*}|t	krltt
j|t	|j| qNW ntdjdjt	||std|d	gkrt rttj|t	|j  || j d< dS )z+Validates the tls_versions option.
        r`   rZ   r[   z(tls_versions must be a list, found: '{}'r   r\   r   )rL   rW   zTLSv1.3zKAt least one TLS protocol version must be specified in 'tls_versions' list.zMtls_versions should be a list with one or more of versions in {}. found: '{}'z, zeAt least one TLS protocol version must be specified in 'tls_versions' list when this option is given.Nrd   )r*   rI   r	   re   rf   rN   rO   rg   rh   r   TLS_VERSION_ERRORrq   rj   TLS_V1_3_SUPPORTEDTLS_VER_NO_SUPPORTEDrL   rk   rr   rm   )r8   r`   Ztls_versionZtls_versrs   r:   r:   r;   _validate_tls_versions  sh    








z.MySQLConnectionAbstract._validate_tls_versionsc             C   s   | j S )z#User used while connecting to MySQL)r$   )r8   r:   r:   r;   userJ  s    zMySQLConnectionAbstract.userc             C   s   | j S )zMySQL server IP address or name)r'   )r8   r:   r:   r;   server_hostO  s    z#MySQLConnectionAbstract.server_hostc             C   s   | j S )zMySQL server TCP/IP port)r(   )r8   r:   r:   r;   server_portT  s    z#MySQLConnectionAbstract.server_portc             C   s   | j S )zMySQL Unix socket file location)r)   )r8   r:   r:   r;   rH   Y  s    z#MySQLConnectionAbstract.unix_socketc             C   s   dS )zGet the current databaseNr:   )r8   r:   r:   r;   database^  s    z MySQLConnectionAbstract.databasec             C   s   | j d|  dS )zSet the current databasezUSE %sN)	cmd_query)r8   rW   r:   r:   r;   r}   c  s    c             C   s   | j S )z"Returns whether to consume results)r7   )r8   r:   r:   r;   can_consume_resultsh  s    z+MySQLConnectionAbstract.can_consume_resultsc          t   K   sb  |j  }d|krtjd| j| y|d | _|d= W n tk
rL   Y nX y|d | _|d= W n tk
rv   Y nX y$tj }| j	|d p| |d= W n tk
r   Y nX y |d rd| _
| j	tjg W n tk
r   Y nX |jdtd | _|jd	td	 | _d
}| jr`tjj| j}|rJtjj|rJtjj| sXtjj|r`td| jsp| jr| j	tjg n| j	tj g y|d sd| _nd| _W n tk
r   d| _Y nX y|d | _|d= W n tk
r   d| _Y nX d|ksd|kr~y|d }|d= W n tk
r<   d
}Y nX y|d }|d= W n tk
rj   d
}Y nX tj||d | _y| j|d  W n2 tk
r   Y n tk
r   tdY nX d>d?d@dAdBg}xJ|D ]B\}}	y |	|kr|| ||	< ||= W n tk
r   Y nX qW d|ks2d|kry|d }
|d= W n tk
r`   | j}
Y nX y|d }|d= W n tk
r   | j }Y nX | j!|
| d|kr|d r|d | _"yt#|d  | _$|d = W n4 tk
r   Y n  t%k
r   tj&d!Y nX d"|kr |j'd"| _(| j(r>| jd#kr>tj&d$d}x|j) D ]\}}yt|  W n$ tk
r   td%j*|Y nX |j+d&rd}| j,j-|j.d&d|i nb|j+d'rd}| j,j-||i n@d(| }yt/| ||j0  W n" tk
r   t/| || Y nX qLW |rXd)| j,kr8td* | j,d)< d+| j,krRtd, | j,d+< d-| j,ksn| j,d- d
krxd| j,d-< t1d.| j,kt1d/| j,kkrtd0nPt2dCt2| j,ksd
| j,d.< d
| j,d/< n&| j,d. d
k| j,d/ d
kkrtd1d2| j,kr$| j,d2 d
k	r$| j(rtd3| j3  d4| j,krX| j,d4 d
k	rX| j(rPtd5| j4  | j5d
krli | _5nt6| j5t7stj&d6nx| j5D ]}|t8krqt6|t9stj&d7j*|| j5t:|d8krtj&d9j*||j+d(rtj&d:j*|| j5| }t6|t9s"tj&d;j*||t:|d<krtj&d=j*||qW | j;tj<@ r^| j=  d
S )DzConfigure the MySQL Connection

        This method allows you to configure the MySQLConnection instance.

        Raises on errors.
        Zdsnz!Data source name is not supportedget_warningsraise_on_warningsZclient_flagscompressTr   r   Nz.allow_local_infile_in_path must be a directoryZconsume_resultsFZauth_pluginr   charset	collationr   Zconverter_classzFConverter class should be a subclass of conversion.MySQLConverterBase.dbr}   usernamerz   passwdpasswordr   connection_timeoutread_default_filerD   hostportz'TCP/IP port number should be an integerr   Zmysql_clear_passwordzEClear password authentication is not supported over insecure channelszUnsupported argument '{0}'ssl_Ztls__Zverify_certZssl_verify_certZverify_identityZssl_verify_identitycakeycertz;ssl_key and ssl_cert need to be both specified, or neither.z5ssl_key and ssl_cert need to be both set, or neither.r`   z@The tls_versions option can not be used along with ssl_disabled.rY   zDThe tls_ciphersuites option can not be used along with ssl_disabled.z conn_attrs must be of type dict.z6Attribute name should be a string, found: '{}' in '{}'    z5Attribute name '{}' exceeds 32 characters limit size.zEKey names in connection attributes cannot start with '_', found: '{}'z1Attribute '{}' value: '{}' must be a string type.i   z=Attribute '{}' value: '{}' exceeds 1024 characters limit size)r   r}   )r   rz   )r   r   )r   r   )r   rD   )r   r   )>copyr   NotSupportedErrorrX   r   rK   r   r   r   set_client_flagsr6   ZCOMPRESSrl   r   r1   r2   ospathabspathexistsisdirislinkrN   ZLOCAL_FILESr7   r3   r   get_charset_infor   set_converter_class	TypeErrorr$   r%   	set_loginr'   intr(   
ValueErrorInterfaceErrorpopr+   rM   rO   re   r*   ro   replacesetattrrh   boolrk   ry   ru   r#   rI   dictr   r	   lenr   ZCONNECT_ARGS_add_default_conn_attrs)r8   r9   rS   defaultZinfile_in_pathr   r   Z
compat_mapcompat	translaterz   r   Zset_ssl_flagr   rW   	attribute	attr_name
attr_valuer:   r:   r;   rS   m  sj   



























zMySQLConnectionAbstract.configc             C   s   dS )z&Add the default connection attributes.Nr:   )r8   r:   r:   r;   r   c  s    z/MySQLConnectionAbstract._add_default_conn_attrsc             C   sn   t |tr|j }tjd}|j|}|s4tjdtdd |j	 dd D }|d
k rjtjd	j
||S )a7  Check the MySQL version

        This method will check the MySQL version and raise an InterfaceError
        when it is not supported or invalid. It will return the version
        as a tuple with major, minor and patch.

        Raises InterfaceError if invalid server version.

        Returns tuple
        z$^(\d{1,2})\.(\d{1,2})\.(\d{1,3})(.*)zFailed parsing MySQL versionc             S   s   g | ]}t |qS r:   )r   )r]   vr:   r:   r;   r_   |  s    zAMySQLConnectionAbstract._check_server_version.<locals>.<listcomp>r         r   z%MySQL Version '{0}' is not supported.)r   r   )rI   r   decoderecompilematchr   r   tuplerT   rO   )r8   Zserver_versionZ	regex_verr   versionr:   r:   r;   _check_server_versiong  s    



z-MySQLConnectionAbstract._check_server_versionc             C   s   | j S )zGet the MySQL version

        This method returns the MySQL server version as a tuple. If not
        previously connected, it will return None.

        Returns a tuple or None.
        )r!   )r8   r:   r:   r;   get_server_version  s    z*MySQLConnectionAbstract.get_server_versionc             C   s(   y
| j d S  ttfk
r"   dS X dS )zGet the original MySQL version information

        This method returns the original MySQL server as text. If not
        previously connected, it will return None.

        Returns a string or None.
        Zserver_version_originalN)r"   r   rK   )r8   r:   r:   r;   get_server_info  s    
z'MySQLConnectionAbstract.get_server_infoc             C   s   dS )z'MySQL session has started a transactionNr:   )r8   r:   r:   r;   in_transaction  s    z&MySQLConnectionAbstract.in_transactionc             C   st   t |tr|dkr|| _nTt |ttfrdxD|D ]0}|dk rP|  jt| M  _q.|  j|O  _q.W n
tjd| jS )a   Set the client flags

        The flags-argument can be either an int or a list (or tuple) of
        ClientFlag-values. If it is an integer, it will set client_flags
        to flags as is.
        If flags is a list (or tuple), each flag will be set or unset
        when it's negative.

        set_client_flags([ClientFlag.FOUND_ROWS,-ClientFlag.LONG_FLAG])

        Raises ProgrammingError when the flags argument is not a set or
        an integer bigger than 0.

        Returns self.client_flags
        r   z+set_client_flags expect integer (>0) or set)rI   r   r   r   rL   absr   ProgrammingError)r8   flagsflagr:   r:   r;   r     s    
z(MySQLConnectionAbstract.set_client_flagsc             C   s   | j |@ dkrdS dS )zCheck if a client flag is setr   TF)r   )r8   r   r:   r:   r;   isset_client_flag  s    z)MySQLConnectionAbstract.isset_client_flagc             C   s   | j dd S )zGet the current time zonezSELECT @@session.time_zoner   )
info_query)r8   r:   r:   r;   	time_zone  s    z!MySQLConnectionAbstract.time_zonec             C   s   | j dj| || _dS )zSet the time zonezSET @@session.time_zone = '{0}'N)r~   rO   r   )r8   rW   r:   r:   r;   r     s    c             C   s   | j dd S )zGet the SQL modezSELECT @@session.sql_moder   )r   )r8   r:   r:   r;   sql_mode  s    z MySQLConnectionAbstract.sql_modec             C   s2   t |ttfrdj|}| jdj| || _dS )a  Set the SQL mode

        This method sets the SQL Mode for the current connection. The value
        argument can be either a string with comma separate mode names, or
        a sequence of mode names.

        It is good practice to use the constants class SQLMode:
          from mysql.connector.constants import SQLMode
          cnx.sql_mode = [SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
        r\   zSET @@session.sql_mode = '{0}'N)rI   rL   r   rr   r~   rO   r   )r8   rW   r:   r:   r;   r     s    
c             C   s   dS )z%Send a query which only returns 1 rowNr:   )r8   queryr:   r:   r;   r     s    z"MySQLConnectionAbstract.info_queryNc             C   s4   |dk	r|j  | _nd| _|dk	r*|| _nd| _dS )zSet login information for MySQL

        Set the username and/or password for the user connecting to
        the MySQL Server.
        Nr   )rh   r$   r%   )r8   r   r   r:   r:   r;   r     s    z!MySQLConnectionAbstract.set_loginTc             C   s   || _ | jr| jj| dS )zuToggle unicode mode

        Set whether we return string fields as unicode or not.
        Default is True.
        N)r,   r4   set_unicode)r8   rW   r:   r:   r;   r     s    z#MySQLConnectionAbstract.set_unicodec             C   s   | j dd }|dkrdS dS )z#Get whether autocommit is on or offzSELECT @@session.autocommitr   r   TF)r   )r8   rW   r:   r:   r;   
autocommit  s    z"MySQLConnectionAbstract.autocommitc             C   s&   |rdnd}| j dj| || _dS )zToggle autocommitONZOFFzSET @@session.autocommit = {0}N)r~   rO   r    )r8   rW   switchr:   r:   r;   r     s    c             C   s   | j S )zGet whether this connection retrieves warnings automatically

        This method returns whether this connection retrieves warnings
        automatically.

        Returns True, or False when warnings are not retrieved.
        )r-   )r8   r:   r:   r;   r     s    	z$MySQLConnectionAbstract.get_warningsc             C   s   t |tstd|| _dS )zSet whether warnings should be automatically retrieved

        The toggle-argument must be a boolean. When True, cursors for this
        connection will retrieve information about warnings (if any).

        Raises ValueError on error.
        zExpected a boolean typeN)rI   r   r   r-   )r8   rW   r:   r:   r;   r     s    	
c             C   s   | j S )zGet whether this connection raises an error on warnings

        This method returns whether this connection will raise errors when
        MySQL reports warnings.

        Returns True or False.
        )r.   )r8   r:   r:   r;   r   &  s    	z)MySQLConnectionAbstract.raise_on_warningsc             C   s"   t |tstd|| _|| _dS )a  Set whether warnings raise an error

        The toggle-argument must be a boolean. When True, cursors for this
        connection will raise an error when MySQL reports warnings.

        Raising on warnings implies retrieving warnings automatically. In
        other words: warnings will be set to True. If set to False, warnings
        will be also set to False.

        Raises ValueError on error.
        zExpected a boolean typeN)rI   r   r   r.   r-   )r8   rW   r:   r:   r;   r   1  s    
c             C   s   | j S )zGet whether there is an unread result

        This method is used by cursors to check whether another cursor still
        needs to retrieve its result set.

        Returns True, or False when there is no unread result.
        )r/   )r8   r:   r:   r;   unread_resultD  s    	z%MySQLConnectionAbstract.unread_resultc             C   s   t |tstd|| _dS )zSet whether there is an unread result

        This method is used by cursors to let other cursors know there is
        still a result set that needs to be retrieved.

        Raises ValueError on errors.
        zExpected a boolean typeN)rI   r   r   r/   )r8   rW   r:   r:   r;   r   O  s    	
c             C   s   t j| jd S )a+  Returns the character set for current connection

        This property returns the character set name of the current connection.
        The server is queried when the connection is active. If not connected,
        the configured character set name is returned.

        Returns a string.
        r   )r   get_infor   )r8   r:   r:   r;   r   \  s    
zMySQLConnectionAbstract.charsetc             C   s    t j| jd }|dkrdS |S )ay  Returns the Python character set for current connection

        This property returns the character set name of the current connection.
        Note that, unlike property charset, this checks if the previously set
        character set is supported by Python and if not, it returns the
        equivalent character set that Python supports.

        Returns a string.
        r   utf8mb4binaryutf8)r   r   )r   r   r   )r8   encodingr:   r:   r;   python_charseth  s    z&MySQLConnectionAbstract.python_charsetc             C   s   |rLt |tr"tj|\| _}}qdt |trBtj||\| _}}qdtdn|rdtj|d\| _}}| jdj|| y| j	| W n t
k
r   Y nX | jr| jj| dS )aV  Sets the character set and collation for the current connection

        This method sets the character set and collation to be used for
        the current connection. The charset argument can be either the
        name of a character set as a string, or the numerical equivalent
        as defined in constants.CharacterSet.

        When the collation is not given, the default will be looked up and
        used.

        For example, the following will set the collation for the latin1
        character set to latin1_general_ci:

           set_charset('latin1','latin1_general_ci')

        z0charset should be either integer, string or None)r   zSET NAMES '{0}' COLLATE '{1}'N)rI   r   r   r   r   rJ   r   _execute_queryrO   Zset_character_set_namerN   r4   set_charset)r8   r   r   charset_nameZcollation_namer:   r:   r;   set_charset_collationx  s"    


z-MySQLConnectionAbstract.set_charset_collationc             C   s   t j| jd S )a  Returns the collation for current connection

        This property returns the collation name of the current connection.
        The server is queried when the connection is active. If not connected,
        the configured collation name is returned.

        Returns a string.
           )r   r   r   )r8   r:   r:   r;   r     s    
z!MySQLConnectionAbstract.collationc             C   s   dS )z<Gather information of the MySQL server before authenticationNr:   )r8   r:   r:   r;   _do_handshake  s    z%MySQLConnectionAbstract._do_handshakec             C   s   dS )z'Open the connection to the MySQL serverNr:   )r8   r:   r:   r;   _open_connection  s    z(MySQLConnectionAbstract._open_connectionc             C   s4   | j | j | j| _| jr"| j| _| jr0| j| _dS )zExecutes commands after connection has been established

        This method executes commands after the connection has been
        established. Some setting like autocommit, character set, and SQL mode
        are set using this method.
        N)r   r   r    r   r   r   r   r   )r8   r:   r:   r;   _post_connection  s    z(MySQLConnectionAbstract._post_connectionc             C   s   dS )z Disconnect from the MySQL serverNr:   )r8   r:   r:   r;   
disconnect  s    z"MySQLConnectionAbstract.disconnectc             K   s8   |r| j f | | j  | j  | jtj@ s4| j  dS )zConnect to the MySQL server

        This method sets up the connection to the MySQL server. If no
        arguments are given, it will use the already configured or default
        values.
        N)rS   r   r   r   r   ZCAN_HANDLE_EXPIRED_PASSWORDSr   )r8   r9   r:   r:   r;   connect  s    zMySQLConnectionAbstract.connectr   r   c             C   s   d}x||kr|d }y| j   | j  | j r2P W nD tk
rx } z(||krhdj|t|}tj|W Y dd}~X nX |dkrtj	| qW dS )a  Attempt to reconnect to the MySQL server

        The argument attempts should be the number of times a reconnect
        is tried. The delay argument is the number of seconds to wait between
        each retry.

        You may want to set the number of attempts higher and use delay when
        you expect the MySQL server to be down for maintenance or when you
        expect the network to be temporary unavailable.

        Raises InterfaceError on errors.
        r   r   z4Can not reconnect to MySQL after {0} attempt(s): {1}N)
r   r   is_connected	ExceptionrO   rJ   r   r   timesleep)r8   attemptsdelaycountererrmsgr:   r:   r;   	reconnect  s    
z!MySQLConnectionAbstract.reconnectc             C   s   dS )z;Reports whether the connection to MySQL Server is availableNr:   )r8   r:   r:   r;   r     s    z$MySQLConnectionAbstract.is_connectedFc             C   s   dS )z&Check availability of the MySQL serverNr:   )r8   r   r   r   r:   r:   r;   ping  s    zMySQLConnectionAbstract.pingc             C   s   dS )zCommit current transactionNr:   )r8   r:   r:   r;   commit  s    zMySQLConnectionAbstract.commitc             C   s   dS )z!Instantiates and returns a cursorNr:   )r8   bufferedrawpreparedZcursor_class
dictionaryZnamed_tupler:   r:   r;   cursor  s    zMySQLConnectionAbstract.cursorc             C   s   dS )zExecute a queryNr:   )r8   r   r:   r:   r;   r     s    z&MySQLConnectionAbstract._execute_queryc             C   s   dS )zRollback current transactionNr:   )r8   r:   r:   r;   rollback  s    z MySQLConnectionAbstract.rollbackc             C   s   | j rtjd|rZ|j jddj }ddddg}||krJtdj|| jd	j| |d
k	r| j	dk r|tdj| j	|rd}nd}| jdj| d}|r|d7 }| j
| d
S )a  Start a transaction

        This method explicitly starts a transaction sending the
        START TRANSACTION statement to the MySQL server. You can optionally
        set whether there should be a consistent snapshot, which
        isolation level you need or which access mode i.e. READ ONLY or
        READ WRITE.

        For example, to start a transaction with isolation level SERIALIZABLE,
        you would do the following:
            >>> cnx = mysql.connector.connect(..)
            >>> cnx.start_transaction(isolation_level='SERIALIZABLE')

        Raises ProgrammingError when a transaction is already in progress
        and when ValueError when isolation_level specifies an Unknown
        level.
        zTransaction already in progressrb    zREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READZSERIALIZABLEzUnknown isolation level "{0}"z#SET TRANSACTION ISOLATION LEVEL {0}N      z6MySQL server version {0} does not support this featurez	READ ONLYz
READ WRITEzSET TRANSACTION {0}zSTART TRANSACTIONz WITH CONSISTENT SNAPSHOT)r   r   r   )r   r   r   rh   r   ri   r   rO   r   r!   r~   )r8   Zconsistent_snapshotZisolation_levelreadonlylevelZlevelsZaccess_moder   r:   r:   r;   start_transaction  s2    


z)MySQLConnectionAbstract.start_transactionc             C   s   | j  stjdy| j  W nD tjtfk
rb   | jrFtjdn| j| j| j	| j
| j Y nX |sl|r| j }|rx(|j D ]\}}|jdj||f qW |rx(|j D ]\}}|jdj||f qW |j  dS )a  Clears the current active session

        This method resets the session state, if the MySQL server is 5.7.3
        or later active session will be reset without re-authenticating.
        For other server versions session will be reset by re-authenticating.

        It is possible to provide a sequence of variables and their values to
        be set after clearing the session. This is possible for both user
        defined variables and session variables.
        This method takes two arguments user_variables and session_variables
        which are dictionaries.

        Raises OperationalError if not connected, InternalError if there are
        unread results and InterfaceError on errors.
        zMySQL Connection not available.zZReset session is not supported with compression for MySQL server version 5.7.2 or earlier.zSET @`{0}` = %szSET SESSION `{0}` = %sN)r   r   ZOperationalErrorcmd_reset_connectionr   NotImplementedErrorr6   cmd_change_userr$   r%   r&   r   r   rM   executerO   r>   )r8   Zuser_variablesZsession_variablescurr   rW   r:   r:   r;   reset_sessionO  s&    
z%MySQLConnectionAbstract.reset_sessionc             C   s@   |r4t |tr4tj| jd }|| _||| j| _ntddS )z
        Set the converter class to be used. This should be a class overloading
        methods and members of conversion.MySQLConverter.
        r   zFConverter class should be a subclass of conversion.MySQLConverterBase.N)	
issubclassr
   r   r   r   r5   r,   r4   r   )r8   Z	convclassr   r:   r:   r;   r   w  s
    z+MySQLConnectionAbstract.set_converter_classc             C   s   dS )z)Get all rows returned by the MySQL serverNr:   )r8   countr   columnsr   Z	prep_stmtr:   r:   r;   get_rows  s    z MySQLConnectionAbstract.get_rowsc             C   s   t dS )zChange the current databaseN)r   )r8   r}   r:   r:   r;   cmd_init_db  s    z#MySQLConnectionAbstract.cmd_init_dbc             C   s   t dS )z Send a query to the MySQL serverN)r   )r8   r   r   r   Zraw_as_stringr:   r:   r;   r~     s    z!MySQLConnectionAbstract.cmd_queryc             C   s   t dS )z/Send one or more statements to the MySQL serverN)r   )r8   Z
statementsr:   r:   r;   cmd_query_iter  s    z&MySQLConnectionAbstract.cmd_query_iterc             C   s   t dS )z,Send the Refresh command to the MySQL serverN)r   )r8   optionsr:   r:   r;   cmd_refresh  s    z#MySQLConnectionAbstract.cmd_refreshc             C   s   t dS )z,Close the current connection with the serverN)r   )r8   r:   r:   r;   cmd_quit  s    z MySQLConnectionAbstract.cmd_quitc             C   s   t dS )zShut down the MySQL ServerN)r   )r8   Zshutdown_typer:   r:   r;   cmd_shutdown  s    z$MySQLConnectionAbstract.cmd_shutdownc             C   s   t dS )z/Send the statistics command to the MySQL ServerN)r   )r8   r:   r:   r;   cmd_statistics  s    z&MySQLConnectionAbstract.cmd_statisticsc             C   s   t jddS )ak  Get the process list of the MySQL Server

        This method is a placeholder to notify that the PROCESS_INFO command
        is not supported by raising the NotSupportedError. The command
        "SHOW PROCESSLIST" should be send using the cmd_query()-method or
        using the INFORMATION_SCHEMA database.

        Raises NotSupportedError exception
        z;Not implemented. Use SHOW PROCESSLIST or INFORMATION_SCHEMAN)r   r   )r8   r:   r:   r;   cmd_process_info  s    
z(MySQLConnectionAbstract.cmd_process_infoc             C   s   t dS )zKill a MySQL processN)r   )r8   Z	mysql_pidr:   r:   r;   cmd_process_kill  s    z(MySQLConnectionAbstract.cmd_process_killc             C   s   t dS )zSend the DEBUG commandN)r   )r8   r:   r:   r;   	cmd_debug  s    z!MySQLConnectionAbstract.cmd_debugc             C   s   t dS )zSend the PING commandN)r   )r8   r:   r:   r;   cmd_ping  s    z MySQLConnectionAbstract.cmd_pingr   r   c             C   s   t dS )z!Change the current logged in userN)r   )r8   r   r   r}   r   r:   r:   r;   r     s    z'MySQLConnectionAbstract.cmd_change_userc             C   s   t dS )zPrepare a MySQL statementN)r   )r8   Z	statementr:   r:   r;   cmd_stmt_prepare  s    z(MySQLConnectionAbstract.cmd_stmt_preparec             C   s   t dS )z"Execute a prepared MySQL statementN)r   )r8   statement_iddata
parametersr   r:   r:   r;   cmd_stmt_execute  s    z(MySQLConnectionAbstract.cmd_stmt_executec             C   s   t dS )z%Deallocate a prepared MySQL statementN)r   )r8   r	  r:   r:   r;   cmd_stmt_close  s    z&MySQLConnectionAbstract.cmd_stmt_closec             C   s   t dS )zSend data for a columnN)r   )r8   r	  Zparam_idr
  r:   r:   r;   cmd_stmt_send_long_data  s    z/MySQLConnectionAbstract.cmd_stmt_send_long_datac             C   s   t dS )z3Reset data for prepared statement sent as long dataN)r   )r8   r	  r:   r:   r;   cmd_stmt_reset  s    z&MySQLConnectionAbstract.cmd_stmt_resetc             C   s   t dS )z2Resets the session state without re-authenticatingN)r   )r8   r:   r:   r;   r     s    z,MySQLConnectionAbstract.cmd_reset_connection)NN)T)NN)r   r   )Fr   r   )NNNNNN)FNN)NN)NFNNN)FFF)N)r   r   r   r   )M__name__
__module____qualname____doc__r<   r=   rB   rC   rX   ru   ry   propertyrz   r{   r|   rH   r   r}   setterr   rS   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r>   r   r   r   r   r   r   r   r   r   r   r   r   r   r~   r   r   r  r  r  r  r  r  r  r   r  r  r  r  r  r   r:   r:   r:   r;   r   B   s   /5R? w




,
  
3
( 

 
r   c               @   s   e Zd ZdZdd Zdd Zdd Zef fdd	Zed
d Z	ef dfddZ
edd Zedd Zed*ddZedd Zdd Zdd Zd+ddZd,d d!Zed"d# Zed$d% Zed&d' Zd(d) ZdS )-MySQLCursorAbstractzAbstract cursor class

    Abstract class defining cursor class with method and members
    required by the Python Database API Specification v2.0.
    c             C   s"   d| _ d| _d| _d| _d| _dS )ZInitializationNr   rd   )_description	_rowcount_last_insert_id	_warningsZ	arraysize)r8   r:   r:   r;   r<     s
    zMySQLCursorAbstract.__init__c             C   s   | S )Nr:   )r8   r:   r:   r;   r=     s    zMySQLCursorAbstract.__enter__c             C   s   | j   d S )N)r>   )r8   r?   r@   rA   r:   r:   r;   rB     s    zMySQLCursorAbstract.__exit__c             C   s   dS )a  Calls a stored procedure with the given arguments

        The arguments will be set during this session, meaning
        they will be called like  _<procname>__arg<nr> where
        <nr> is an enumeration (+1) of the arguments.

        Coding Example:
          1) Defining the Stored Routine in MySQL:
          CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
          BEGIN
            SET pProd := pFac1 * pFac2;
          END

          2) Executing in Python:
          args = (5,5,0) # 0 is to hold pprod
          cursor.callproc('multiply', args)
          print(cursor.fetchone())

        Does not return a value, but a result set will be
        available when the CALL-statement execute successfully.
        Raises exceptions when something is wrong.
        Nr:   )r8   Zprocnameargsr:   r:   r;   callproc  s    zMySQLCursorAbstract.callprocc             C   s   dS )zClose the cursor.Nr:   )r8   r:   r:   r;   r>     s    zMySQLCursorAbstract.closeFc             C   s   dS )a  Executes the given operation

        Executes the given operation substituting any markers with
        the given parameters.

        For example, getting all rows where id is 5:
          cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))

        The multi argument should be set to True when executing multiple
        statements in one operation. If not set and multiple results are
        found, an InterfaceError will be raised.

        If warnings where generated, and connection.get_warnings is True, then
        self._warnings will be a list containing these warnings.

        Returns an iterator when multi is True, otherwise None.
        Nr:   )r8   	operationparamsZmultir:   r:   r;   r     s    zMySQLCursorAbstract.executec             C   s   dS )a  Execute the given operation multiple times

        The executemany() method will execute the operation iterating
        over the list of parameters in seq_params.

        Example: Inserting 3 new employees and their phone number

        data = [
            ('Jane','555-001'),
            ('Joe', '555-001'),
            ('John', '555-003')
            ]
        stmt = "INSERT INTO employees (name, phone) VALUES ('%s','%s')"
        cursor.executemany(stmt, data)

        INSERT statements are optimized by batching the data, that is
        using the MySQL multiple rows syntax.

        Results are discarded. If they are needed, consider looping over
        data using the execute() method.
        Nr:   )r8   r  Z
seq_paramsr:   r:   r;   executemany&  s    zMySQLCursorAbstract.executemanyc             C   s   dS )zQReturns next row of a query result set

        Returns a tuple or None.
        Nr:   )r8   r:   r:   r;   fetchone?  s    zMySQLCursorAbstract.fetchoner   c             C   s   dS )a  Returns the next set of rows of a query result, returning a
        list of tuples. When no more rows are available, it returns an
        empty list.

        The number of rows returned can be specified using the size argument,
        which defaults to one
        Nr:   )r8   sizer:   r:   r;   	fetchmanyG  s    	zMySQLCursorAbstract.fetchmanyc             C   s   dS )zRReturns all rows of a query result set

        Returns a list of tuples.
        Nr:   )r8   r:   r:   r;   fetchallR  s    zMySQLCursorAbstract.fetchallc             C   s   dS )zNot Implemented.Nr:   )r8   r:   r:   r;   nextsetZ  s    zMySQLCursorAbstract.nextsetc             C   s   dS )zNot Implemented.Nr:   )r8   sizesr:   r:   r;   setinputsizes^  s    z!MySQLCursorAbstract.setinputsizesNc             C   s   dS )zNot Implemented.Nr:   )r8   r!  columnr:   r:   r;   setoutputsizeb  s    z!MySQLCursorAbstract.setoutputsizeTc             C   s   dS )zReset the cursor to defaultNr:   )r8   freer:   r:   r;   resetf  s    zMySQLCursorAbstract.resetc             C   s   | j S )a  Returns description of columns in a result

        This property returns a list of tuples describing the columns in
        in a result set. A tuple is described as follows::

                (column_name,
                 type,
                 None,
                 None,
                 None,
                 None,
                 null_ok,
                 column_flags)  # Addition to PEP-249 specs

        Returns a list of tuples.
        )r  )r8   r:   r:   r;   descriptionj  s    zMySQLCursorAbstract.descriptionc             C   s   | j S )a   Returns the number of rows produced or affected

        This property returns the number of rows produced by queries
        such as a SELECT, or affected rows when executing DML statements
        like INSERT or UPDATE.

        Note that for non-buffered cursors it is impossible to know the
        number of rows produced before having fetched them all. For those,
        the number of rows will be -1 right after execution, and
        incremented when fetching rows.

        Returns an integer.
        )r  )r8   r:   r:   r;   rowcount~  s    zMySQLCursorAbstract.rowcountc             C   s   | j S )a  Returns the value generated for an AUTO_INCREMENT column

        Returns the value generated for an AUTO_INCREMENT column by
        the previous INSERT or UPDATE statement or None when there is
        no such value available.

        Returns a long value or None.
        )r  )r8   r:   r:   r;   	lastrowid  s    
zMySQLCursorAbstract.lastrowidc             C   s   | j S )zReturns Warnings.)r  )r8   r:   r:   r;   fetchwarnings  s    z!MySQLCursorAbstract.fetchwarnings)r   )N)T)r  r  r  r  r<   r=   rB   r   r  r>   r   r  r   r"  r#  r$  r&  r(  r*  r   r+  r,  r-  r.  r:   r:   r:   r;   r    s,   


r  )'r  abcr   r   r   r   r   r   weakrefrw   sslhasattrr   Zcatch23r   r   r	   
conversionr
   	constantsr   r   r   r   r   r   r   Zoptionfilesr   r   r   WeakValueDictionaryZNAMED_TUPLE_CACHErq   rv   rx   objectr   r  r:   r:   r:   r;   <module>   sD   $         #