o
    c_3                  	   @   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mZ ddl	m
Z
mZ ddl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 dd
lmZmZ zd dl Z dZ!W n e"yw   dZ dZ!Y nw zd dl#Z#e#$ Z%[#W n e"e&fy   dZ%Y nw dZ'ej(ej)ej*ej+ej,ej-ej.ej/ej0h	Z1dZ2dZ3dd Z4dd Z5G dd dZ6G dd dZ7G dd dZ8dS )    N   )_auth)charset_by_namecharset_by_id)CLIENTCOMMANDCR
FIELD_TYPESERVER_STATUS)
converters)Cursor)Parser)dump_packetMysqlPacketFieldDescriptorPacketOKPacketWrapperEOFPacketWrapperLoadLocalPacketWrapper)errVERSION_STRINGTFutf8mb4 c                 C   s   t d| d d S )N<I   )structpack)n r   5/usr/lib/python3/dist-packages/pymysql/connections.py_pack_int24C   s   r   c                 C   s   | dk r
t d|  | dk rt| gS | dk rdtd|  S | dk r/dtd	| d d
  S | dk r;dtd|  S t d| df )Nr   zFEncoding %d is less than 0 - no representation in LengthEncodedInteger   i      <H      r   r   l               z<QzIEncoding %x is larger than %x - no representation in LengthEncodedInteger)
ValueErrorbytesr   r   )ir   r   r   _lenenc_intH   s"   
r)   c                '   @   s&  e Zd ZdZdZdZdZdZddddddddddddedddddddddddddddddddddddddd	&d
dZ	dd Z
dd Zdd Zdd Zedd Zdd Ze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dbd*d+Zd,d- Zd.d/ Zd0d1 Zdbd2d3Zdcd4d5Z dcd6d7Z!d8d9 Z"d:d; Z#ddd<d=Z$d>d? Z%dbd@dAZ&dBdC Z'e(fdDdEZ)dFdG Z*dHdI Z+dcdJdKZ,dLdM Z-dNdO Z.dPdQ Z/dRdS Z0dTdU Z1dVdW Z2dXdY Z3dZd[ Z4d\d] Z5d^d_ Z6d`da Z7e8j9Z9e8j:Z:e8j;Z;e8j<Z<e8j=Z=e8j>Z>e8j?Z?e8j@Z@e8jAZAe8jBZBdS )e
ConnectionaP  
    Representation of a socket with a mysql server.

    The proper way to get an instance of this class is to call
    connect().

    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 database: Database to use, None to not use a particular one.
    :param port: MySQL port to use, default is usually OK. (default: 3306)
    :param bind_address: When the client has multiple network interfaces, specify
        the interface from which to connect to the host. Argument can be
        a hostname or an IP address.
    :param unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
    :param read_timeout: The timeout for reading from the connection in seconds (default: None - no timeout)
    :param write_timeout: The timeout for writing to the connection in seconds (default: None - no timeout)
    :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:
        Conversion dictionary to use instead of the default one.
        This is used to provide custom marshalling and unmarshalling of types.
        See converters.
    :param use_unicode:
        Whether or not to default to unicode strings.
        This option defaults to true.
    :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.
        (default: 10, min: 1, max: 31536000)
    :param ssl:
        A dict of arguments similar to mysql_ssl_set()'s parameters.
    :param ssl_ca: Path to the file that contains a PEM-formatted CA certificate
    :param ssl_cert: Path to the file that contains a PEM-formatted client certificate
    :param ssl_disabled: A boolean value that disables usage of TLS
    :param ssl_key: Path to the file that contains a PEM-formatted private key for the client certificate
    :param ssl_verify_cert: Set to true to check the validity of server certificates
    :param ssl_verify_identity: Set to true to check the server's identity
    :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 max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
        Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
    :param defer_connect: Don't explicitly connect on construction - wait for connect call.
        (default: False)
    :param auth_plugin_map: A dict of plugin names to a class that processes that plugin.
        The class will take the Connection object as the argument to the constructor.
        The class needs an authenticate method taking an authentication packet as
        an argument.  For the dialog plugin, a prompt(echo, prompt) method can be used
        (if no authenticate method) for returning a string from the user. (experimental)
    :param server_public_key: SHA256 authentication plugin public key value. (default: None)
    :param binary_prefix: Add _binary prefix on bytes and bytearray. (default: False)
    :param compress: Not supported
    :param named_pipe: Not supported
    :param db: **DEPRECATED** Alias for database.
    :param passwd: **DEPRECATED** Alias for password.

    See `Connection <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_ in the
    specification.
    N Fr   T
   r#   )&userpasswordhostdatabaseunix_socketportcharsetsql_moderead_default_fileconvuse_unicodeclient_flagcursorclassinit_commandconnect_timeoutread_default_group
autocommitlocal_infilemax_allowed_packetdefer_connectauth_plugin_mapread_timeoutwrite_timeoutbind_addressbinary_prefixprogram_nameserver_public_keysslssl_cassl_certssl_disabledssl_keyssl_verify_certssl_verify_identitycompress
named_pipepasswddbc       &   *         s  |&d ur
|d u r
|&}|%d ur|s|%}|#s|$rt dt|| _| jr'|tjO }r6|	s6tjdr4d}	nd}	|	rs<dt   	t
j|	  fdd}'|'d|}|'d	|}|'d
|}|'d|}|'d|}t|'d|}|'d|}|'d|}|s}i }t|trdD ]}(|'d|( ||(})|)r|)||(< qd| _|s|s|s| s|!s|"r|t|"|!d ur|!ndd}|d ur||d< | d ur| |d< |rtst dd| _|tjO }| || _|pd| _|pd| _t| jturtd|pt| _|pd| _t| jtr| jd| _|| _|| _ || _!d|  k rdks$td td|p(d | _"|d ur8|dkr8td || _#|d urI|dkrItd!|| _$|pPt%| _&|| _'t(| j&j)| _)|tj*O }| jrj|tj+O }|| _,|| _-d | _.d| _/d"| _0|| _1|
d u rt2j3}
d#d$ |
4 D | _5d%d$ |
4 D | _6|| _7|| _8|| _9|pi | _:|| _;|| _<d&tt
= t>d'| _?|r|| j?d(< |rd | _@d S | A  d S ))Nz3compress and named_pipe arguments are not supportedwinz	c:\my.iniz/etc/my.cnfclientc                    s.   |r|S z  | W S  ty   | Y S w N)get	Exception)keyargcfgr<   r   r   _config   s   z$Connection.__init__.<locals>._configr-   r.   r/   r0   socketr2   zbind-addresszdefault-character-set)cacapathcertrX   cipherzssl-F)r^   check_hostnameverify_moder`   rX   zssl module not foundT	localhosti  zport should be of type int    latin1r   i3z+connect_timeout should be >0 and <=31536000zread_timeout should be > 0zwrite_timeout should be > 0zNot connectedc                 S   s"   i | ]\}}t |tur||qS r   typeint.0kvr   r   r   
<dictcomp>L     " z'Connection.__init__.<locals>.<dictcomp>c                 S   s"   i | ]\}}t |tu r||qS r   rg   rj   r   r   r   rn   M  ro   pymysql)_client_name_pid_client_versionrF   )BNotImplementedErrorbool_local_infiler   LOCAL_FILESsysplatform
startswithr   readospath
expanduserri   
isinstancedictrV   rH   SSL_ENABLEDSSL_create_ssl_ctxctxr/   r2   rh   r&   DEFAULT_USERr-   r.   strencoderR   r1   rD   r;   _read_timeout_write_timeoutDEFAULT_CHARSETr3   r7   r   encodingCAPABILITIESCONNECT_WITH_DBr8   r9   _result_affected_rows	host_infoautocommit_moder   conversionsitemsencodersdecodersr4   r:   r?   _auth_plugin_map_binary_prefixrG   getpidr   _connect_attrs_sockconnect)*selfr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   r\   rX   valuer   rZ   r   __init__   s   *




















zConnection.__init__c                 C   s   | S rU   r   r   r   r   r   	__enter__c  s   zConnection.__enter__c                 G   s   ~|    d S rU   )close)r   exc_infor   r   r   __exit__f  s   zConnection.__exit__c                 C   sN  t |tjr|S |d}|d}|d u o|d u }tj||d}| o)|dd|_|d}|d u r>|r9tjntj|_n<t |t	rM|rHtjntj|_n-t |t
rV| }|dv r_tj|_n|dkrhtj|_n|d	v rqtj|_n	|rvtjntj|_d
|v r|j|d
 |dd d|v r||d  | jtjO  _| jtjO  _|S )Nr^   r_   )cafiler_   rb   Trc   )none0falsenooptional)required1trueyesr`   rX   )keyfilera   )r   rH   
SSLContextrV   create_default_contextrb   	CERT_NONECERT_REQUIREDrc   ru   r   lowerCERT_OPTIONALload_cert_chainset_ciphersoptionsOP_NO_SSLv2OP_NO_SSLv3)r   sslpr^   r_   hasnocar   verify_mode_valuer   r   r   r   j  s8   







zConnection._create_ssl_ctxc                 C   s~   | j rtdd| _ | jdu rdS tddtj}zz| | W n	 t	y+   Y nw W | 
  dS W | 
  dS | 
  w )z
        Send the quit message and close the socket.

        See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
        in the specification.

        :raise Error: If the connection is already closed.
        Already closedTN<iBr   )_closedr   Errorr   r   r   r   COM_QUIT_write_bytesrW   _force_close)r   	send_datar   r   r   r     s   	

zConnection.closec                 C   s
   | j duS )z%Return True if the connection is openN)r   r   r   r   r   open  s   
zConnection.openc                 C   s.   | j rz| j   W n   Y d| _ d| _dS )z%Close connection without QUIT messageN)r   r   _rfiler   r   r   r   r     s   
zConnection._force_closec                 C   s*   t || _|  }||kr|   d S d S rU   )ru   r   get_autocommit_send_autocommit_mode)r   r   currentr   r   r   r=     s
   
zConnection.autocommitc                 C   s   t | jtj@ S rU   )ru   server_statusr
   SERVER_STATUS_AUTOCOMMITr   r   r   r   r     s   zConnection.get_autocommitc                 C   s0   |   }| stddt|}|j| _|S )N  zCommand Out of Sync)_read_packetis_ok_packetr   OperationalErrorr   r   )r   pktokr   r   r   _read_ok_packet  s   zConnection._read_ok_packetc                 C   s&   |  tjd| | j  |   dS )z2Set whether or not to commit after every execute()zSET AUTOCOMMIT = %sN)_execute_commandr   	COM_QUERYescaper   r   r   r   r   r   r     s   z Connection._send_autocommit_modec                 C      |  tjd |   dS )zBegin transaction.BEGINNr   r   r   r   r   r   r   r   begin  s   zConnection.beginc                 C   r   )z
        Commit changes to stable storage.

        See `Connection.commit() <https://www.python.org/dev/peps/pep-0249/#commit>`_
        in the specification.
        COMMITNr   r   r   r   r   commit     zConnection.commitc                 C   r   )z
        Roll back the current transaction.

        See `Connection.rollback() <https://www.python.org/dev/peps/pep-0249/#rollback>`_
        in the specification.
        ROLLBACKNr   r   r   r   r   rollback  r   zConnection.rollbackc                 C   s$   |  tjd t| }|  |jS )z%Send the "SHOW WARNINGS" SQL command.zSHOW WARNINGS)r   r   r   MySQLResultr{   rows)r   resultr   r   r   show_warnings  s   zConnection.show_warningsc                 C   s   |  tj| |   dS )zI
        Set current db.

        :param db: The name of the db.
        N)r   r   COM_INIT_DBr   )r   rR   r   r   r   	select_db  s   zConnection.select_dbc                 C   sX   t |trd| | d S t |ttfr#| |}| jr!d| }|S tj|| j	|dS )z}Escape whatever value you pass to it.

        Non-standard, for internal use; do not use this in your applications.
        '_binary)mapping)
r   r   escape_stringr'   	bytearray_quote_bytesr   r   escape_itemr3   )r   objr   retr   r   r   r     s   

zConnection.escapec                 C   s   |  || jS )zjAlias for escape()

        Non-standard, for internal use; do not use this in your applications.
        )r   r   )r   r   r   r   r   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   r   r   sr   r   r   r     s   
zConnection.escape_stringc                 C   s0   | j tj@ rd|ddddf S t|S )Nz'%s'   's   ''asciisurrogateescape)r   r
   r   r   decoder   escape_bytesr   r   r   r   r     s   
zConnection._quote_bytesc                 C   s   |r|| S |  | S )a	  
        Create a new cursor to execute queries with.

        :param cursor: The type of cursor to create; one of :py:class:`Cursor`,
            :py:class:`SSCursor`, :py:class:`DictCursor`, or :py:class:`SSDictCursor`.
            None means use Cursor.
        )r9   )r   cursorr   r   r   r     s   
zConnection.cursorc                 C   s:   t |tr|| jd}| tj| | j|d| _| jS )Nr   
unbuffered)	r   r   r   r   r   r   r   _read_query_resultr   )r   sqlr   r   r   r   query  s
   
zConnection.queryc                 C   s   | j |d| _| jS )Nr   )r   r   )r   r   r   r   r   next_result'  s   zConnection.next_resultc                 C      | j S rU   )r   r   r   r   r   affected_rows+     zConnection.affected_rowsc                 C   s"   t d|}| tj| |  S )Nr   )r   r   r   r   COM_PROCESS_KILLr   )r   	thread_idrY   r   r   r   kill.  s   zConnection.killc                 C   sp   | j du r|r|   d}ntdz| tjd |   W dS  ty7   |r6|   | 	d Y dS  w )z
        Check if the server is alive.

        :param reconnect: If the connection is closed, reconnect.
        :raise Error: If the connection is closed and reconnect=False.
        NFr   r+   )
r   r   r   r   r   r   COM_PINGr   rW   ping)r   	reconnectr   r   r   r  3  s   

zConnection.pingc                 C   s:   t |j}| tjd| |  |   || _|| _d S )NzSET NAMES %s)r   r   r   r   r   r   r   r3   )r   r3   r   r   r   r   set_charsetJ  s
   

zConnection.set_charsetc              
   C   sD  d| _ z|d u r| jr,ttjtj}|| j || j d| _d| _	t
r+td n]i }| jd ur:| jdf|d< 	 ztj| j| jf| jfi |}W n ttfyg } z|jtjkrbW Y d }~q: d }~ww d| j| jf | _t
rwtd |tjtjd	 |tjtjd	 |d  || _|d
| _d| _|   |   | jd ur|   }|!d| jf | j"d ur|   }|!| j" |#  | $  | j%d ur| &| j% W d S W d S  t'y! } z:d | _|d urz|#  W n   Y t(|tttj)frt*+dd| j|f }||_,t-. |_-t
rt|j- | d }~ww )NFzLocalhost via UNIX socketTzconnected using unix_socketr   source_addresszsocket %s:%dzconnected using socketr   rbzSET sql_mode=%si  z(Can't connect to MySQL server on %r (%s))/r   r1   r]   AF_UNIXSOCK_STREAM
settimeoutr;   r   r   _secureDEBUGprintrD   create_connectionr/   r2   OSErrorIOErrorerrnoEINTR
setsockoptIPPROTO_TCPTCP_NODELAY
SOL_SOCKETSO_KEEPALIVEr   makefiler   _next_seq_id_get_server_information_request_authenticationr4   r   executer:   r   r   r   r=   BaseExceptionr   errorr   r   original_exception	traceback
format_exc)r   sockkwargsecexcr   r   r   r   S  s   






zConnection.connectc                 C   sF   t t|t| jg | }trt| | | | jd d | _dS )zvWrites an entire "mysql packet" in its entirety to the network
        adding its length and sequence number.
        r      N)r   lenr'   r  r  r   r   )r   payloaddatar   r   r   write_packet  s
   
zConnection.write_packetc           
      C   s   t  }	 | d}td|\}}}||d>  }|| jkr6|   |dkr,ttj	dt
d|| jf | jd d	 | _| |}trIt| ||7 }|d
krRq|tk rWnq|t|| j}	|	 rw| jdurs| jjdu rsd| j_|	  |	S )a!  Read an entire "mysql packet" in its entirety from the network
        and return a MysqlPacket type that represents the results.

        :raise OperationalError: If the connection to the MySQL server is lost.
        :raise InternalError: If the packet sequence number is wrong.
        T   z<HBB   r   ,Lost connection to MySQL server during queryz1Packet sequence number wrong - got %d expected %dr   r*  r   NF)r   _read_bytesr   unpackr  r   r   r   r   CR_SERVER_LOSTInternalErrorr  r   MAX_PACKET_LENr'   r   is_error_packetr   unbuffered_activeraise_for_error)
r   packet_typebuffpacket_headerbtrlbtrhpacket_numberbytes_to_read	recv_datapacketr   r   r   r     sB   


zConnection._read_packetc              
   C   s   | j | j 	 z| j|}W n3 ttfy8 } z|jtjkr&W Y d }~q| 	  t
tjd|f d }~w tyC   | 	   w t||k rU| 	  t
tjd|S )NTz1Lost connection to MySQL server during query (%s)r1  )r   r  r   r   r{   r  r  r  r  r   r   r   r   r4  r   r+  )r   	num_bytesr-  r'  r   r   r   r2    s0   zConnection._read_bytesc              
   C   sV   | j | j z	| j | W d S  ty* } z|   ttj	d|f d }~ww )NzMySQL server has gone away (%r))
r   r  r   sendallr  r   r   r   r   CR_SERVER_GONE_ERROR)r   r-  r'  r   r   r   r     s   zConnection._write_bytesc                 C   sb   d | _ |rz
t| }|  W n   d|_d |_ t| }|  || _ |jd ur.|j| _|jS NF)r   r   init_unbuffered_queryr8  
connectionr{   r   r   )r   r   r   r   r   r   r     s   
zConnection._read_query_resultc                 C   s   | j r| j jS dS Nr   )r   	insert_idr   r   r   r   rJ    s   zConnection.insert_idc                 C   s  | j s	tdd| jdur+| jjrtd | j  | jjr(| 	  | jjs d| _t
|tr6|| j}ttt|d }td||}||d|d   }| | tr[t| d| _|tk rddS ||d d }	 ttt|}| |d|  ||d }|s|tk rdS qm)z~
        :raise InterfaceError: If the connection is closed.
        :raise ValueError: If no username was specified.
        r   r+   Nz.Previous unbuffered result was left incompleter   r   )r   r   InterfaceErrorr   r8  warningswarn_finish_unbuffered_queryhas_nextr   r   r   r   r   minr6  r+  r   r   r   r  r   r  r.  )r   commandr   packet_sizepreluderB  r   r   r   r     s:   




zConnection._execute_commandc           
      C   s  t | jddd dkr|  jtjO  _| jd u rtdt| j	j
}t| jtr2| j| j| _td| jt|d}| jr_| jtj@ r_| | | jj| j| jd| _| jd	| _d
| _|| j d }d}d }| jdkrzd}t| j | j!}nN| jdkrd}t| j | j!}n>| jdkrd}| j rt"rt#d t$| j | j!}n%t"rt#d n| jdkrd}| jr| jtj@ r| j d }n| j rd}n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| _)|| j)d 7 }| jtj+@ r#||pdd 7 }| jtj,@ red}| j-. D ]'\}}|d}|tdt'|| 7 }|d}|tdt'|| 7 }q1|tdt'|| 7 }| | | / }	|	0 rt"rzt#d |	1  |	2 }| jtj+@ r|d ur| 3||	}	nAt4| j | j!d }| | | / }	n-|	5 rt"rt#d | jdkrt6| |	}	n| jdkrt7| |	}	nt89d| jt"rt#d d S d S )N.r   r      zDid not specify a usernamez<iIB23sre   )server_hostnamer
  T    r+   mysql_native_password   mysql_native_passwordcaching_sha2_password   caching_sha2_passwordzcaching_sha2: trying fast pathzcaching_sha2: empty passwordsha256_password   sha256_password   Butf-8zreceived auth switchzreceived extra dataz(Received extra packet for auth method %rzSucceed to auth):ri   server_versionsplitr8   r   MULTI_RESULTSr-   r&   r   r3   idr   r   r   r   r   r   r6  rH   server_capabilitiesr   r.  r   wrap_socketr   r/   r  r   r  _auth_plugin_namer   scramble_native_passwordr.   saltr  r  scramble_caching_sha2PLUGIN_AUTH_LENENC_CLIENT_DATAr)   r+  SECURE_CONNECTIONrR   r   PLUGIN_AUTHCONNECT_ATTRSr   r   r   is_auth_switch_request
read_uint8read_string_process_authscramble_old_passwordis_extra_auth_datacaching_sha2_password_authsha256_password_authr   r   )
r   
charset_id	data_initr-  authrespplugin_nameconnect_attrsrl   rm   auth_packetr   r   r   r  >  s   














z"Connection._request_authenticationc                 C   s  |  |}|r'z||W S  ty&   |dkr$tdd|t|f Y nw |dkr1t| |S |dkr;t| |S |dkrIt	| j
| }n|dkrWt| j
| }n|dkrgt| j
| d	 }n|d
krq| j
d	 }n|dkr|}	 | }|d@ dk}|d@ dk}| }	|	dkr| | j
d	  nA|rd}
z|||	}
| |
d	  W n- ty   tdd||f  ty   tdd|||
|	f w tdd||f |  }|  | s|r	 |S qxtdd| | | |  }|  |S )Ns   dialog  zGAuthentication plugin '%s' not loaded: - %r missing authenticate methodr[  r]  rY  s   client_ed25519s   mysql_old_passwordrW  s   mysql_clear_passwordT      r   s
   Password: z3no response - TypeError within plugin.prompt methodzAAuthentication plugin '%s' not loaded: - %r missing prompt methodi  zTAuthentication plugin '%s' %r didn't respond with string. Returned '%r' to prompt %rz.Authentication plugin '%s' (%r) not configuredz)Authentication plugin '%s' not configured)_get_auth_plugin_handlerauthenticateAttributeErrorr   r   rh   r   ru  rv  rh  r.   read_alled25519_passwordrs  rp  r.  prompt	TypeErrorr   check_errorr   )r   rz  r|  handlerr-  r   flagecholastr  respr   r   r   rr    s   


'
zConnection._process_authc              	   C   sj   | j |}|st|tr| j |d}|r1z|| }W |S  ty0   tdd||f w d }|S )Nr   r}  zXAuthentication plugin '%s' not loaded: - %r cannot be constructed with connection object)r   rV   r   r'   r   r  r   r   )r   rz  plugin_classr  r   r   r   r    s"   

z#Connection._get_auth_plugin_handlerc                 C   s
   | j d S rI  )server_thread_idr   r   r   r   r    s   
zConnection.thread_idc                 C   r   rU   )r3   r   r   r   r   character_set_name  r  zConnection.character_set_namec                 C   r   rU   )r   r   r   r   r   get_host_info  r  zConnection.get_host_infoc                 C   r   rU   )protocol_versionr   r   r   r   get_proto_info  r  zConnection.get_proto_infoc           	      C   s  d}|   }| }|| | _|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 || _trtd|  |  j
|d> O  _
trtd| 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   rW  rf   r   r/     	   r"   r  r~  z<BHHBzserver_status: %xr0  z	salt_len:   r,   r`  )r   get_all_datar  findr   ra  r   r3  r  ri  re  r+  server_languager   nameserver_charsetKeyErrorr   r  r  maxr   rm  rg  )	r   r(   rB  r-  
server_endlangstatcap_hsalt_lenr   r   r   r    sR   
 

z"Connection._get_server_informationc                 C   r   rU   )ra  r   r   r   r   get_server_info^  r  zConnection.get_server_inforU   )F)T)C__name__
__module____qualname____doc__r   rg  r   r  r   r   r   r   r   r   propertyr   r   __del__r=   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r.  r   r   r2  r   r   rJ  r   r  rr  r  r  r  r  r  r  r  r   Warningr   rK  DatabaseError	DataErrorr   IntegrityErrorr5  ProgrammingErrorNotSupportedErrorr   r   r   r   r*   \   s    C ? 




	


	

	L-

+qOA
r*   c                   @   st   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d ZdS )r   c                 C   sF   || _ d| _d| _d| _d| _d| _d| _d| _d| _d| _	d| _
dS )z.
        :type connection: Connection
        Nr   F)rH  r   rJ  r   warning_countmessagefield_countdescriptionr   rO  r8  )r   rH  r   r   r   r   n  s   
zMySQLResult.__init__c                 C   s   | j r	|   d S d S rU   )r8  rN  r   r   r   r   r  ~  s   zMySQLResult.__del__c                 C   sj   z0| j  }| r| | n| r| | n| | W d | _ d S W d | _ d S W d | _ d S d | _ w rU   )rH  r   r   r   is_load_local_packet_read_load_local_packet_read_result_packetr   first_packetr   r   r   r{     s   


zMySQLResult.readc                 C   sp   d| _ | j }| r| | d| _ d| _dS | r*| | d| _ d| _dS | | _| 	  d| _
dS )zw
        :raise OperationalError: If the connection to the MySQL server is lost.
        :raise InternalError:
        TFNl    )r8  rH  r   r   r   r  r  read_length_encoded_integerr  _get_descriptionsr   r  r   r   r   rG    s   






z!MySQLResult.init_unbuffered_queryc                 C   s<   t |}|j| _|j| _|j| _|j| _|j| _|j| _d S rU   )r   r   rJ  r   r  r  rO  )r   r  	ok_packetr   r   r   r     s   zMySQLResult._read_ok_packetc                 C   sr   | j jstdt|}t|j| j }z|  W n	   | j    | j  }| s2t	
dd| | d S )NzF**WARN**: Received LOAD_LOCAL packet but local_infile option is false.r   zCommands Out of Sync)rH  rv   RuntimeErrorr   LoadLocalFilefilenamer   r   r   r   r   r   )r   r  load_packetsenderr  r   r   r   r    s    

z#MySQLResult._read_load_local_packetc                 C   s(   |  sdS t|}|j| _|j| _dS )NFT)is_eof_packetr   r  rO  )r   rB  wpr   r   r   _check_packet_is_eof  s   z MySQLResult._check_packet_is_eofc                 C   s   |  | _|   |   d S rU   )r  r  r  _read_rowdata_packetr  r   r   r   r    s   
zMySQLResult._read_result_packetc                 C   sP   | j sd S | j }| |rd| _ d | _d | _d S | |}d| _|f| _|S )NFr   )r8  rH  r   r  r   _read_row_from_packetr   )r   rB  rowr   r   r   _read_rowdata_packet_unbuffered  s   


z+MySQLResult._read_rowdata_packet_unbufferedc                 C   s4   | j r| j }| |rd| _ d | _| j sd S d S rF  )r8  rH  r   r  )r   rB  r   r   r   rN    s   

z$MySQLResult._finish_unbuffered_queryc                 C   sL   g }	 | j  }| |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   )r   r   rB  r   r   r   r    s   


z MySQLResult._read_rowdata_packetc              	   C   s   g }| j D ]9\}}z| }W n ty   Y  t|S w |d ur9|d ur*||}tr1td| |d ur9||}|| qt|S )NzDEBUG: DATA = )r   read_length_coded_string
IndexErrorr   r  r  r  r  )r   rB  r  r   	converterr-  r   r   r   r    s"   	

z!MySQLResult._read_row_from_packetc           
      C   s  g | _ g | _| jj}| jj}g }t| jD ]X}| jt}| j 	| |	|
  |j}|rI|tjkr7|}n|tv rF|jdkrCd}n|}nd}nd}| jj|}|tju rYd}tretd| d|  | j	||f q| j }	|	 s{J dt|| _
dS )z>Read a column descriptor packet for each column in the result.?   Nr   zDEBUG: field=z, converter=zProtocol error, expecting EOF)fieldsr   rH  r7   r   ranger  r   r   r  r  	type_coder	   JSON
TEXT_TYPES	charsetnrr   rV   throughr  r  r  r  )
r   r7   conn_encodingr  r(   field
field_typer   r  
eof_packetr   r   r   r    s8   



zMySQLResult._get_descriptionsN)r  r  r  r   r  r{   rG  r   r  r  r  r  rN  r  r  r  r   r   r   r   r   m  s    	
r   c                   @   s   e Zd Zdd Zdd ZdS )r  c                 C   s   || _ || _d S rU   )r  rH  )r   r  rH  r   r   r   r   ?  s   
zLoadLocalFile.__init__c              	   C   s   | j js
tdd| j }zHz-t| jd}t|jd}	 ||}|s%n|	| qW d   n1 s5w   Y  W n t
yM   tdd| j d	w W |	d
 dS |	d
 w )z3Send data packets from the local file to the serverr   r+   r
  i @  TNi  zCan't find file 'r   re   )rH  r   r   rK  r   r  rP  r?   r{   r.  r  r   )r   conn	open_filerR  chunkr   r   r   r   C  s,   

	zLoadLocalFile.send_dataN)r  r  r  r   r   r   r   r   r   r  >  s    r  )9r  r|   r]   r   rx   r#  rL  r+   r   r3   r   r   	constantsr   r   r   r	   r
   r   cursorsr   
optionfiler   protocolr   r   r   r   r   r   r   r   rH   r   ImportErrorgetpassgetuserr   r  r  BITBLOB	LONG_BLOBMEDIUM_BLOBSTRING	TINY_BLOB
VAR_STRINGVARCHARGEOMETRYr  r   r6  r   r)   r*   r   r  r   r   r   r   <module>   sp             R