o
    þÑÐb±À  ã                   @   s  d Z ddlm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mZmZmZ ddl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mZmZm Z  dd
l!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z* e +e,¡Z-G dd„ de*ƒZ.dS )z/Implementing communication with MySQL servers.
é    )ÚIOBaseNé   )Úget_auth_plugin)Ú
ClientFlagÚ	ServerCmdÚ
ServerFlagÚflag_is_setÚShutdownTypeÚNET_BUFFER_LENGTH)ÚerrorsÚversion)ÚMySQLConverter)
Ú
CursorBaseÚMySQLCursorÚMySQLCursorRawÚMySQLCursorBufferedÚMySQLCursorBufferedRawÚMySQLCursorPreparedÚMySQLCursorDictÚMySQLCursorBufferedDictÚMySQLCursorNamedTupleÚMySQLCursorBufferedNamedTuple)ÚMySQLUnixSocketÚMySQLTCPSocket)ÚMySQLProtocol)Ú	int4storeÚlinux_distribution)ÚMySQLConnectionAbstractc                       s  e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z		dudd„Zdvdd„Zdwdd„Z	dd„ Z
dd„ Zdd„ ZeZ			dxdd„Zdydd„Zdd„ Zedd „ ƒZd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zdzd)d*„Z		d{d+d,„Zd-d.„ Zd/d0„ Zd|d1d2„Zd3d4„ Zd5d6„ Zd7d8„ Zdwd9d:„Zd;d<„ Z d=d>„ Z!d?d@„ Z"dAdB„ Z#	C	
d}dDdE„Z$edFdG„ ƒZ%e%j&dHdG„ ƒZ%dIdJ„ Z'dKdL„ Z(dvdMdN„Z)d~dPdQ„Z*ddRdS„Z+edTdU„ ƒZ,		d€dVdW„Z-dXdY„ Z.dZd[„ Z/d\d]„ Z0d^d_„ Z1d`da„ Z2dbdc„ Z3dddde„Z4dfdg„ Z5d‚didj„Z6dkdl„ Z7dmdn„ Z8dodp„ Z9dqdr„ Z:dsdt„ Z;‡  Z<S )ƒÚMySQLConnectionzConnection to a MySQL Serverc                    s  d | _ d | _d | _tt| ƒj|i |¤Ž 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 | _%g | _&|r‰z| j'di |¤Ž W d S    |  (¡  d | _‚ d S )	Né-   FÚ z	127.0.0.1iê  r   T© ))Ú	_protocolÚ_socketÚ
_handshakeÚsuperr   Ú__init__r   Ú_converter_classr   Úget_defaultÚ_client_flagsÚ_charset_idZ	_sql_modeZ
_time_zoneZ_autocommitÚ_userÚ	_passwordÚ	_databaseZ_hostZ_portZ_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Ú_columns_descÚconnectÚclose)ÚselfÚargsÚkwargs©Ú	__class__r!   úY/var/www/secure340b-portal/env/lib/python3.10/site-packages/mysql/connector/connection.pyr&   >   sT   
ùzMySQLConnection.__init__c                 C   sü   t jdkr)dt ¡ d v rd}ndt ¡ d v rd}nt ¡ }d t ¡ d ¡}nt ¡ }t ¡ d	kr>d
 dt ¡ d ¡}n
d 	t
ƒ dd… ¡}tj d¡}|d dkrWd}nd}tt  ¡ ƒ|t ¡ d|d 	dd„ tjdd… D ƒ¡|dœ}| j |¡ dS )z&Add the default connection attributes.ÚntZ64r   Úx86_64Z32Úi386z
Windows-{}r   ÚDarwinz{}-{}ÚmacOSú-é   ú ZGPLv2zGPL-2.0Z
Commercialzmysql-connector-pythonÚ.c                 S   s   g | ]}t |ƒ‘qS r!   )Ústr)Ú.0Úxr!   r!   r?   Ú
<listcomp>Ž   s    z;MySQLConnection._add_default_conn_attrs.<locals>.<listcomp>é   )Ú_pidÚ	_platformZ_source_hostZ_client_nameZ_client_licenseZ_client_versionÚ_osN)ÚosÚnameÚplatformÚarchitectureÚformatÚ	win32_verÚmachineÚsystemÚmac_verÚjoinr   r   ÚLICENSEÚsplitrI   ÚgetpidÚsocketÚgethostnameÚVERSIONÚ_conn_attrsÚupdate)r:   Zplatform_archZos_verZlicense_chunksZclient_licenseZdefault_conn_attrsr!   r!   r?   Ú_add_default_conn_attrsr   s0   

ù	z'MySQLConnection._add_default_conn_attrsc              
   C   s  | j  ¡ }|d dkrt |¡‚d| _z| j |¡}W n ty2 } ztj|j	|j
|jd‚d}~ww |  |d ¡| _|d tj@ se| jdkrNd}t |¡‚| j d	¡r[tjd
dd‚|  jtj M  _n| jsp|  jtjO  _|d tj@ r~|  tjg¡ || _dS )z'Get the handshake from the MySQL serveré   éÿ   N)ÚmsgÚerrnoÚsqlstateZserver_version_originalZcapabilitiesZmysql_clear_passwordzEClear password authentication is not supported over insecure channelsÚverify_certz1SSL is required but the server doesn't support itiê  )rg   )r#   Úrecvr   Úget_exceptionr$   r"   Zparse_handshakeÚ	ExceptionZget_mysql_exceptionrf   rg   rh   Z_check_server_versionÚ_server_versionr   ÚSSLr5   ÚInterfaceErrorr.   Úgetr)   Z_ssl_disabledZPLUGIN_AUTHZset_client_flags)r:   ÚpacketÚ	handshakeÚerrÚerr_msgr!   r!   r?   Ú_do_handshake“   s:   

ÿ€þÿ

ÿ
zMySQLConnection._do_handshakeNr   r   c           
      C   sò   d| _ |tj@ rM| jj||d}| j |¡ | d¡dur&d | d¡¡}	nd}	| j 	| d¡| d¡| d	¡| d
¡p=d| d¡pCd|	| d¡¡ d| _ | jj
| j|||||| j | j|d	}| j |¡ |  ||¡ |tj@ sw|rw|  |¡ 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.
        F)ÚcharsetÚclient_flagsÚtls_ciphersuitesNú:r    ÚcaÚcertÚkeyri   Zverify_identityZtls_versionsT©	rr   ÚusernameÚpasswordÚdatabaserv   rw   Ússl_enabledÚauth_pluginÚ
conn_attrs)r4   r   rn   r"   Zmake_auth_sslr#   Úsendrp   rZ   Zswitch_to_sslZ	make_authr$   r5   Ú_auth_switch_requestÚCONNECT_WITH_DBÚcmd_init_db)
r:   r~   r   r€   rw   rv   Zssl_optionsrƒ   rq   rx   r!   r!   r?   Ú_do_authµ   s@   
ÿ
ùú
zMySQLConnection._do_authc                 C   s†  d}| j p	| jd }t d|¡ | j ¡ }|d dkr&t|ƒdkr&t d¡‚|d dkr{| j	 
|¡\}}t|ƒ|| j|| jd}|d	krRt d
|¡ | | 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r{d}
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 }|s:|dk sô|sDt d ||¡‚t d!|t|ƒ¡ | ||
d… ¡}t d"|t|ƒ¡ | j |¡ | j ¡ }t d#|¡ | j ¡ }t d$|¡ |d dkr©| j	 |¡}t|ƒ||| jd%}|d&kr©| ¡ }|r¤| j |¡ | j ¡ }|d dkrµ|  |¡S |d dkrÁt |¡‚dS )'z®Handle 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: %srd   éþ   é   z‡Authentication with old (insecure) passwords is not supported. For more information, lookup Password Hashing in the latest MySQL manual)r~   r   r   Zauthentication_ldap_sasl_clientz# auth_data: %sz# request: %s size: %sz# server response packet: %sé   ér   é=   év   s   GSSAPIre   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ó    zLUnable to fulfill server request after %s attempts. Last server response: %sz0 last GSSAPI response from server: %s length: %dz* >> last response to server: %s length: %dz"<< final handshake from server: %sz<< ok packet from server: %s)r   r   Zcaching_sha2_password)r5   r$   Ú_LOGGERÚdebugr#   rj   Úlenr   ÚNotSupportedErrorr"   Zparse_auth_switch_requestr   r+   r4   Zauth_responser6   r„   Zauth_continueZauth_finalizeZauth_continue_krbro   Zauth_accept_close_handshakeZparse_auth_more_dataÚ
_handle_okrk   )r:   r~   r   ÚauthZnew_auth_pluginrq   Z	auth_dataÚresponseZdec_responseZ	cresponseZ
rcode_sizeZcompleteÚtriesÚstepZ	last_stepr!   r!   r?   r…   â   sº   
ÿ
ÿþ

ÿ
ÿ
ÿ


€
ÿ
ÿ


ø	þÿÿ

ÿ



z$MySQLConnection._auth_switch_requestc                 C   sF   d}| j rtjdkrt| j d}n
t| j| j| jd}| | j	¡ |S )zÉGet connection based on configuration

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

        Returns subclass of MySQLBaseSocket.
        Nr@   )Úunix_socket)ÚhostÚportZ
force_ipv6)
r™   rQ   rR   r   r   Zserver_hostZserver_portr/   Úset_connection_timeoutZ_connection_timeout)r:   ZprtclsÚconnr!   r!   r?   Ú_get_connectionA  s   þzMySQLConnection._get_connectionc              	   C   sœ   t ƒ | _|  ¡ | _z<| j ¡  |  ¡  |  | j| j| j	| j
| j| j| j¡ |  | j¡ | j
tj@ r=| jj| j_| jj| j_| j d¡ W dS    |  ¡  ‚ )z–Open the connection to the MySQL server

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

        Raises on errors.
        N)r   r"   rž   r#   Úopen_connectionru   rˆ   r+   r,   r-   r)   r*   r.   ra   Zset_converter_classr'   r   ZCOMPRESSZrecv_compressedrj   Zsend_compressedr„   rœ   r9   ©r:   r!   r!   r?   Ú_open_connectionT  s"   

þz MySQLConnection._open_connectionc              	   C   s6   | j sdS z| j  ¡  W dS  ttjfy   Y dS w )z.Shut down connection to MySQL Server.
        N)r#   ÚshutdownÚAttributeErrorr   ÚErrorr    r!   r!   r?   r¢   m  s   ÿzMySQLConnection.shutdownc              	   C   sD   | j sdS z|  ¡  W n ttjfy   Y nw | j  ¡  d| _dS )z Disconnect from the MySQL serverN)r#   Úcmd_quitr£   r   r¤   Zclose_connectionr$   r    r!   r!   r?   r9   x  s   ÿ

zMySQLConnection.closeTc                 C   sV   |   ¡  z| j | j ||p|¡||¡ W n ty!   t d¡‚w |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 available.N)	Úhandle_unread_resultr#   r„   r"   Úmake_commandr£   r   ÚOperationalErrorrj   )r:   ÚcommandÚargumentZpacket_numberrq   Úexpect_responseZcompressed_packet_numberr!   r!   r?   Ú	_send_cmd†  s   þ
ÿ
zMySQLConnection._send_cmdFc                 C   s    |   ¡  t|dƒstdƒ‚z| td ¡}|r&| j |¡ | td ¡}|sW n ty3   t 	d¡‚w |rKz| j d¡ W n tyJ   t 	d¡‚w | 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¦   r   )r§   ÚhasattrÚ
ValueErrorr®   r
   r#   r„   r£   r   r©   rj   )r:   Ú	data_fileÚsend_empty_packetÚbufr!   r!   r?   Ú
_send_data¤  s,   

þ€
ÿÿÿ
zMySQLConnection._send_datac                 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_EXISTSr1   ZSTATUS_IN_TRANSr3   )r:   Úflagsr!   r!   r?   Ú_handle_server_statusÄ  s   ÿz%MySQLConnection._handle_server_statusc                 C   s   | j S )z'MySQL session has started a transaction)r3   r    r!   r!   r?   Úin_transactionÏ  s   zMySQLConnection.in_transactionc                 C   óJ   |d dkr| j  |¡}|  |d ¡ |S |d dkr t |¡‚t d¡‚)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, errors.InterfaceError will be raised.

        Returns a dict()
        rd   r   Ústatus_flagre   zExpected OK packet)r"   Zparse_okr·   r   rk   ro   )r:   rq   Zok_pktr!   r!   r?   r”   Ô  ó   	

zMySQLConnection._handle_okc                 C   r¹   )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, errors.InterfaceError will be raised.

        Returns a dict()
        rd   r‰   rº   re   zExpected EOF packet)r"   Z	parse_eofr·   r   rk   ro   )r:   rq   Úeofr!   r!   r?   Ú_handle_eofå  r»   zMySQLConnection._handle_eofc                 C   sr  t j |¡}t j |¡rt d¡‚| js| jst d¡‚| js_| jr_t j | j¡}d}z
t j 	||g¡}W n t
yO } zd}t | t|ƒ||¡¡‚d}~ww ||kr_d}t | ||¡¡‚zGz"t|dƒ}|  | j|dd¡W W z| ¡  W S  ttfy‚   Y S w  ty¦   z| j d	¡ W n ty   t d
¡‚w t d |¡¡‚w z| ¡  W w  ttfy¸   Y w w )z'Handle a LOAD DATA INFILE LOCAL requestz#Use of symbolic link is not allowedúKLOAD 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 '{0}' could not be read)rQ   ÚpathÚabspathÚislinkr   r©   Z_allow_local_infileÚ_allow_local_infile_in_pathÚDatabaseErrorÚ
commonpathr±   ro   rU   rI   Úopenr”   rµ   r9   ÚIOErrorÚ	NameErrorr#   r„   r£   )r:   ÚfilenameÚ	file_nameZinfile_pathZc_pathrs   rt   r²   r!   r!   r?   Ú_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r+|dd…  ¡ }|  |¡S |d dkr6|  |¡S |d dkrAt |¡‚| j 	|¡}|rNt
|tƒsSt 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 errors.Error-exception will be
        raised.

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

        Returns a dict()
        rd   úEmpty responser   éû   rŠ   Nr‰   re   úIllegal result set.T)Úcolumnsr¼   )r’   r   ro   r”   ÚdecoderË   r½   rk   r"   Úparse_column_countÚ
isinstanceÚintr7   ÚrangeÚparse_columnr#   rj   Úpython_charsetÚunread_result)r:   rq   rÉ   Úcolumn_countÚir¼   r!   r!   r?   Ú_handle_result%  s,   





ÿzMySQLConnection._handle_resultc                 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   )ÚcountÚbinaryrÏ   Úrawr   N)Úget_rows)r:   rÜ   rÏ   rÝ   Úrowsr¼   r!   r!   r?   Úget_rowM  s   


ÿzMySQLConnection.get_rowc           
   
      s  |du rˆj }ˆjst d¡‚z#|r&ˆj}|dkrd}ˆj ˆj|||¡}nˆjjˆjˆj	|d}W n tj
yD } zdˆ_|‚d}~ww |\}}	|sg|sgˆjdurg|rgtˆdƒrgˆjj‰ ‡ ‡fdd	„|D ƒ}|	dur}ˆ d
|	v ru|	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.Zutf8mb4Úutf8)rÛ   FÚ	converterc                    s   g | ]}ˆ |ˆj ƒ‘qS r!   )r7   )rJ   Úrow©Úrow_to_pythonr:   r!   r?   rL     s    z,MySQLConnection.get_rows.<locals>.<listcomp>rº   Zserver_status)r2   r×   r   ÚInternalErrorrv   r"   Zread_binary_resultr#   Zread_text_resultrm   r¤   r7   r°   râ   rå   r·   )
r:   rÛ   rÜ   rÏ   rÝ   Z	prep_stmtrv   rß   rs   Zeof_pr!   rä   r?   rÞ   ]  sH   


ÿ
þ€€þÿÿÿzMySQLConnection.get_rowsc                 C   s   | j r	|  ¡  dS dS )zConsume results
        N)r×   rÞ   r    r!   r!   r?   Úconsume_resultsŠ  s   ÿzMySQLConnection.consume_resultsc                 C   s   |   |  tj| d¡¡¡S )zëChange 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)r:   r€   r!   r!   r?   r‡     s   	ÿzMySQLConnection.cmd_init_dbc              
   C   s€   t |tƒs
| d¡}z|  |  tj|¡¡}W n tjy5 } z|j	dkr0d|j
v r0d}t |¡‚‚ d}~ww | jr>t d¡‚|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 errors.Error will be raised.

        Returns a tuple()
        rè   il  zLoading local data is disabledr¾   Nz8Use cmd_query_iter for statements with multiple queries.)rÒ   Úbytesré   rÚ   r­   r   ÚQUERYr   ÚProgrammingErrorrg   rf   rÄ   r1   ro   )r:   ÚqueryrÝ   ÚbufferedZraw_as_stringÚresultrs   rt   r!   r!   r?   Ú	cmd_queryœ  s$   


ÿ
€úÿzMySQLConnection.cmd_queryc                 c   sl    t |tƒst |tƒr| d¡}t|ƒ}|  |  tj|¡¡V  | jr4|  	¡  |  | j
 ¡ ¡V  | js"dS 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á   N)rÒ   Ú	bytearrayrI   ré   rÚ   r­   r   rë   r1   r§   r#   rj   )r:   Z
statementsr!   r!   r?   Úcmd_query_iter¼  s   €


þzMySQLConnection.cmd_query_iterc                 C   ó   |   |  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   )r:   Úoptionsr!   r!   r?   Úcmd_refreshÚ  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§   r"   r¨   r   ZQUITr#   r„   ©r:   rq   r!   r!   r?   r¥   ë  s   	zMySQLConnection.cmd_quitc                 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   ro   ZSHUTDOWN_DEFAULTr½   r­   r   ÚSHUTDOWNr   )r:   Zshutdown_typeZatyper!   r!   r?   Úcmd_shutdownú  s   

ÿzMySQLConnection.cmd_shutdownc                 C   s8   |   ¡  | j tj¡}| j |dd¡ | j | j ¡ ¡S )zâSend 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§   r"   r¨   r   Z
STATISTICSr#   r„   Zparse_statisticsrj   rö   r!   r!   r?   Úcmd_statistics  s   zMySQLConnection.cmd_statisticsc                 C   ró   )zÞKill 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   )r:   Z	mysql_pidr!   r!   r?   Úcmd_process_kill  s   	ÿz MySQLConnection.cmd_process_killc                 C   ó   |   |  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    r!   r!   r?   Ú	cmd_debug(  s   
zMySQLConnection.cmd_debugc                 C   rü   )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    r!   r!   r?   Úcmd_ping4  s   	zMySQLConnection.cmd_pingr    c                 C   s–   |   ¡  | jrt d¡‚| jj| j||||| j| j| j	| j
d	}| j |dd¡ |  ||¡}z| jtj@ s<|r<|  |¡ W n   ‚ || _|  ¡  |S )zÑChange 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.Change user is not supported with compression.r}   r   )r§   Z	_compressr   r“   r"   Zmake_change_userr$   r)   r4   r5   ra   r#   r„   r…   r   r†   r‡   r*   Ú_post_connection)r:   r~   r   r€   rv   rq   Z	ok_packetr!   r!   r?   Úcmd_change_user?  s0   	
úÿ
€zMySQLConnection.cmd_change_userc                 C   s   |   d¡d S )zGet the current databasezSELECT DATABASE()r   )Ú
info_queryr    r!   r!   r?   r€   d  s   zMySQLConnection.databasec                 C   s   |   d| ¡ dS )zSet the current databasezUSE %sN)rð   )r:   Úvaluer!   r!   r?   r€   i  s   c                 C   s   z|   ¡  W dS    Y 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)rÿ   r    r!   r!   r?   Úis_connectedn  s
   	
þzMySQLConnection.is_connectedc                 C   s
   || _ dS )zJset local_infile_in_path

        Set allow_local_infile_in_path.
        N)rÃ   )r:   rÀ   r!   r!   r?   Úset_allow_local_infile_in_path}  s   
z.MySQLConnection.set_allow_local_infile_in_pathc              	   C   s°   |   ¡ s	t d¡‚z|  ¡  W n tjy%   |  | j| j| j| j	¡ Y nw |  
¡ }|r?| ¡ D ]\}}| d |¡|f¡ q0|rT| ¡ D ]\}}| d |¡|f¡ qEdS 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.
        r¦   zSET @`{0}` = %szSET SESSION `{0}` = %sN)r  r   r©   Úcmd_reset_connectionr“   r  r+   r,   r-   r*   ÚcursorÚitemsÚexecuterU   )r:   Zuser_variablesZsession_variablesÚcurr|   r  r!   r!   r?   Úreset_session„  s$   
ÿÿþzMySQLConnection.reset_sessionr   c              
   C   s    d}||krN|d }z|   ¡  |  ¡  |  ¡ rW dS W n# ty> } z||kr4d |t|ƒ¡}t |¡‚W Y d}~nd}~ww |dkrHt 	|¡ ||ksdS 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)
Ú
disconnectr8   r  rl   rU   rI   r   ro   ÚtimeÚsleep)r:   ÚattemptsÚdelayÚcounterrs   rf   r!   r!   r?   Ú	reconnect¥  s*   ÿÿ
ý€ÿ
ózMySQLConnection.reconnectc                 C   s8   z|   ¡  W dS    |r| j||d Y dS t d¡‚)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.
        )r  r  z%Connection to MySQL is not available.N)rÿ   r  r   ro   )r:   r  r  r  r!   r!   r?   ÚpingÂ  s   
zMySQLConnection.pingc                 C   s   | j r	| j  d¡S dS )zMySQL connection IDZserver_threadidN)r$   rp   r    r!   r!   r?   Úconnection_idÙ  s   zMySQLConnection.connection_idc              
      s  |   ¡  |  ¡ st d¡‚|durt|tƒst d¡‚|| ƒS |dur%|n| j}|dur.|n| j}d‰|du r;ˆdO ‰|du rCˆdO ‰|du rKˆdO ‰|du rSˆd	O ‰|du r[ˆd
O ‰t	t
tttttttdœ	}z|ˆ | ƒW S  tyŠ   d‰ tdd ‡ ‡fdd„tdƒD ƒ¡ ƒ‚w )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   rF   rd   é   r¯   )	r   r   rF   rM   rd   rŠ   r  é	   r¯   )rî   rÝ   Ú
dictionaryÚnamed_tupleÚpreparedz*Cursor not available with given criteria: z, c                    s$   g | ]}ˆd |> @ dkrˆ | ‘qS ©r   r   r!   )rJ   rÙ   ©r;   Zcursor_typer!   r?   rL     s    ÿz*MySQLConnection.cursor.<locals>.<listcomp>rŠ   )r§   r  r   r©   Ú
issubclassr   rì   r0   r2   r   r   r   r   r   r   r   r   r   ÚKeyErrorr±   rZ   rÔ   )r:   rî   rÝ   r  Zcursor_classr  r  Útypesr!   r  r?   r  à  sP   

ÿ÷ÿþzMySQLConnection.cursorc                 C   s   |   d¡ dS )zCommit current transactionZCOMMITN)Ú_execute_queryr    r!   r!   r?   Úcommit!  s   zMySQLConnection.commitc                 C   s   | j r|  ¡  |  d¡ dS )zRollback current transactionZROLLBACKN)r×   rÞ   r  r    r!   r!   r?   Úrollback%  s   zMySQLConnection.rollbackc                 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 errors.InterfaceError
        is raised. Otherwise whatever cmd_query() returns is returned.

        Returns a dict()
        N)r§   rð   )r:   rí   r!   r!   r?   r  ,  s   	zMySQLConnection._execute_queryc                 C   s   | j dd}| |¡ | ¡ S )z%Send a query which only returns 1 rowT)rî   )r  r	  Zfetchone)r:   rí   r  r!   r!   r?   r  8  s   
zMySQLConnection.info_queryc                 C   s8   |d dkr| j  |¡S |d dkrt |¡‚t d¡‚)aE  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, errors.InterfaceError
        will be raised.

        Returns a dict()
        rd   r   re   zExpected Binary OK packet)r"   Zparse_binary_prepare_okr   rk   ro   rö   r!   r!   r?   Ú_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r#|  |¡S |d dkr.t |¡‚| j |¡}|r;t|t	ƒs@t d¡‚dg| }t
d|ƒD ]}| j | j ¡ | j¡||< qJ|  | 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 errors.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()
        rd   rÌ   r   r‰   re   rÎ   N)r’   r   ro   r”   r½   rk   r"   rÑ   rÒ   rÓ   rÔ   rÕ   r#   rj   rÖ   )r:   rq   rØ   rÏ   rÙ   r¼   r!   r!   r?   Ú_handle_binary_resultN  s$   






ÿ
z%MySQLConnection._handle_binary_resultc                 C   s0   | j  ||¡}d| _| jtj|dd d| _dS )z³Fetch 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)r"   Zmake_stmt_fetchr×   r­   r   Z
STMT_FETCH)r:   Ústatement_idrß   rq   r!   r!   r?   Úcmd_stmt_fetchs  s   
zMySQLConnection.cmd_stmt_fetchc                 C   sÌ   |   tj|¡}|  |¡}g |d< g |d< |d dkr<td|d ƒD ]}|d  | j | j 	¡ | j
¡¡ q!|  | j 	¡ ¡ |d dkrdtd|d ƒD ]}|d  | j | j 	¡ | j
¡¡ qI|  | j 	¡ ¡ |S )z£Prepare 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_PREPAREr"  rÔ   Úappendr"   rÕ   r#   rj   rÖ   r½   )r:   Z	statementrq   rï   Ú_r!   r!   r?   Úcmd_stmt_prepare~  s*   
ÿÿÿÿz MySQLConnection.cmd_stmt_preparer!   c              	   C   s°   t |ƒ}i }|r;t|ƒD ].\}}t|| tƒr:d}z	d|| jv}W n	 ty+   Y nw |  |||| ¡ |f||< q| j ||t	|ƒ||| j
¡}	| jtj|	d}
|  |
¡}|S )z"Execute a prepared MySQL statementTÚb)rq   )ÚlistÚ	enumeraterÒ   r   Úmoder£   Úcmd_stmt_send_long_datar"   Zmake_stmt_executeÚtuplerv   r­   r   ZSTMT_EXECUTEr#  )r:   r%  Údatar'  r¶   Zlong_data_usedÚparam_idr)  rÜ   Zexecute_packetrq   rï   r!   r!   r?   Úcmd_stmt_executeš  s.   ÿÿ
€þ
z MySQLConnection.cmd_stmt_executec                 C   s   | j tjt|ƒdd dS )zÃDeallocate a prepared MySQL statement

        This method deallocates the prepared statement using the
        statement_id. Note that the MySQL server does not return
        anything.
        Fr$  N)r­   r   Z
STMT_CLOSEr   ©r:   r%  r!   r!   r?   Úcmd_stmt_close²  s   
ÿzMySQLConnection.cmd_stmt_closec           	      C   s|   d}d}| j j}z)| |¡}|r/||||ƒ}| jtj|dd |t|ƒ7 }| |¡}|sW |S W |S  ty=   t 	d¡‚w )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)rq   r¬   r¦   )
r"   Z_prepare_stmt_send_long_datar®   r­   r   ZSTMT_SEND_LONG_DATAr’   r£   r   r©   )	r:   r%  r2  r1  Ú
chunk_sizeÚ
total_sentZprepare_packetr´   rq   r!   r!   r?   r/  ¼  s&   

ÿ
û	÷	ý
ÿz'MySQLConnection.cmd_stmt_send_long_datac                 C   s   |   |  tjt|ƒ¡¡ dS )z–Reset 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   r4  r!   r!   r?   Úcmd_stmt_resetß  s   
ÿzMySQLConnection.cmd_stmt_resetc                 C   s2   | j dk r
t d¡‚|  |  tj¡¡ |  ¡  dS )zÉResets the session state without re-authenticating

        Works only for MySQL server 5.7.3 or later.
        The result is a dictionary with OK packet information.

        Returns a dict()
        )rŠ   é   rM   zFMySQL version 5.7.2 and earlier does not support COM_RESET_CONNECTION.N)rm   r   r“   r”   r­   r   ZRESET_CONNECTIONr   r    r!   r!   r?   r  é  s   

z$MySQLConnection.cmd_reset_connectionc                 C   s&   | j r	|  ¡  dS | jrt d¡‚dS )z'Check whether there is an unread resultzUnread result foundN)Zcan_consume_resultsrç   r×   r   ræ   r    r!   r!   r?   r§   ø  s
   
ÿz$MySQLConnection.handle_unread_result)NNNr   r   NN)NN)N)Nr   NTr   )F)FNN)NFNNN)FFF)r    r    r    r   r  )Fr   r   )NNNNNN)r   )r!   r!   r   )=Ú__name__Ú
__module__Ú__qualname__Ú__doc__r&   rc   ru   rˆ   r…   rž   r¡   r¢   r9   r  r­   rµ   r·   Úpropertyr¸   r”   r½   rË   rÚ   rà   rÞ   rç   r‡   rð   rò   rõ   r¥   rù   rú   rû   rþ   rÿ   r  r€   Úsetterr  r  r  r  r  r  r  r   r!  r  r  r"  r#  r&  r*  r3  r5  r/  r8  r  r§   Ú__classcell__r!   r!   r=   r?   r   <   sŽ    4!"
ÿ
-
_
ÿ
 
/
(
ÿ-
 

ÿ%



!


ÿA
%

#
r   )/r=  Úior   ÚloggingrQ   rS   r^   r  Zauthenticationr   Ú	constantsr   r   r   r   r	   r
   r    r   r   Ú
conversionr   r  r   r   r   r   r   r   r   r   r   r   Únetworkr   r   Úprotocolr   Úutilsr   r   Ú	abstractsr   Ú	getLoggerr:  r   r   r!   r!   r!   r?   Ú<module>   s$    0
