o
    `^h                     @   s.  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZ d dlmZ d dl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 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'm(Z( d dl%m)Z) d dl%m*Z* d dl%m+Z+ d dl%m,Z, d dl%m-Z- d dl%m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7 ze8 Z9W n e:y   dZ9Y nw dddddddddedd e0dddddddddddfddZ;dd Z<d+dd Z=d,d!d"Z>G d#d$ d$e j?Z@G d%d& d&ZAG d'd( d(ZBG d)d* d*ZCdS )-    N)partial)charset_by_namecharset_by_id)SERVER_STATUS)CLIENT)COMMAND)CR)
FIELD_TYPE)escape_itemencodersdecodersescape_stringescape_bytes_prefixedthrough)
WarningErrorInterfaceError	DataErrorDatabaseErrorOperationalErrorIntegrityErrorInternalErrorNotSupportedErrorProgrammingError)
TEXT_TYPESMAX_PACKET_LENDEFAULT_CHARSET)_auth)MysqlPacket)FieldDescriptorPacket)EOFPacketWrapper)OKPacketWrapper)LoadLocalPacketWrapper   )Cursor)_pack_int24_lenenc_int_ConnectionContextManager_ContextManager)loggerunknown	localhost   Fc                 C   s   t di d| d|d|d|d|d|d|d|d	|d
|	d|
d|d|d|d|d|d|d|d|d|d|d|d|}t|S )zISee connections.Connection.__init__() for information about
    defaults.hostuserpassworddbportunix_socketcharsetsql_moderead_default_fileconvuse_unicodeclient_flagcursorclassinit_commandconnect_timeoutread_default_group
autocommitecholocal_infileloopsslauth_pluginprogram_nameN )_connectr'   )r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   server_public_keycororE   rE   Q/home/air/shanriGPT/back/venv/lib/python3.10/site-packages/aiomysql/connection.pyconnect0   sP    			

rJ   c                     s"   t | i |}| I d H  |S N)
ConnectionrF   )argskwargsconnrE   rE   rI   rF   I   s   rF   c                    sd   t j }t|d}t j||d |j fdd| |fi |I dH \}}t | ||}||fS )zThis is based on asyncio.open_connection, allowing us to use a custom
    StreamReader.

    `limit` arg has been removed as we don't currently use it.
    rA   c                          S rK   rE   rE   protocolrE   rI   <lambda>Y       z"_open_connection.<locals>.<lambda>N)asyncioeventsget_running_loop_StreamReaderStreamReaderProtocolcreate_connectionStreamWriter)r.   r2   kwdsrA   reader	transport_writerrE   rR   rI   _open_connectionO   s   

rb   c                    sb   t j }t|d}t j||d |j fdd| fi |I dH \}}t | ||}||fS )zThis is based on asyncio.open_unix_connection, allowing us to use a custom
    StreamReader.

    `limit` arg has been removed as we don't currently use it.
    rP   c                      rQ   rK   rE   rE   rR   rE   rI   rT   i   rU   z'_open_unix_connection.<locals>.<lambda>N)rV   rW   rX   rY   rZ   create_unix_connectionr\   )pathr]   rA   r^   r_   r`   ra   rE   rR   rI   _open_unix_connection^   s   

re   c                       s<   e Zd ZdZd
 fdd	Zd fddZedd	 Z  ZS )rY   a  This StreamReader exposes whether EOF was received, allowing us to
    discard the associated connection instead of returning it from the pool
    when checking free connections in Pool._fill_free_pool().

    `limit` arg has been removed as we don't currently use it.
    Nc                    s   d| _ t j|d d S )NFrP   )_eof_receivedsuper__init__)selfrA   	__class__rE   rI   rh   u   s   z_StreamReader.__init__returnc                    s   d| _ t   d S )NT)rf   rg   feed_eofri   rj   rE   rI   rm   y   s   z_StreamReader.feed_eofc                 C      | j S rK   )rf   rn   rE   rE   rI   eof_received}      z_StreamReader.eof_receivedrK   )rl   N)	__name__
__module____qualname____doc__rh   rm   propertyrp   __classcell__rE   rE   rj   rI   rY   n   s    rY   c                   @   sx  e Zd ZdZdddddddddeddedddddddddddfdd	Zed
d Zedd Z	edd Z
edd Zedd Zedd Zedd Zedd Zedd Zedd Zedd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!dd>d?Z"d@dA Z#dBdC Z$dDdE Z%ddGdHZ&dIdJ Z'dKdL Z(dMdN Z)dOdP Z*dQdR Z+e,fdSdTZ-dUdV Z.dWdX Z/ddYdZZ0d[d\ Z1d]d^ Z2d_d` Z3dadb Z4dcdd Z5dedf Z6dgdh Z7didj Z8dkdl Z9dmdn Z:dodp Z;dqdr Z<dsdt Z=dudv Z>dwdx Z?dydz Z@d{d| ZAd}d~ ZBeCZCeDZDeEZEeFZFeGZGeHZHeIZIeJZJeKZKeLZLdS )rL   zRepresentation of a socket with a mysql server.

    The proper way to get an instance of this class is to call
    connect().
    r+   Nr,   r-   r   Fc                 C   s  |pt  | _|du rtjd dkrd}|	rY|sd}t }|tj	
|	 t|j|}|d|d}|d|d}|d	|d}|d
|d}|d|d}t|d|d}|d|d}|| _|| _|pbt| _|pgd| _|| _|| _| j | _|| _d| _d| _d| _|| _d| _ddlm} dtt  |d| _!|r|| j!d< || _"|r|| _#d| _$nt%| _#d| _$|dur|| _$|| _&|r|t'j(O }t)| j#j*| _+|r|t'j,O }|t'j-O }|t'j.O }| jr|t'j/O }|| _0|| _1|| _2d| _3d| _4d| _5|| _6t7| _7|
| _8|| _9|| _:d| _;d| _<d| _=dS )az  
        Establish a connection to the MySQL database. Accepts several
        arguments:

        :param host: Host where the database server is located
        :param user: Username to log in as
        :param password: Password to use.
        :param db: Database to use, None to not use a particular one.
        :param port: MySQL port to use, default is usually OK.
        :param unix_socket: Optionally, you can use a unix socket rather
        than TCP/IP.
        :param charset: Charset you want to use.
        :param sql_mode: Default SQL_MODE to use.
        :param read_default_file: Specifies  my.cnf file to read these
            parameters from under the [client] section.
        :param conv: Decoders dictionary to use instead of the default one.
            This is used to provide custom marshalling of types.
            See converters.
        :param use_unicode: Whether or not to default to unicode strings.
        :param  client_flag: Custom flags to send to MySQL. Find
            potential values in constants.CLIENT.
        :param cursorclass: Custom cursor class to use.
        :param init_command: Initial SQL statement to run when connection is
            established.
        :param connect_timeout: Timeout before throwing an exception
            when connecting.
        :param read_default_group: Group to read from in the configuration
            file.
        :param autocommit: Autocommit mode. None means use server default.
            (default: False)
        :param local_infile: boolean to enable the use of LOAD DATA LOCAL
            command. (default: False)
        :param ssl: Optional SSL Context to force SSL
        :param auth_plugin: String to manually specify the authentication
            plugin to use, i.e you will want to use mysql_clear_password
            when using IAM authentication with Amazon RDS.
            (default: Server Default)
        :param program_name: Program name string to provide when
            handshaking with MySQL. (omitted by default)
        :param server_public_key: SHA256 authentication plugin public
            key value.
        :param loop: asyncio loop
        Nr      Tclientr/   )fallbackr0   r.   databasesocketr2   zdefault-character-setr,   Fr#   )__version__aiomysql)_client_name_pid_client_versionrD   zNot connected)>rV   get_event_loop_loopsysversion_infoconfigparserRawConfigParserreadosrd   
expanduserr   getint_host_portDEFAULT_USER_user	_password_db_echotime_last_usage_client_auth_plugin_server_auth_plugin_auth_plugin_used_securerG   saltr,   r}   strgetpid_connect_attrs_unix_socket_charsetr8   r   _ssl_contextr   SSLr   encoding	_encodingLOCAL_FILESCAPABILITIESMULTI_STATEMENTSCONNECT_WITH_DBr9   r:   r<   _result_affected_rows	host_infoautocommit_moder   r   r5   r;   _reader_writer_close_reason)ri   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rG   cfg_configr}   rE   rE   rI   rh      s   4









zConnection.__init__c                 C   ro   )zMySQL server IP address or name)r   rn   rE   rE   rI   r.        zConnection.hostc                 C   ro   )zMySQL server TCP/IP port)r   rn   rE   rE   rI   r2     r   zConnection.portc                 C   ro   )zMySQL Unix socket file location)r   rn   rE   rE   rI   r3   "  r   zConnection.unix_socketc                 C   ro   )zCurrent database name.)r   rn   rE   rE   rI   r1   '  r   zConnection.dbc                 C   ro   )z#User used while connecting to MySQL)r   rn   rE   rE   rI   r/   ,  r   zConnection.userc                 C   ro   )zReturn echo mode status.)r   rn   rE   rE   rI   r?   1  r   zConnection.echoc                 C   ro   )z'Return time() when connection was used.)r   rn   rE   rE   rI   
last_usage6  r   zConnection.last_usagec                 C   ro   rK   )r   rn   rE   rE   rI   rA   ;  rq   zConnection.loopc                 C   s
   | j du S )zVThe readonly property that returns ``True`` if connections is
        closed.
        N)r   rn   rE   rE   rI   closed?  s   
zConnection.closedc                 C   ro   )z&Encoding employed for this connection.)r   rn   rE   rE   rI   r   F  r   zConnection.encodingc                 C   ro   )z1Returns the character set for current connection.r   rn   rE   rE   rI   r4   K  r   zConnection.charsetc                 C   s"   | j r	| j j  d| _ d| _dS )zClose socket connectionN)r   r_   closer   rn   rE   rE   rI   r   P  s   
zConnection.closec                    sP   | j du rdS tddttjg }| j | | j  I dH  |   dS )z2Send quit command and then close socket connectionNz<ir#   )	r   structpackbytesr   COM_QUITwritedrainr   )ri   	send_datarE   rE   rI   ensure_closedW  s   
zConnection.ensure_closedc                    s2   t || _|  }||kr|  I dH  dS dS )zuEnable/disable autocommit mode for current MySQL session.

        :param value: ``bool``, toggle autocommit
        N)boolr   get_autocommit_send_autocommit_mode)ri   valuecurrentrE   rE   rI   r>   a  s   
zConnection.autocommitc                 C   s   | j tj@ }t|S )zgReturns autocommit status for current MySQL session.

        :returns bool: current autocommit status.)server_statusr   SERVER_STATUS_AUTOCOMMITr   )ri   statusrE   rE   rI   r   k  s   zConnection.get_autocommitc                    s6   |   I d H }| stddt|}|j| _dS )N  zCommand Out of SyncT)_read_packetis_ok_packetr   r!   r   )ri   pktokrE   rE   rI   _read_ok_packets  s   
zConnection._read_ok_packetc                    s4   |  tjd| | j I dH  |  I dH  dS )z3Set whether or not to commit after every execute() zSET AUTOCOMMIT = %sN)_execute_commandr   	COM_QUERYescaper   r   rn   rE   rE   rI   r   {  s   
z Connection._send_autocommit_modec                    (   |  tjdI dH  |  I dH  dS )zBegin transaction.BEGINNr   r   r   r   rn   rE   rE   rI   begin     zConnection.beginc                    r   )z!Commit changes to stable storage.COMMITNr   rn   rE   rE   rI   commit  r   zConnection.commitc                    r   )z"Roll back the current transaction.ROLLBACKNr   rn   rE   rE   rI   rollback  r   zConnection.rollbackc                    s(   |  tj|I dH  |  I dH  dS )zSet current dbN)r   r   COM_INIT_DBr   )ri   r1   rE   rE   rI   	select_db  r   zConnection.select_dbc                    s2   |  tjd I dH  t| }| I dH  |jS )zSHOW WARNINGSN)r   r   r   MySQLResultr   rows)ri   resultrE   rE   rI   show_warnings  s
   zConnection.show_warningsc                 C   s:   t |trd| | d S t |trt|S t|| jS )z% Escape whatever value you pass to it')
isinstancer   r   r   r   r
   r   ri   objrE   rE   rI   r     s
   

zConnection.escapec                 C   s
   |  |S )zAlias for escape())r   r   rE   rE   rI   literal  s   
zConnection.literalc                 C   s    | j tj@ r|ddS t|S )Nr   z'')r   r   "SERVER_STATUS_NO_BACKSLASH_ESCAPESreplacer   )ri   srE   rE   rI   r     s
   zConnection.escape_stringc                 G   s   |    | j | _z|rtdd |D rtdW n ty&   tdw |r8t|dkr8|d | | j}n&|rWdt	dd |
d	dd	 }t||i }|| | j}n| | | j}| j }|| t|S )
a  Instantiates and returns a cursor

        By default, :class:`Cursor` is returned. It is possible to also give a
        custom cursor through the cursor_class parameter, but it needs to
        be a subclass  of :class:`Cursor`

        :param cursor: custom cursor class.
        :returns: instance of cursor, by default :class:`Cursor`
        :raises TypeError: cursor_class is not a subclass of Cursor.
        c                 s   s    | ]	}t |t V  qd S rK   )
issubclassr$   ).0cursorrE   rE   rI   	<genexpr>  s    z$Connection.cursor.<locals>.<genexpr>z(Custom cursor must be subclass of Cursorr#   r   r,   c                 S   ro   rK   )rr   )xrE   rE   rI   rT     s    z#Connection.cursor.<locals>.<lambda>r$   )_ensure_aliver   r   r   any	TypeErrorlenr   joinmapr   typer:   create_future
set_resultr(   )ri   cursorscurcursor_namecursor_classfutrE   rE   rI   r     s.   


zConnection.cursorc                    sF   t |tr|| jd}| tj|I d H  | j|dI d H  | jS )Nsurrogateescape)
unbuffered)	r   r   encoder   r   r   r   _read_query_resultr   )ri   sqlr   rE   rE   rI   query  s   
zConnection.queryc                    s   |   I d H  | jS rK   )r   r   rn   rE   rE   rI   next_result  s   zConnection.next_resultc                 C   ro   rK   )r   rn   rE   rE   rI   affected_rows     zConnection.affected_rowsc                    s4   t d|}| tj|I d H  |  I d H  d S )N<I)r   r   r   r   COM_PROCESS_KILLr   )ri   	thread_idargrE   rE   rI   kill  s   zConnection.killTc                    s   | j du r| jdu r|r|  I dH  d}ntdz| tjdI dH  |  I dH  W dS  tyK   |rJ|  I dH  | 	dI dH  Y dS  w )zCheck if the server is aliveNFzAlready closedr,   )
r   r   rF   r   r   r   COM_PINGr   	Exceptionping)ri   	reconnectrE   rE   rI   r	    s   zConnection.pingc                    sH   t |j}| tjd| | I dH  |  I dH  || _|| _dS )z1Sets the character set for the current connectionzSET NAMES %sN)	r   r   r   r   r   r   r   r   r   )ri   r4   r   rE   rE   rI   set_charset  s   


zConnection.set_charsetc              
      s  z| j r!tjt| j | jdI d H \| _| _d| j  | _d| _n&tjt	| j
| j| jdI d H \| _| _|   | d d| j
| jf | _d| _|  I d H  |  I d H  | j | _| jd uro| d| j I d H  | jd ur| | jI d H  |  I d H  | jd ur| | jI d H  W d S W d S  ty } z#| jr| jj  d | _d | _t|tttj frt!t"j#d| j
 | d }~ww )N)timeoutzLocalhost via UNIX socket: Tzsocket %s:%dr   zSET sql_mode=z#Can't connect to MySQL server on %r)$r   rV   wait_forre   r<   r   r   r   r   rb   r   r   _set_keep_alive_set_nodelay_next_seq_id_get_server_information_request_authenticationr   r   connected_timer5   r   r;   r   r   r>   r  r_   r   r   IOErrorOSErrorTimeoutErrorr   r   CR_CONN_HOST_ERROR)ri   erE   rE   rI   rF      sh   



zConnection._connectc                 C   sL   | j j}|  |jdd d}|d u rtd|tjtjd |	  d S )Nr|   default)Transport does not expose socket instancer#   )
r   r_   pause_readingget_extra_infoRuntimeError
setsockoptr|   
SOL_SOCKETSO_KEEPALIVEresume_reading)ri   r_   raw_sockrE   rE   rI   r  =  s   zConnection._set_keep_alivec                 C   sX   t t|}| jj}|  |jdd d}|d u rtd|tj	tj
| |  d S )Nr|   r  r  )r   r   r   r_   r  r  r  r  r|   IPPROTO_TCPTCP_NODELAYr"  )ri   r   flagr_   r#  rE   rE   rI   r  F  s   zConnection._set_nodelayc                 C   s:   t t|t| jg | }| | | jd d | _dS )zwWrites an entire "mysql packet" in its entirety to the network
        addings its length and sequence number.
        r#      N)r%   r   r   r  _write_bytes)ri   payloaddatarE   rE   rI   write_packetP  s   
zConnection.write_packetc           
         s*  d}	 z
|  dI dH }W n tjy   |    w td|\}}}||d>  }|| jkrG|   |dkr>tt	j
dtd	|| jf | jd
 d | _z
|  |I dH }W n tjyf   |    w ||7 }|dkrpq|tk runq||| j}	|	 r| jdur| jjdu rd| j_|	  |	S )zRead an entire "mysql packet" in its entirety from the network
        and return a MysqlPacket type that represents the results.
            T   Nz<HBB   r   ,Lost connection to MySQL server during queryz1Packet sequence number wrong - got %d expected %dr#   r'  i F)_read_bytesrV   CancelledError_close_on_cancelr   unpackr  r   r   r   CR_SERVER_LOSTr   r   r   is_error_packetr   unbuffered_activeraise_for_error)
ri   packet_typebuffpacket_headerbtrlbtrhpacket_numberbytes_to_read	recv_datapacketrE   rE   rI   r   Z  sZ   

(
zConnection._read_packetc              
      s   z| j |I d H }W |S  tjy' } zd}|   ttj||d }~w tyC } zd| d}|   ttj||d }~ww )Nr/  z.Lost connection to MySQL server during query ())	r   readexactlyrV   IncompleteReadErrorr   r   r   r4  r  )ri   	num_bytesr*  r  msgrE   rE   rI   r0    s   	zConnection._read_bytesc                 C   s   | j |S rK   )r   r   )ri   r*  rE   rE   rI   r(    s   zConnection._write_bytesc                    s   d | _ |r"zt| }| I d H  W n ty!   d|_d |_ w t| }| I d H  || _ |j| _|j	d ur?|j	| _	d S d S )NF)
r   r   init_unbuffered_queryBaseExceptionr6  
connectionr   r   r   r   )ri   r   r   rE   rE   rI   r     s$   
zConnection._read_query_resultc                 C   s   | j r| j jS dS Nr   )r   	insert_idrn   rE   rE   rI   rJ    s   zConnection.insert_idc                    s   | S rK   rE   rn   rE   rE   rI   
__aenter__  s   zConnection.__aenter__c                    s$   |r	|    d S |  I d H  d S rK   )r   r   )ri   exc_typeexc_valexc_tbrE   rE   rI   	__aexit__  s   zConnection.__aexit__c                    s  |    | jd ur-| jjrtd | j I d H  | jjr*|  I d H  | jjsd | _t|t	r8|
| j}ttt|d }td||}| ||d |d    d| _|tk r^d S ||d d  }	 ttt|}| |d |  ||d  }|s|tk rd S qg)Nz.Previous unbuffered result was left incompleter#   z<iB)r   r   r6  warningswarn_finish_unbuffered_queryhas_nextr   r   r   r   r   minr   r   r   r   r(  r  r+  )ri   commandr   
chunk_sizepreluderE   rE   rI   r     s4   


zConnection._execute_commandc                    s
  t | jddd dkr|  jtjO  _| jd u rtdt| j	j
}td| jt|d}| jrq| jtj@ rq| | | jj  | jjjdd d	}|d u rTtd
| }| jj  t|| j| jdI d H \| _| _d| _t| jtr| j| j }n| j}|| d }d}| j!}| j!s| j"}|dv rt#$| j%d| j&}n>|dkr| j%rt#'| j%d| j&}n+|dkr| jr| jtj@ r| j%dd }n| j%rd}nd}n|dv r| j%dd }| jtj(@ r|t)t*|| 7 }n| jtj+@ r|tdt*|| 7 }n||d 7 }| j,r/| jtj-@ r/t| j,tr&| j,| j }n| j,}||d 7 }| jtj.@ rI|}	t|	trC|	d}	||	d 7 }|| _/| jtj0@ rd}
| j12 D ](\}}|d|d}}|
tdt*|| 7 }
|
tdt*|| 7 }
qZ|tdt*|
|
 7 }| | | 3 I d H }|4 r|5  |6 }| jtj.@ r|d ur| 7||I d H  d S t#8| j%d|9 d }| | | 3 I d H  d S |: r|dkr| ;|I d H  d S |dkr| <|I d H  d S t=d|d S )N.r#   r      zDid not specify a usernamez<iIB23sr,  r|   r  r  )sockrB   server_hostnameT    )r,   mysql_native_passwordlatin1caching_sha2_passwordsha256_password   )r,   mysql_clear_passwordBasciiutf8z(Received extra packet for auth method %r)>r   server_versionsplitr9   r   MULTI_RESULTSr/   
ValueErrorr   r4   idr   r   r   r   server_capabilitiesr   r+  r   r_   r  r  r  dupr   rb   r   r   r   r   r   r   r   r   r   r   scramble_native_passwordr   r   scramble_caching_sha2PLUGIN_AUTH_LENENC_CLIENT_DATAr&   r   SECURE_CONNECTIONr   r   PLUGIN_AUTHr   CONNECT_ATTRSr   itemsr   is_auth_switch_request
read_uint8read_string_process_authscramble_old_passwordread_allis_extra_auth_datacaching_sha2_password_authsha256_password_authr   )ri   
charset_id	data_initr#  r   r*  authresprC   r1   nameconnect_attrskvauth_packetplugin_namerE   rE   rI   r    s   











z"Connection._request_authenticationc                    s   |dkr|  |I d H  | | _d S |dkr'| |I d H  | | _d S |dkr8t| jd| }n(|dkrKt	| jd| d }n|dkrX| jdd }nt
dd	|| | |  I d H }|  | | _|S )
Ns   caching_sha2_passwords   sha256_passwords   mysql_native_passwordr^  s   mysql_old_passwordr\  s   mysql_clear_passwordi  z)Authentication plugin '{}' not configured)r{  decoder   r|  r   rm  r   r   ry  rx  r   formatr+  r   check_error)ri   r  r  r*  r   rE   rE   rI   rw  h  s<   



zConnection._process_authc                    s  | j s| d |  I d H }|  |S | r?td | | _t	
| j d| j}| | |  I d H }|  | sOtd|jd d |d | }|dkrntd |  I d H }|  |S |dkrytd	|td
 | jrtd | | j dd  |  I d H }|  |S | js| d |  I d H }|  | std|jd d |jdd  | _t| jd t	| j d| j| j}| | |  I d H }|  d S )Nr,  zcaching sha2: Trying fast pathr^  z.caching sha2: Unknown packet for fast auth: {}r#      z%caching sha2: succeeded by fast path.r-  z.caching sha2: Unknown result for fast auth: {}z!caching sha2: Trying full auth...z:caching sha2: Sending plain password via secure connectionr\     z/caching sha2: Unknown packet for public key: {}rd  )r   r+  r   r  rt  r)   debugry  r   r   rn  r   rz  r   r  _dataadvanceru  r   rG   r  sha2_rsa_encrypt)ri   r   	scramblednr*  rE   rE   rI   r{    sp   










z%Connection.caching_sha2_password_authc                    s  | j r#td | jdd }| | |  I d H }|  |S | rG|	 | _
| jsG| jrGtd | d |  I d H }|  | r]|jdd  | _td| jd | jru| jsgtd	t| jd| j
| j}nd
}| | |  I d H }|  |S )Nzsha256: Sending plain passwordr^  r\  z$sha256: Requesting server public keyra  r#   zReceived public key:
%srd  z$Couldn't receive server's public keyr,  )r   r)   r  r   r   r+  r   r  rt  ry  r   rG   rz  r  r  r   r   r  )ri   r   r*  rE   rE   rI   r|    sB   






zConnection.sha256_password_authc                 C   s
   | j d S rI  )server_thread_idrn   rE   rE   rI   r  
  s   
zConnection.thread_idc                 C   ro   rK   r   rn   rE   rE   rI   character_set_name  r  zConnection.character_set_namec                 C   ro   rK   )r   rn   rE   rE   rI   get_host_info  r  zConnection.get_host_infoc                 C   ro   rK   )protocol_versionrn   rE   rE   rI   get_proto_info  r  zConnection.get_proto_infoc           	         s  d}|   I d H }| }|| | _|d7 }|d|}||| d| _|d }td|||d  | _|d7 }|||d  | _	|d7 }td	|||d
  d | _
|d
7 }t||d krtd|||d  \}}}}|d7 }|| _zt|j| _W n ty   d | _Y nw || _|  j
|d> O  _
td|d }|d7 }t||| kr|  j	||||  7  _	||7 }|d7 }| j
tj@ rt||kr|d|}|dk r||d  d| _d S ||| d| _d S d S d S )Nr   r#   r\  r^  r  r-     	   z<Hrx      z<BHHBr.     
   )r   get_all_datar  findr  rf  r   r3  r  r   rk  r   server_languager   r  server_charsetKeyErrorr   maxr   rq  r   )	ri   ir@  r*  
server_endlangstatcap_hsalt_lenrE   rE   rI   r    sL   
 
z"Connection._get_server_informationc                 C   s   t | jtj@ S rK   )r   r   r   SERVER_STATUS_IN_TRANSrn   rE   rE   rI   get_transaction_statusT  s   z!Connection.get_transaction_statusc                 C   ro   rK   )rf  rn   rE   rE   rI   get_server_infoW  r  zConnection.get_server_infoc                 C   s   |    d| _d S )NzCancelled during execution)r   r   rn   rE   rE   rI   r2  \  s   
zConnection._close_on_cancelc                 C   s&   | j s| jd u rtdt| jd S )Nz(0, 'Not connected'))r   r   r   rn   rE   rE   rI   r   `  s
   

zConnection._ensure_alivec                 C   s(   | j rtd| t |   d S d S )NzUnclosed connection )r   rP  rQ  ResourceWarningr   rn   rE   rE   rI   __del__g  s   zConnection.__del__)F)T)Mrr   rs   rt   ru   r   r$   rh   rv   r.   r2   r3   r1   r/   r?   r   rA   r   r   r4   r   r   r>   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  r  rF   r  r  r+  r   r   r0  r(  r   rJ  rK  rO  r   r  rw  r{  r|  r  r  r  r  r  r  r  r2  r   r  r   r   r   r   r   r   r   r   r   r   rE   rE   rE   rI   rL      s    
 













!

=	

5
" *N*>rL   c                   @   sl   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )r   c                 C   sF   || _ d | _d | _d | _d| _d | _d| _d | _d | _d | _	d| _
d S )Nr   F)rH  r   rJ  r   warning_countmessagefield_countdescriptionr   rS  r6  )ri   rH  rE   rE   rI   rh   }  s   
zMySQLResult.__init__c                    s~   z9| j  I d H }| r| | n| r!| |I d H  n| |I d H  W d | _ d S W d | _ d S W d | _ d S d | _ w rK   )rH  r   r   r   is_load_local_packet_read_load_local_packet_read_result_packetri   first_packetrE   rE   rI   r     s   

zMySQLResult.readc                    s   d| _ | j I d H }| r| | d| _ d | _d S | r1| |I d H  d| _ d | _d S | | _| 	 I d H  d| _
d S )NTFl    )r6  rH  r   r   r   r  r  read_length_encoded_integerr  _get_descriptionsr   r  rE   rE   rI   rF    s   




z!MySQLResult.init_unbuffered_queryc                 C   s<   t |}|j| _|j| _|j| _|j| _|j| _|j| _d S rK   )r!   r   rJ  r   r  r  rS  )ri   r  	ok_packetrE   rE   rI   r     s   zMySQLResult._read_ok_packetc                    s|   t |}t|j| j}z	| I d H  W n ty%   | j I d H   w | j I d H }| s7tdd| 	| d S )Nr   zCommands Out of Sync)
r"   LoadLocalFilefilenamerH  r   r  r   r   r   r   )ri   r  load_packetsenderr  rE   rE   rI   r    s   
z#MySQLResult._read_load_local_packetc                 C   s(   |  rt|}|j| _|j| _dS dS )NTF)is_eof_packetr    r  rS  )ri   r@  
eof_packetrE   rE   rI   _check_packet_is_eof  s   z MySQLResult._check_packet_is_eofc                    s,   |  | _|  I d H  |  I d H  d S rK   )r  r  r  _read_rowdata_packetr  rE   rE   rI   r    s   
zMySQLResult._read_result_packetc                    sX   | j sd S | j I d H }| |rd| _ d | _d | _d S | |}d| _|f| _|S )NFr#   )r6  rH  r   r  r   _read_row_from_packetr   )ri   r@  rowrE   rE   rI   _read_rowdata_packet_unbuffered  s   

z+MySQLResult._read_rowdata_packet_unbufferedc              
      s   | j r@z
| j I d H }W n! ty/ } z|jd dv r*d| _ d | _W Y d }~d S  d }~ww | |r;d| _ d | _| j sd S d S )Nr   )i  i  F)r6  rH  r   r   rM   r  )ri   r@  r  rE   rE   rI   rR    s    
z$MySQLResult._finish_unbuffered_queryc                    sT   g }	 | j  I dH }| |rd| _ n	|| | qt|| _t|| _dS )z:Read a rowdata packet for each data row in the result set.TN)	rH  r   r  appendr  r   r   tupler   )ri   r   r@  rE   rE   rI   r    s   

z MySQLResult._read_rowdata_packetc              	   C   sx   g }| j D ]2\}}z| }W n ty   Y  t|S w |d ur2|d ur*||}|d ur2||}|| qt|S rK   )
convertersread_length_coded_string
IndexErrorr  r  r  )ri   r@  r  r   	converterr*  rE   rE   rI   r    s   
z!MySQLResult._read_row_from_packetc           
         s   g | _ g | _| jj}| jj}g }t| jD ]N}| jtI dH }| j 	| |	|
  |j}|rM|tjkr;|}n|tv rJ|jdkrGd}n|}nd}nd}| jj|}|tu r\d}| j	||f q| j I dH }	|	 suJ dt|| _
dS )z>Read a column descriptor packet for each column in the result.N?   rd  zProtocol error, expecting EOF)fieldsr  rH  r8   r   ranger  r   r   r  r  	type_coder	   JSONr   	charsetnrr   r   r   r  r  )
ri   r8   conn_encodingr  r  field
field_typer   r  r  rE   rE   rI   r    s:   


zMySQLResult._get_descriptionsN)rr   rs   rt   rh   r   rF  r   r  r  r  r  rR  r  r  r  rE   rE   rE   rI   r   {  s    	r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
r  c                 C   s$   || _ || _|j| _d | _d | _d S rK   )r  rH  rA   r   _file_object	_executor)ri   r  rH  rE   rE   rI   rh   K  s
   
zLoadLocalFile.__init__c                    s$    fdd} j  j| j}|S )Nc              
      sD   z	t | d _W d S  ty! } zd|  d}td||d }~ww )NrbzCan't find file 'r   i  )openr  r  r   )r  r  rE  rn   rE   rI   openerT  s   z(LoadLocalFile._open_file.<locals>.opener)r   run_in_executorr  r  )ri   r  r   rE   rn   rI   
_open_fileR  s   zLoadLocalFile._open_filec                    s"    fdd} j  j||}|S )Nc              
      sn   z j | }|s j   d  _ W |S W |S  ty6 } z j   d  _ d j }td||d }~ww )NzError reading file i   )r  r   r   r  r  r   )rV  chunkr  rE  rn   rE   rI   freader`  s   
	
z)LoadLocalFile._file_read.<locals>.freader)r   r  r  )ri   rV  r  r   rE   rn   rI   
_file_read^  s   zLoadLocalFile._file_readc              	      s   | j   | j }zGz0|  I dH  | j t}	 | |I dH }|s$n|| qW d   n1 s4w   Y  W n tjyH   | j 	   w W |d dS |d w )z3Send data packets from the local file to the serverNTr,  )
rH  r   r  r  r   r  r+  rV   r1  r2  )ri   rO   rV  r  rE   rE   rI   r   r  s,   


zLoadLocalFile.send_dataN)rr   rs   rt   rh   r  r  r   rE   rE   rE   rI   r  J  s
    r  )NNrK   )DrV   r   r|   r   r   rP  r   getpass	functoolsr   pymysql.charsetr   r   pymysql.constantsr   r   r   r   r	   pymysql.convertersr
   r   r   r   r   r   pymysql.errr   r   r   r   r   r   r   r   r   r   pymysql.connectionsr   r   r   r   r   r   r    r!   r"   r   r$   utilsr%   r&   r'   r(   logr)   getuserr   r  rJ   rF   rb   re   StreamReaderrY   rL   r   r  rE   rE   rE   rI   <module>   st    0


         P