U
    e`                     @   s  d 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 ddlmZmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZSmTZTmUZU eVeWXeY  eVeWZZG dd deZ[dS )z.Implementing communication with MySQL servers.    N)Decimal)IOBase)AnyBinaryIODict	GeneratorListMappingOptionalSequenceTupleTypeUnion   )version)MySQLConnectionAbstract)get_auth_plugin)NET_BUFFER_LENGTHCharacterSet
ClientFlag	FieldType	ServerCmd
ServerFlagShutdownTypeflag_is_set)MySQLConverter)
CursorBaseMySQLCursorMySQLCursorBufferedMySQLCursorBufferedDictMySQLCursorBufferedNamedTupleMySQLCursorBufferedRawMySQLCursorDictMySQLCursorNamedTupleMySQLCursorPreparedMySQLCursorPreparedDictMySQLCursorRaw)DatabaseErrorErrorInterfaceErrorInternalErrorNotSupportedErrorOperationalErrorProgrammingErrorget_exception)MySQLTCPSocketMySQLUnixSocket)BaseAuthPlugin)MySQLProtocol)ConnAttrsTypeDescriptionTypeEofPacketTypeHandShakeTypeOkPacketType
ResultTypeRowType
SocketTypeStatsPacketType
StrOrBytes!SupportedMysqlBinaryProtocolTypes)get_platform	int1store	int4storelc_intc                       s  e Zd ZdZedd fddZddddZddd	d
Zdee	 ee	 ee	 e
e
eee	eee	eee	 f  f  ee edddZdee	 ee	 ee dddZeee dddZee	eedddZedddZddddZddddZdddd ZeZde
ee e
ee ee
ee d"d#d$Zdeeed&d'd(Z e
dd)d*d+Z!e"edd,d-Z#eedd.d/Z$ee%dd0d1Z&e	ed2d3d4Z'ee(dd5d6Z)deeee*  ee e+ee, ee% f d7d8d9Z-dee
 eeee*  ee ee+ee, ee% f d:d;d<Z.ddd=d>Z/e	ed?d@dAZ0de1eeee(dBdCdDZ2e1e3e(ddf dEdFdGZ4e
edHdIdJZ5eddKdLZ6dee
 e%dMdNdOZ7e8ddPdQZ9e
edRdSdTZ:e%ddUdVZ;eddWdXZ<de	e	e	e
e	e	e	e	ee dZ	d[d\Z=e"e	dd]d^Z>e>j?e	dd_d`d^Z>eddadbZ@e	ddcdddeZAdeee	ef  eee	ef  ddfdgdhZBdee
e
ddjdkdlZCe"ee
 ddmdnZDdee ee ee eeEeF  ee ee eFdodpdqZGdddrdsZHdddtduZIe1ddvdwdxZJe1ee, dvdydzZKeee	e
f dd{d|ZLeeee+e
ee* e%f f dd}d~ZMde
e
ddddZNeeOe	ee
ee* f f dddZPde
eQeR eQe e
eee+e
ee* e%f f dddZSe
ddddZTe
e
ee
dddZUe
ddddZVedddZWddddZX  ZYS )MySQLConnectionzConnection to a MySQL ServerN)kwargsreturnc                    s"  d | _ d | _d | _t   t| _t | _	d| _
d | _d | _d| _d| _d| _d| _d| _d| _d | _d| _d| _i | _d| _d| _d| _d| _d| _d| _d| _d| _d| _d | _ d| _!d | _"d | _#d | _$d| _%g | _&d| _'|rz| j(f | W n& t)k
r   | *  d | _ Y nX d S )	N-   F z	127.0.0.1i  r   Tr   )+	_protocol_socket
_handshakesuper__init__r   _converter_classr   get_default_client_flags_charset_idZ	_sql_modeZ
_time_zoneZ_autocommit_user	_password	_databaseZ_hostZ_port_unix_socketZ_client_hostZ_client_port_ssl_force_ipv6Z_use_unicodeZ_get_warningsZ_raise_on_warnings	_bufferedZ_unread_result_have_next_result_raw_in_transactionZ_prepared_statements_ssl_active_auth_plugin_krb_service_principalZ_pool_config_version_query_attrs_supported_columns_desc_mfa_nfactorconnect	Exceptionclose)selfrC   	__class__ [/var/www/html/assets/scripts/venv/lib/python3.8/site-packages/mysql/connector/connection.pyrK   x   sV    

zMySQLConnection.__init__)rD   c                 C   sz   t  }tjd}|d dkr$d}nd}tt |d t d|d	d	d
 tj
dd D |d d}| j| dS )z&Add the default connection attributes. r   ZGPLv2zGPL-2.0Z
Commercialarchzmysql-connector-python.c                 S   s   g | ]}t |qS rf   )str).0xrf   rf   rg   
<listcomp>   s     z;MySQLConnection._add_default_conn_attrs.<locals>.<listcomp>   r   )_pid	_platformZ_source_hostZ_client_nameZ_client_licenseZ_client_version_osN)r>   r   LICENSEsplitrk   osgetpidsocketgethostnamejoinVERSION_conn_attrsupdate)rc   platformZlicense_chunksZclient_licenseZdefault_conn_attrsrf   rf   rg   _add_default_conn_attrs   s    

z'MySQLConnection._add_default_conn_attrsc                 C   s4  | j  }|d dkrt|d| _| j|}|d }| t|tt	t
frP|nd| _t| j |d tj@ s| jdkr| jstd| jd	rtd
dd|  jtj M  _n| js|  jtjO  _|d tj@ r| tjg |d tj@ rd| _| tjg |d tj@ r*| tjg || _dS )z'Get the handshake from the MySQL server      NZserver_version_originalUnknownZcapabilitiesZmysql_clear_passwordzEClear password authentication is not supported over insecure channelsverify_certz1SSL is required but the server doesn't support iti  )errnoT)rH   recvr.   rI   rG   Zparse_handshakeZ_check_server_version
isinstancerk   bytes	bytearray_server_versionr   Zset_mysql_versionr   SSLr[   	is_securer)   rT   getrN   _ssl_disabledZPLUGIN_AUTHZset_client_flagsCLIENT_QUERY_ATTRIBUTESr]   ZMULTI_FACTOR_AUTHENTICATION)rc   packet	handshakeZserver_versionrf   rf   rg   _do_handshake   sB    
zMySQLConnection._do_handshaker   rE   )usernamepassworddatabaseclient_flagscharsetssl_options
conn_attrsrD   c           
      C   st  d| _ |dkri }| js|tj@ r| jj||d}| j| |ddk	r^d	|d}	nd}	| j
|d|d|d	|d
pd|dpd|	|d d| _ | jr|| jkr| j}td| j | jds| jdrtjdkr|st }td|| j | jj| j|||||| j | j|| jd
}| j| | || |tj@ sp|rp| | dS )ae  Authenticate with the MySQL server

        Authentication happens in two parts. We first send a response to the
        handshake. The MySQL server will then send either an AuthSwitchRequest
        or an error packet.

        Raises NotSupportedError when we get the old, insecure password
        reply back. Raises any error coming from MySQL.
        FN)r   r   tls_ciphersuites:rF   cacertkeyr   Zverify_identityZtls_versionsTz## _do_auth(): self._auth_plugin: %sZauthentication_ociZauthentication_kerberosntz4MySQL user is empty, OS user: %s will be used for %s)
r   r   r   r   r   r   ssl_enabledauth_pluginr   Zauth_plugin_class)rZ   r   r   r   rG   Zmake_auth_sslrH   sendr   ry   Zswitch_to_ssl
_password1_LOGGERdebugr[   
startswithru   namegetpassgetuserZ	make_authrI   _auth_plugin_class_auth_switch_requestCONNECT_WITH_DBcmd_init_db)
rc   r   r   r   r   r   r   r   r   r   rf   rf   rg   _do_auth   sp     	


zMySQLConnection._do_auth)r   r   rD   c                 C   s8  d}| j p| jd }td| | j }|d dkrJt|dkrJtd|d dkr| j	|\}}t
|| j||pz| j|| jd}| |||}|d d	kr| j|}t
|| j||| jd
}|dkr| }|r| j| | j }|d dkr| |S |d dkr| |S |d dkr4t|dS )zHandle second part of authentication

        Raises NotSupportedError when we get the old, insecure password
        reply back. Raises any error coming from MySQL.
        Nr   znew_auth_plugin: %sr         zAuthentication with old (insecure) passwords is not supported. For more information, lookup Password Hashing in the latest MySQL manualr   r   r   r   r   r   caching_sha2_passwordr      r   )r[   rI   r   r   rH   r   lenr+   rG   Zparse_auth_switch_requestr   r   rP   r   _auth_continueparse_auth_more_dataauth_responser   
_handle_ok_handle_mfar.   )rc   r   r   authZnew_auth_pluginr   	auth_dataresponserf   rf   rg   r   ?  sP    



  


z$MySQLConnection._auth_switch_request)r   rD   c                 C   s,  |  j d7  _ | j dkr | j}n| j dkr2| j}ntdtd| j  | j|dd \}}t|| j	d| j
|| jd}| |||}|d dkr| j|}t|| j	||| jd	}|d
kr| }|r| j| | j }|d dkr| |S |d dkr| |S |d dkr(t|dS )z#Handle Multi Factor Authentication.r   r   ro   z5Failed Multi Factor Authentication (invalid N factor)z# MFA N Factor #%dr   Nr   r   r   r   r   )r_   
_password2
_password3r)   r   r   rG   Zparse_auth_next_factorr   r   rP   r   r   r   r   rH   r   r   r   r   r.   )rc   r   r   r   r   r   r   rf   rf   rg   r   t  sH    



  


zMySQLConnection._handle_mfa)r   r   r   rD   c                 C   s
  |dkr"t d| || j}nL|dkrBt d| ||}n,|dkrft d| j || j}n| }t d|t| | j| | j }t d| |dkr@t|dkr@|d	 d
kr@|d dkr@|d	d }|	|}| j| | j }|d	 dkr|d dkr|
|d	d r| j }n|dkr|dkr|d dkrd	}t d t d|d|d   t dt| t d d}	d}
|	s<|
d	k r<t dd|
d d t d| t d|d|d   |||d \}}	t d| | j|p"d | j }|
d7 }
q|	sVtd|
 d| t d |t| |||d }t d!|t| | j| | j }t d"| | j }t d#| n>|dkr|d dkrd	}t d$ t d%|d|d   t d&t| t d d}	d}
|	s|
d	k rt dd|
d d t d'| t d(|d|d   |	||d \}}	|r| j| |	rq| j }t d)| |
d7 }
q(|	std|
 d| t d*|t| | j }t d+| |S ),z!Continue with the authentication.Zauthentication_ldap_sasl_clientz# auth_data: %sauthentication_kerberos_clientZauthentication_oci_clientz!# oci configuration file path: %sz# request: %s size: %sz# server response packet: %s   r   r   =   Nv   s   GSSAPIr   r   z*# Continue with sasl GSSAPI authenticationz# response header: %sr   z# response size: %sz# Negotiate a service requestFr   z%s Attempt %s %sz--------------------z<< server response: %sz# response code: %sz >> response to server: %s    z'Unable to fulfill server request after z! attempts. Last server response: z0 last GSSAPI response from server: %s length: %dz* >> last response to server: %s length: %dz"<< final handshake from server: %sz<< ok packet from server: %sz%# Continue with GSSAPI authenticationz# Response header: %sz# Response size: %sz<< Server response: %sz# Response code: %sz>> Response to server: %sz(Last response from server: %s length: %dz<< Ok packet from server: %s)r   r   r   r\   _oci_config_filer   rH   r   r   Zauth_continueZauth_finalizeZauth_continue_krbr)   Zauth_accept_close_handshake)rc   r   r   r   r   r   Zdec_responseZ	cresponseZ
rcode_sizeZcompletetriesstepZ	last_steptokenrf   rf   rg   r     s    















zMySQLConnection._auth_continuec                 C   sF   d}| j r"tjdkr"t| jd}nt| j| j| jd}|	| j
 |S )zGet connection based on configuration

        This method will return the appropriated connection object using
        the connection parameters.

        Returns subclass of MySQLBaseSocket.
        Nposix)unix_socket)hostportZ
force_ipv6)rS   ru   r   r0   r   r/   Zserver_hostZserver_portrU   set_connection_timeoutZ_connection_timeout)rc   connrf   rf   rg   _get_connection  s    zMySQLConnection._get_connectionc              	   C   s*  | j dkr(| js(t| j | j}| | _t | _|  | _zv| j	  | 
  | | j| j| j| j| j| j| j | | j | jtj@ r| jj| j_| jj| j_| jd W n tk
r   |    Y nX | js&t| jjdr&t | jjj!r&| jj! }|dkr&d| d}t"#|t$ dS )zOpen the connection to the MySQL server

        This method sets up and opens the connection to the MySQL server.

        Raises on errors.
        r   Nr   )TLSv1zTLSv1.1zThis connection is using zZ which is now deprecated and will be removed in a future release of MySQL Connector/Python)%r[   rP   r   r   Zget_user_from_credentialsr2   rG   r   rH   open_connectionr   r   rQ   rR   rN   rO   rT   r{   Zset_converter_classrL   r   ZCOMPRESSZrecv_compressedr   Zsend_compressedr   r   ra   rb   r   hasattrsockcallabler   warningswarnDeprecationWarning)rc   clsZtls_versionZwarn_msgrf   rf   rg   _open_connection-  sH    


	

z MySQLConnection._open_connectionc              	   C   s6   | j s
dS z| j   W n ttfk
r0   Y nX dS )z%Shut down connection to MySQL Server.N)rH   shutdownAttributeErrorr(   rc   rf   rf   rg   r   _  s    zMySQLConnection.shutdownc              	   C   sD   | j s
dS z|   W n ttfk
r.   Y nX | j   d| _dS )z Disconnect from the MySQL serverN)rH   cmd_quitr   r(   Zclose_connectionrI   r   rf   rf   rg   rb   i  s    
zMySQLConnection.closeT)commandargumentpacket_numberr   expect_responsecompressed_packet_numberrD   c              
   C   sj   |    z"| j| j||p||| W n, tk
rV } ztd|W 5 d}~X Y nX |s`dS | j S )a4  Send a command to the MySQL server

        This method sends a command with an optional argument.
        If packet is not None, it will be sent and the argument will be
        ignored.

        The packet_number is optional and should usually not be used.

        Some commands might not result in the MySQL server returning
        a response. If a command does not return anything, you should
        set expect_response to False. The _send_cmd method will then
        return None instead of a MySQL packet.

        Returns a MySQL packet or None.
        MySQL Connection not availableN)handle_unread_resultrH   r   rG   make_commandr   r,   r   )rc   r   r   r   r   r   r   errrf   rf   rg   	_send_cmdw  s    zMySQLConnection._send_cmdF)	data_filesend_empty_packetrD   c              
   C   s   |    t|dstdz2|td }|rJ| j| |td }q*W n, tk
rx } ztd|W 5 d}~X Y nX |rz| jd W n, tk
r } ztd|W 5 d}~X Y nX | j	 S )a4  Send data to the MySQL server

        This method accepts a file-like object and sends its data
        as is to the MySQL server. If the send_empty_packet is
        True, it will send an extra empty package (for example
        when using LOAD LOCAL DATA INFILE).

        Returns a MySQL packet.
        readzexpecting a file-like object   r   Nr   )
r   r   
ValueErrorr   r   rH   r   r   r,   r   )rc   r   r   bufr   rf   rf   rg   
_send_data  s     
zMySQLConnection._send_data)flagsrD   c                 C   s    t tj|| _t tj|| _dS )a  Handle the server flags found in MySQL packets

        This method handles the server flags send by MySQL OK and EOF
        packets. It, for example, checks whether there exists more result
        sets or whether there is an ongoing transaction.
        N)r   r   ZMORE_RESULTS_EXISTSrW   ZSTATUS_IN_TRANSrY   )rc   r   rf   rf   rg   _handle_server_status  s    z%MySQLConnection._handle_server_statusc                 C   s   | j S )z'MySQL session has started a transaction)rY   r   rf   rf   rg   in_transaction  s    zMySQLConnection.in_transactionc                 C   sJ   |d dkr*| j |}| |d  |S |d dkr>t|tddS )a  Handle a MySQL OK packet

        This method handles a MySQL OK packet. When the packet is found to
        be an Error packet, an error will be raised. If the packet is neither
        an OK or an Error packet, InterfaceError will be raised.

        Returns a dict()
        r   r   status_flagr   zExpected OK packetN)rG   Zparse_okr   r.   r)   )rc   r   Zok_pktrf   rf   rg   r     s    	zMySQLConnection._handle_okc                 C   sJ   |d dkr*| j |}| |d  |S |d dkr>t|tddS )a  Handle a MySQL EOF packet

        This method handles a MySQL EOF packet. When the packet is found to
        be an Error packet, an error will be raised. If the packet is neither
        and OK or an Error packet, InterfaceError will be raised.

        Returns a dict()
        r   r   r   r   zExpected EOF packetN)rG   Z	parse_eofr   r.   r)   )rc   r   eofrf   rf   rg   _handle_eof  s    	zMySQLConnection._handle_eof)filenamerD   c                 C   s  t j|}t j|r td| js4| js4td| js| jrt j| j}d}zt j||g}W n> t	k
r } z d}t
|t||||W 5 d}~X Y nX ||krd}t|||zz$t|d}| | j|ddW W nS  tk
rP   z| jd	 W n. tk
r8 } ztd
|W 5 d}~X Y nX t
d| ddY nX W 5 z|  W n ttfk
r|   Y nX X dS )z'Handle a LOAD DATA INFILE LOCAL requestz#Use of symbolic link is not allowedKLOAD DATA LOCAL INFILE file request rejected due to restrictions on access.NzL{} while loading file `{}` and path `{}` given in allow_local_infile_in_pathzEThe file `{}` is not found in the given allow_local_infile_in_path {}rbT)r   r   r   zFile 'z' could not be read)ru   pathabspathislinkr,   Z_allow_local_infile_allow_local_infile_in_pathr'   
commonpathr   r)   formatrk   rb   IOError	NameErroropenr   r   rH   r   r   )rc   r   	file_nameZinfile_pathZc_pathr   err_msgr   rf   rf   rg   _handle_load_data_infile  sJ    
z(MySQLConnection._handle_load_data_infilec                 C   s   |rt |dk rtd|d dkr.| |S |d dkrT|dd  }| |S |d dkrj| |S |d dkr~t|| j|}|rt	|t
std	dg| | _td|D ] }| j| j | j| j|< q| | j }d
| _| j|dS )a  Handle a MySQL Result

        This method handles a MySQL result, for example, after sending the
        query command. OK and EOF packets will be handled and returned. If
        the packet is an Error packet, an Error-exception will be
        raised.

        The dictionary returned of:
        - columns: column information
        - eof: the EOF-packet information

        Returns a dict()
        r   Empty responser      r   Nr   r   zIllegal result setT)columnsr   )r   r)   r   decoder  r   r.   rG   parse_column_countr   intr^   rangeparse_columnrH   r   python_charsetunread_result)rc   r   r   column_countir   rf   rf   rg   _handle_result   s4    


 zMySQLConnection._handle_result)binaryr  rawrD   c                 C   s.   | j d|||d\}}|r&|d |fS d|fS )aT  Get the next rows returned by the MySQL server

        This method gets one row from the result set after sending, for
        example, the query command. The result is a tuple consisting of the
        row and the EOF packet.
        If no row was available in the result set, the row data will be None.

        Returns a tuple.
        r   )countr  r  r  r   N)get_rows)rc   r  r  r  rowsr   rf   rf   rg   get_rowK  s    zMySQLConnection.get_row)r  r  r  r  	prep_stmtrD   c           
   
      s  |dkrj }jstdg df}zF|rRj}|dkr<d}jj|||}njjjj|d}W n, t	k
r } zd_|W 5 d}~X Y nX |\}}	|s|s܈j
dk	r|rtdr܈jj  fdd	|D }|	dk	r
d
|	kr|	d
 n|	d  d_||	fS )a  Get all rows returned by the MySQL server

        This method gets all rows returned by the MySQL server after sending,
        for example, the query command. The result is a tuple consisting of
        a list of rows and the EOF packet.

        Returns a tuple()
        NzNo result set availableutf8mb4utf8)r  F	converterc                    s   g | ]} |j qS rf   )r^   )rl   rowrow_to_pythonrc   rf   rg   rn     s     z,MySQLConnection.get_rows.<locals>.<listcomp>r   Zserver_status)rX   r  r*   r   rG   Zread_binary_resultrH   Zread_text_resultr   r(   r^   r   r  r  r   )
rc   r  r  r  r  r  r  r   r   Zeof_prf   r  rg   r  _  sZ         


zMySQLConnection.get_rowsc                 C   s   | j r|   dS )zConsume resultsN)r  r  r   rf   rf   rg   consume_results  s    zMySQLConnection.consume_results)r   rD   c                 C   s   |  | tj|dS )zChange the current database

        This method changes the current (default) database by sending the
        INIT_DB command. The result is a dictionary containing the OK packet
        information.

        Returns a dict()
        utf-8)r   r   r   ZINIT_DBencode)rc   r   rf   rf   rg   r     s    	zMySQLConnection.cmd_init_db)queryr  bufferedraw_as_stringrD   c              
   C   s  t |ts&t |tr|d}t|}| jdkr6| jnd}t }| jsZ| jrZtjdt	d | j
tj@ rg }g }g }	dgt| jd d  }
t| jD ]\}}|d	 }d}|d
kr|
|d   d	|d > O  < |ttjt|  qt |tr| j|\}}}|	| n8t |trL||}|	tt||  tj}nt |trv|	tt||  tj}nt |tr|	ttt||t||  tj}nt |tr|	td| tj}ntt |t j t j!fr
| j"|\}}|	| nDt |t j#t j$fr:| j%|\}}|	| nt&d|j'j( d|t|t|  |d |}|tt||  q|)tt| j |)td	 |	r|)d*dd |
D td	  t+||D ]\}}|)| |)| q|	D ]}|)| q|)| t|}z| ,| -t.j/|}W nL t&k
r } z,|j0dkrxd|j1krxd}t2|| W 5 d
}~X Y nX | j3rt4d|S )a  Send a query to the MySQL server

        This method send the query to the MySQL server and returns the result.

        If there was a text result, a tuple will be returned consisting of
        the number of columns and a list containing information about these
        columns.

        When the query doesn't return a text result, the OK or EOF packet
        information as dictionary will be returned. In case the result was
        an error, exception Error will be raised.

        Returns a tuple()
        r  r  r  <This version of the server does not support Query Attributescategoryr         r   Nz<dz&MySQL binary protocol can not handle 'z	' objectsr   c                 S   s   g | ]}t d |qS )B)structpack)rl   bitrf   rf   rg   rn   	  s     z-MySQLConnection.cmd_query.<locals>.<listcomp>il  zLoading local data is disabledr   z8Use cmd_query_iter for statements with multiple queries.)5r   r   rk   r  r   r]   _query_attrsr   r   WarningrN   r   r   r   	enumerateappendr?   r   ZNULLr  rG   Zprepare_binary_integerrA   ZVARCHARr   ZBLOBr   ZDECIMALfloatr)  r*  DOUBLEdatetimedateZprepare_binary_timestamp	timedeltatimeZprepare_binary_timer-   re   __name__extendry   zipr  r   r   QUERYr   msgr'   rW   r)   )rc   r   r  r!  r"  r   r   namestypesvaluesZnull_bitmapposZ
attr_tuplevaluer   packedZ
field_typer   _typeresultr   r  rf   rf   rg   	cmd_query  s    









zMySQLConnection.cmd_query)
statementsrD   c                 c   s   t  }t|t s,t|tr$|d}t |}| jtj@ rT|td |td || t	|}| 
| tj|V  | jr|   | 
| j V  q|dS )at  Send one or more statements to the MySQL server

        Similar to the cmd_query method, but instead returns a generator
        object to iterate through results. It sends the statements to the
        MySQL server and through the iterator you can get the results.

        statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
        for result in cnx.cmd_query(statement, iterate=True):
            if 'columns' in result:
                columns = result['columns']
                rows = cnx.get_rows()
            else:
                # do something useful with INSERT result

        Returns a generator.
        r  r   r   N)r   r   rk   r  rN   r   r   r7  rA   r   r  r   r   r9  rW   r   rH   r   )rc   rD  r   r   rf   rf   rg   cmd_query_iter&  s    



zMySQLConnection.cmd_query_iter)optionsrD   c                 C   s   |  | tjt|S )a  Send the Refresh command to the MySQL server

        This method sends the Refresh command to the MySQL server. The options
        argument should be a bitwise value using constants.RefreshOption.
        Usage example:
         RefreshOption = mysql.connector.RefreshOption
         refresh = RefreshOption.LOG | RefreshOption.THREADS
         cnx.cmd_refresh(refresh)

        The result is a dictionary with the OK packet information.

        Returns a dict()
        )r   r   r   ZREFRESHr@   )rc   rF  rf   rf   rg   cmd_refreshP  s    zMySQLConnection.cmd_refreshc                 C   s*   |    | jtj}| j|dd |S )a  Close the current connection with the server

        This method sends the QUIT command to the MySQL server, closing the
        current connection. Since the no response can be returned to the
        client, cmd_quit() will return the packet it send.

        Returns a str()
        r   )r   rG   r   r   ZQUITrH   r   rc   r   rf   rf   rg   r   `  s    	zMySQLConnection.cmd_quit)shutdown_typerD   c                 C   s:   |rt |std|}nt j}| | tjt|S )aZ  Shut down the MySQL Server

        This method sends the SHUTDOWN command to the MySQL server and is only
        possible if the current user has SUPER privileges. The result is a
        dictionary containing the OK packet information.

        Note: Most applications and scripts do not the SUPER privilege.

        Returns a dict()
        zInvalid shutdown type)	r   get_infor)   ZSHUTDOWN_DEFAULTr   r   r   SHUTDOWNr@   )rc   rI  Zatyperf   rf   rg   cmd_shutdowno  s    
zMySQLConnection.cmd_shutdownc                 C   s8   |    | jtj}| j|dd | j| j S )zSend the statistics command to the MySQL Server

        This method sends the STATISTICS command to the MySQL server. The
        result is a dictionary with various statistical information.

        Returns a dict()
        r   )	r   rG   r   r   Z
STATISTICSrH   r   Zparse_statisticsr   rH  rf   rf   rg   cmd_statistics  s    zMySQLConnection.cmd_statistics)	mysql_pidrD   c                 C   s   |  | tjt|S )zKill a MySQL process

        This method send the PROCESS_KILL command to the server along with
        the process ID. The result is a dictionary with the OK packet
        information.

        Returns a dict()
        )r   r   r   ZPROCESS_KILLr@   )rc   rN  rf   rf   rg   cmd_process_kill  s    	z MySQLConnection.cmd_process_killc                 C   s   |  | tjS )aF  Send the DEBUG command

        This method sends the DEBUG command to the MySQL server, which
        requires the MySQL user to have SUPER privilege. The output will go
        to the MySQL server error log and the result of this method is a
        dictionary with EOF packet information.

        Returns a dict()
        )r   r   r   DEBUGr   rf   rf   rg   	cmd_debug  s    
zMySQLConnection.cmd_debugc                 C   s   |  | tjS )a  Send the PING command

        This method sends the PING command to the MySQL server. It is used to
        check if the the connection is still valid. The result of this
        method is dictionary with OK packet information.

        Returns a dict()
        )r   r   r   ZPINGr   rf   rf   rg   cmd_ping  s    	zMySQLConnection.cmd_pingrF   )	r   r   r   r   	password1	password2	password3oci_config_filerD   c	                 C   s   t |tstd|dk r"tdd| _|| _|| _|| _|| _|| _| jr\|| jkr\| j}| 	  | j
rrtd| jj| j||||| j| j| j| jd	}	| j|	dd |r|| _| ||}
| jtj@ s|r| | || _|   |
S )zChange the current logged in user

        This method allows to change the current logged in user information.
        The result is a dictionary with OK packet information.

        Returns a dict()
        zcharset must be an integerr   z2charset should be either zero or a postive integerr   z-Change user is not supported with compression)	r   r   r   r   r   r   r   r   r   )r   r  r   r_   rP   rQ   r   r   r   r   Z	_compressr+   rG   Zmake_change_userrI   rN   rZ   r[   r{   rH   r   r   r   r   r   r   rO   _post_connection)rc   r   r   r   r   rS  rT  rU  rV  r   Z	ok_packetrf   rf   rg   cmd_change_user  sF    

zMySQLConnection.cmd_change_userc                 C   s   |  dd S )zGet the current databasezSELECT DATABASE()r   )
info_queryr   rf   rf   rg   r     s    zMySQLConnection.database)r?  rD   c                 C   s   |  d|  dS )zSet the current databasezUSE N)rC  )rc   r?  rf   rf   rg   r     s    c                 C   s(   z|    W n tk
r"   Y dS X dS )a2  Reports whether the connection to MySQL Server is available

        This method checks whether the connection to MySQL is available.
        It is similar to ping(), but unlike the ping()-method, either True
        or False is returned and no exception is raised.

        Returns True or False.
        FT)rR  r(   r   rf   rf   rg   is_connected  s
    	zMySQLConnection.is_connected)r   rD   c                 C   s
   || _ dS )zySet the path that user can upload files.

        Args:
            path (str): Path that user can upload files.
        N)r   )rc   r   rf   rf   rg   set_allow_local_infile_in_path  s    z.MySQLConnection.set_allow_local_infile_in_path)user_variablessession_variablesrD   c              
   C   s   |   std|  sbz,| | j| j| j| j| j| j	| j
| j W n tk
r`   |   Y nX |  }|r| D ]\}}|d| d|f qv|r| D ]\}}|d| d|f qd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.zSET @`z` = %szSET SESSION `N)rZ  r,   cmd_reset_connectionrX  rP   rQ   rR   rO   r   r   r   r   r-   	reconnectcursoritemsexecute)rc   r\  r]  curr   r?  rf   rf   rg   reset_session  s.    
zMySQLConnection.reset_sessionr   )r_  attemptsdelayrD   c              
   C   sR   z|    W n@ tk
rL } z"|r2| j||d n
td|W 5 d}~X Y nX dS )a  Check availability of the MySQL server

        When reconnect is set to True, one or more attempts are made to try
        to reconnect to the MySQL server using the reconnect()-method.

        delay is the number of seconds to wait between each retry.

        When the connection is not available, an InterfaceError is raised. Use
        the is_connected()-method if you just want to check the connection
        without raising an error.

        Raises InterfaceError on errors.
        )re  rf  z$Connection to MySQL is not availableN)rR  r(   r_  r)   )rc   r_  re  rf  r   rf   rf   rg   pingB  s    zMySQLConnection.pingc                 C   s   | j r| j dS dS )zMySQL connection IDZserver_threadidN)rI   r   r   rf   rf   rg   connection_idX  s    zMySQLConnection.connection_id)r!  r  preparedcursor_class
dictionarynamed_tuplerD   c                    s"  |    |  std|dk	r:t|ts2td|| S |dk	rF|n| j}|dk	rX|n| j}d|dkrrdO |dkrdO |dkrdO |dkrd	O |dkrd
O tt	t
tttttttd
}z| | W S  tk
r   d tdd fddtdD  dY nX dS )a  Instantiates and returns a cursor

        By default, MySQLCursor is returned. Depending on the options
        while connecting, a buffered and/or raw cursor is instantiated
        instead. Also depending upon the cursor options, rows can be
        returned as dictionary or named tuple.

        Dictionary and namedtuple based cursors are available with buffered
        output but not raw.

        It is possible to also give a custom cursor through the
        cursor_class parameter, but it needs to be a subclass of
        mysql.connector.cursor.CursorBase.

        Raises ProgrammingError when cursor_class is not a subclass of
        CursorBase. Raises ValueError when cursor is not available.

        Returns a cursor-object
        r   Nz6Cursor class needs be to subclass of cursor.CursorBaser   Tr   r   r   r'  r   )
r   r   r   ro   r   r   r'  	   r      )r!  r  rk  rl  ri  z*Cursor not available with given criteria: z, c                    s$   g | ]}d |> @ dkr | qS )r   r   rf   )rl   r  argsZcursor_typerf   rg   rn     s      z*MySQLConnection.cursor.<locals>.<listcomp>r   )r   rZ  r,   
issubclassr   r-   rV   rX   r   r   r&   r!   r"   r   r#   r    r$   r%   KeyErrorr   ry   r	  )rc   r!  r  ri  rj  rk  rl  r<  rf   ro  rg   r`  _  sX    
zMySQLConnection.cursorc                 C   s   |  d dS )zCommit current transactionZCOMMITN)_execute_queryr   rf   rf   rg   commit  s    zMySQLConnection.commitc                 C   s   | j r|   | d dS )zRollback current transactionZROLLBACKN)r  r  rs  r   rf   rf   rg   rollback  s    zMySQLConnection.rollback)r   rD   c                 C   s   |    | | dS )a  Execute a query

        This method simply calls cmd_query() after checking for unread
        result. If there are still unread result, an InterfaceError
        is raised. Otherwise whatever cmd_query() returns is returned.

        Returns a dict()
        N)r   rC  )rc   r   rf   rf   rg   rs    s    	zMySQLConnection._execute_queryc                 C   s   | j dd}|| | S )z%Send a query which only returns 1 rowT)r!  )r`  rb  Zfetchone)rc   r   r`  rf   rf   rg   rY    s    
zMySQLConnection.info_queryc                 C   s8   |d dkr| j |S |d dkr,t|tddS )a>  Handle a MySQL Binary Protocol OK packet

        This method handles a MySQL Binary Protocol OK packet. When the
        packet is found to be an Error packet, an error will be raised. If
        the packet is neither an OK or an Error packet, InterfaceError
        will be raised.

        Returns a dict()
        r   r   r   zExpected Binary OK packetN)rG   Zparse_binary_prepare_okr.   r)   rH  rf   rf   rg   _handle_binary_ok  s
    
z!MySQLConnection._handle_binary_okc                 C   s   |rt |dk rtd|d dkr.| |S |d dkrD| |S |d dkrXt|| j|}|rrt|tsztddg| }t	d|D ]}| j
| j | j||< q| | j }|||fS )a  Handle a MySQL Result

        This method handles a MySQL result, for example, after sending the
        query command. OK and EOF packets will be handled and returned. If
        the packet is an Error packet, an Error exception will be raised.

        The tuple returned by this method consist of:
        - the number of columns in the result,
        - a list of tuples with information about the columns,
        - the EOF packet information as a dictionary.

        Returns tuple() or dict()
        r   r  r   r   r   zIllegal result set.N)r   r)   r   r   r.   rG   r  r   r  r	  r
  rH   r   r  )rc   r   r  r  r  r   rf   rf   rg   _handle_binary_result  s&    


 
z%MySQLConnection._handle_binary_result)statement_idr  rD   c                 C   s0   | j ||}d| _| jtj|dd d| _dS )zFetch a MySQL statement Result Set

        This method will send the FETCH command to MySQL together with the
        given statement id and the number of rows to fetch.
        Fr   TN)rG   Zmake_stmt_fetchr  r   r   Z
STMT_FETCH)rc   rx  r  r   rf   rf   rg   cmd_stmt_fetch  s    zMySQLConnection.cmd_stmt_fetch)	statementrD   c                 C   s   |  tj|}| |}g |d< g |d< |d dkrxtd|d D ]$}|d | j| j	 | j
 qB| | j	  |d dkrtd|d D ]$}|d | j| j	 | j
 q| | j	  |S )zPrepare a MySQL statement

        This method will send the PREPARE command to MySQL together with the
        given statement.

        Returns a dict()
        r  
parametersZ
num_paramsr   Znum_columns)r   r   ZSTMT_PREPARErv  r	  r/  rG   r
  rH   r   r  r   )rc   r{  r   rB  _rf   rf   rg   cmd_stmt_prepare	  s.    

  z MySQLConnection.cmd_stmt_preparerf   )rx  datar|  r   rD   c              
   C   s  t |}i }|rxt|D ]^\}}t|| trd}zd|| jk}W n tk
rX   Y nX | ||||  |f||< q| js| jrt	j
dtd | jtj@ r| j||t|||| j| j| j}	n"| jj||t|||| j| jd}	| jtj|	d}
| |
}|S )z"Execute a prepared MySQL statementTbr#  r$  )Zconverter_str_fallback)r   )listr.  r   r   moder   cmd_stmt_send_long_datar]   r,  r   r   r-  rN   r   r   rG   Zmake_stmt_executetupler   Z_converter_str_fallbackr   r   ZSTMT_EXECUTErw  )rc   rx  r  r|  r   Zlong_data_usedparam_idr}  r  Zexecute_packetr   rB  rf   rf   rg   cmd_stmt_execute+  sP    	
z MySQLConnection.cmd_stmt_execute)rx  rD   c                 C   s   | j tjt|dd dS )zDeallocate a prepared MySQL statement

        This method deallocates the prepared statement using the
        statement_id. Note that the MySQL server does not return
        anything.
        Fry  N)r   r   Z
STMT_CLOSEr@   rc   rx  rf   rf   rg   cmd_stmt_close^  s
    zMySQLConnection.cmd_stmt_close)rx  r  r  rD   c           	   
   C   s   d}d}zL| |}|rR| j|||}| jtj|dd |t|7 }| |}qW n, tk
r } ztd|W 5 d}~X Y nX |S )a.  Send data for a column

        This methods send data for a column (for example BLOB) for statement
        identified by statement_id. The param_id indicate which parameter
        the data belongs too.
        The data argument should be a file-like object.

        Since MySQL does not send anything back, no error is raised. When
        the MySQL server is not reachable, an OperationalError is raised.

        cmd_stmt_send_long_data should be called before cmd_stmt_execute.

        The total bytes send is returned.

        Returns int.
        i    r   F)r   r   r   N)	r   rG   Zprepare_stmt_send_long_datar   r   ZSTMT_SEND_LONG_DATAr   r   r,   )	rc   rx  r  r  
chunk_size
total_sentr   r   r   rf   rf   rg   r  k  s(    
  z'MySQLConnection.cmd_stmt_send_long_datac                 C   s   |  | tjt| dS )zReset data for prepared statement sent as long data

        The result is a dictionary with OK packet information.

        Returns a dict()
        N)r   r   r   Z
STMT_RESETr@   r  rf   rf   rg   cmd_stmt_reset  s    zMySQLConnection.cmd_stmt_resetc              	   C   s@   z |  | tj |   W dS  ttfk
r:   Y dS X dS )zResets the session state without re-authenticating

        Reset command only works on MySQL server 5.7.3 or later.
        The result is True for a successful reset otherwise False.

        Returns bool
        TFN)r   r   r   ZRESET_CONNECTIONrW  r+   r,   r   rf   rf   rg   r^    s    z$MySQLConnection.cmd_reset_connectionc                 C   s"   | j r|   n| jrtddS )z'Check whether there is an unread resultzUnread result foundN)Zcan_consume_resultsr  r  r*   r   rf   rf   rg   r     s    
z$MySQLConnection.handle_unread_result)NNNr   rE   NN)NN)Nr   NTr   )F)FNN)NFNNN)FFF)N)rF   rF   rF   rE   rF   rF   rF   rF   )NN)Fr   r   )NNNNNN)r   )rf   rf   r   )Zr6  
__module____qualname____doc__r   rK   r~   r   r
   rk   r  r   r   boolr   r3   r   r7   r   r   r   r1   r   r   r:   r   r   r   rb   Z
disconnectr   r   r   r   propertyr   r   r5   r   r  r8   r  r4   r   r9   r  r  r  r   r<   rC  r   rE  rG  r   rL  r;   rM  rO  rQ  rR  rX  r   setterrZ  r[  rd  rg  rh  r   r   r`  rt  ru  rs  rY  rv  rw  rz  r	   r~  r   r=   r  r  r  r  r^  r   __classcell__rf   rf   rd   rg   rB   u   s~  6/        Q    5+  z2
     (  !
0-   
     
;   {*        ?
  .      
K'%   3  '	rB   )\r  r2  r   loggingru   rw   r)  r   decimalr   ior   typingr   r   r   r   r   r	   r
   r   r   r   r   rF   r   Z	abstractsr   Zauthenticationr   	constantsr   r   r   r   r   r   r   r   
conversionr   r`  r   r   r   r   r    r!   r"   r#   r$   r%   r&   errorsr'   r(   r)   r*   r+   r,   r-   r.   networkr/   r0   pluginsr1   protocolr2   r<  r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   utilsr>   r?   r@   rA   	getLoggerr6  
addHandlerNullHandlerr   rB   rf   rf   rf   rg   <module>   s2   4(
4(
4
