3 $c3@sddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z ddl m Z mZmZmZmZddlmZddlmZddlmZdd lmZmZmZmZmZmZdd lmZmZyddl Z d Z!Wne"k rdZ d Z!YnXyddl#Z#e#j$Z%[#Wne"e&fk r&dZ%YnXd Z'ej(ej)ej*ej+ej,ej-ej.ej/ej0h Z1d Z2dZ3ddZ4ddZ5GdddZ6GdddZ7GdddZ8dS)N)_auth)charset_by_name charset_by_id)CLIENTCOMMANDCR FIELD_TYPE SERVER_STATUS) converters)Cursor)Parser) dump_packet MysqlPacketFieldDescriptorPacketOKPacketWrapperEOFPacketWrapperLoadLocalPacketWrapper)errVERSION_STRINGTFZutf8mb4cCstjd|ddS)NzZ$d?d@Z%djdAdBZ&dCdDZ'e(fdEdFZ)dGdHZ*dIdJZ+dkdKdLZ,dMdNZ-dOdPZ.dQdRZ/dSdTZ0dUdVZ1dWdXZ2dYdZZ3d[d\Z4d]d^Z5d_d`Z6dadbZ7e8j9Z9e8j:Z:e8j;Z;e8jZ>e8j?Z?e8j@Z@e8jAZAe8jBZBdS)l 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 `_ in the specification. NFrT r i)&userpasswordhostdatabase unix_socketportcharsetsql_moderead_default_fileconv use_unicode client_flag cursorclass init_commandconnect_timeoutread_default_group autocommit local_infilemax_allowed_packet defer_connectauth_plugin_map read_timeout write_timeout bind_address binary_prefix program_nameserver_public_keysslssl_cassl_cert ssl_disabledssl_keyssl_verify_certssl_verify_identitycompress named_pipepasswddbc&*s|&dk r|dkr|&}|%dk r&| r&|%}|#s.|$r6tdt||_|jrP| tjO} rp| rptjjdrld} nd} | r@s~dtj t j j | fdd}'|'d|}|'d |}|'d |}|'d |}|'d |}t |'d |}|'d|}|'d|}|si}t|tr@x0d+D](}(|'d|(|j|(})|)r|)||(<qWd|_|s|sj|sj| sj|!sj|"r|t|"|!dk r|!ndd}|dk r||d<| dk r| |d<|rtstdd|_| tjO} |j||_|pd|_|pd|_t|jt k r td|pt|_|p d|_t|jtr@|jjd|_||_||_ ||_!d|kofd knsvtd!|p~d|_"|dk r|dkrtd"||_#|dk r|dkrtd#||_$|pt%|_&| |_'t(|j&j)|_)| tj*O} |jr| tj+O} | |_,| |_-d|_.d|_/d$|_0||_1| dkr6t2j3} d%d&| j4D|_5d'd&| j4D|_6||_7||_8||_9|pxi|_:||_;||_d)|_?|r||j?d*<|rd|_@n|jAdS),Nz3compress and named_pipe arguments are not supportedwinz c:\my.iniz /etc/my.cnfclientc s.|r|Sy j|Stk r(|SXdS)N)get Exception)keyarg)cfgr;rr_configs  z$Connection.__init__.._configr,r-r.r/socketr1z bind-addresszdefault-character-setcacapathcertrVcipherzssl-F)r[check_hostname verify_modezssl module not foundT localhosti zport should be of type intlatin1ri3z+connect_timeout should be >0 and <=31536000zread_timeout should be > 0zwrite_timeout should be > 0z Not connectedcSs"i|]\}}t|tk r||qSr)typeint).0kvrrr Lsz'Connection.__init__..cSs"i|]\}}t|tkr||qSr)rdre)rfrgrhrrrriMsZpymysql)Z _client_name_pidZ_client_versionrE)r[r\r]rVr^)BNotImplementedErrorbool _local_infilerZ LOCAL_FILESsysplatform startswithr readospath expanduserre isinstancedictrTrG SSL_ENABLEDSSL_create_ssl_ctxctxr.r1rdr% DEFAULT_USERr,r-strencoderQr0rCr: _read_timeout_write_timeoutDEFAULT_CHARSETr2r6rencodingZ CAPABILITIESCONNECT_WITH_DBr7r8_result_affected_rows host_infoautocommit_moder Z conversionsitemsencodersdecodersr3r9r>_auth_plugin_map_binary_prefixrFgetpidr_connect_attrs_sockconnect)*selfr,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrYrVvaluer)rXr;r__init__s*                              zConnection.__init__cCs|S)Nr)rrrr __enter__cszConnection.__enter__cGs~|jdS)N)close)rexc_inforrr__exit__fszConnection.__exit__cCsRt|tjr|S|jd}|jd}|dko2|dk}tj||d}| oR|jdd|_|jd}|dkr||rrtjntj|_nxt|t r|rtjntj|_nZt|t r|j }|dkrtj|_n6|d krtj |_n$|dkrtj|_n|rtjntj|_d|kr|j |d|jddd|kr.|j|d|jtjO_|jtjO_|S)Nr[r\)cafiler\r_Tr`none0falsenooptionalrequired1trueyesr]rV)keyfiler^)rrrr)rrrr)rurG SSLContextrTcreate_default_contextr_ CERT_NONE CERT_REQUIREDr`rlr|lower CERT_OPTIONALload_cert_chain set_ciphersoptions OP_NO_SSLv2 OP_NO_SSLv3)rZsslpr[r\ZhasnocarzZverify_mode_valuerrrryjs8           zConnection._create_ssl_ctxcCsl|jrtjdd|_|jdkr$dStjddtj}z(y|j|Wnt k rXYnXWd|j XdS)z Send the quit message and close the socket. See `Connection.close() `_ in the specification. :raise Error: If the connection is already closed. zAlready closedTNz`_ in the specification. ZCOMMITN)rrrr)rrrrcommitszConnection.commitcCs|jtjd|jdS)z Roll back the current transaction. See `Connection.rollback() `_ in the specification. ZROLLBACKN)rrrr)rrrrrollbackszConnection.rollbackcCs$|jtjdt|}|j|jS)z%Send the "SHOW WARNINGS" SQL command.z SHOW WARNINGS)rrr MySQLResultrqrows)rresultrrr show_warningsszConnection.show_warningscCs|jtj||jdS)zI Set current db. :param db: The name of the db. N)rrZ COM_INIT_DBr)rrQrrr select_dbszConnection.select_dbcCsXt|trd|j|dSt|ttfrF|j|}|jrBd|}|Stj||j |dS)z}Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. '_binary)mapping) rur| escape_stringr& bytearray _quote_bytesrr Z escape_itemr2)robjrretrrrrs  zConnection.escapecCs|j||jS)zjAlias for escape() Non-standard, for internal use; do not use this in your applications. )rr)rrrrrliteralszConnection.literalcCs"|jtj@r|jddStj|S)Nrz'')rr "SERVER_STATUS_NO_BACKSLASH_ESCAPESreplacer r)rsrrrrs  zConnection.escape_stringcCs0|jtj@r&d|jddjddfStj|S)Nz'%s''s''asciisurrogateescape)rr rrdecoder Z escape_bytes)rrrrrr s zConnection._quote_bytescCs|r ||S|j|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. )r8)rcursorrrrrszConnection.cursorcCs:t|tr|j|jd}|jtj||j|d|_|jS)Nr) unbuffered) rur|r}rrrr_read_query_resultr)rsqlrrrrquerys  zConnection.querycCs|j|d|_|jS)N)r)rr)rrrrr next_result'szConnection.next_resultcCs|jS)N)r)rrrr affected_rows+szConnection.affected_rowscCs"tjd|}|jtj||jS)Nz}||jkrl|j|dkrXtjtj dtj d||jf|jdd|_|j|}t rt |||7}|d krq|t krPqW|t||j} | jr|jd k r|jjd krd |j_| 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. ztk r\}z"|jtjtj d|fWYdd}~XnXdS)NzMySQL server has gone away (%r)) rrrsendallrrrrrZCR_SERVER_GONE_ERROR)rrrrrrrszConnection._write_bytesc Csjd|_|rs                      z"Connection._request_authenticationc Cs0|j|}|rNy |j|Stk rL|dkrHtjdd|t|fYnX|dkrbtj||S|dkrvtj||S|dkrtj |j |j }n~|dkrtj |j |j }n`|dkrtj |j |j d }n>|d kr|j d }n(|dkr|}x|j}|d @d k}|d @d k}|j } | dkr@|j|j d n|rd} y|j|| } |j| d WnVtk rtjdd||fYn.tk rtjdd||| | fYnXntjdd||f|j}|j|js|rPqW|Stjdd||j||j}|j|S)Nsdialogi zGAuthentication plugin '%s' not loaded: - %r missing authenticate methodscaching_sha2_passwordssha256_passwordsmysql_native_passwordsclient_ed25519smysql_old_passwordr!smysql_clear_passwordrrs 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_handlerZ authenticateAttributeErrorrrrdrr1r2r*r-Zread_allZed25519_passwordr0r-rprompt TypeErrorrZ check_errorr) rr3r4handlerrrflagZecholastr8resprrrr/s|             zConnection._process_authc Csr|jj|}| r.t|tr.|jj|jd}|rjy ||}Wqntk rftjdd||fYqnXnd}|S)Nri zXAuthentication plugin '%s' not loaded: - %r cannot be constructed with connection object)rrTrur&rr9rr)rr3Z plugin_classr:rrrr6s  z#Connection._get_auth_plugin_handlercCs |jdS)Nr)server_thread_id)rrrrrszConnection.thread_idcCs|jS)N)r2)rrrrcharacter_set_nameszConnection.character_set_namecCs|jS)N)r)rrrr get_host_infoszConnection.get_host_infocCs|jS)N)protocol_version)rrrrget_proto_infoszConnection.get_proto_infoc Cs d}|j}|j}|||_|d7}|jd|}|||jd|_|d}tjd|||d|_|d7}|||d|_ |d7}tjd |||d d|_ |d 7}t ||d krftjd |||d \}}}}|d 7}||_ yt |j|_Wntk rd|_YnX||_tr6td ||j |d>O_ trXtd|td|d}|d7}t |||kr|j ||||7_ ||7}|d7}|j tj@rt ||kr|jd|}|dkr||djd|_n|||jd|_dS)Nrrr!rczr+r'rZserver_languagernameZserver_charsetKeyErrorrrrmaxrr,r)) rr'rrZ server_endlangstatZcap_hZsalt_lenrrrrsN        z"Connection._get_server_informationcCs|jS)N)r$)rrrrget_server_info^szConnection.get_server_infoi@i)N)N)F)F)T)N)F)C__name__ __module__ __qualname____doc__rr)rrr rrrryrpropertyrr__del__r<rrrrrrrrrrrrrrrrrrrrrrrr rrrrrr/r6rr?r@rBrrLrWarningrrZ DatabaseErrorZ DataErrorrZIntegrityErrorr ZProgrammingErrorZNotSupportedErrorrrrrr)\sB         L - +qOAr)c@steZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZdS)rcCsF||_d|_d|_d|_d|_d|_d|_d|_d|_d|_ d|_ dS)z. :type connection: Connection NrF) rrrr warning_countmessage field_count descriptionrrr)rrrrrrnszMySQLResult.__init__cCs|jr|jdS)N)rr)rrrrrR~szMySQLResult.__del__c CsNz@|jj}|jr |j|n|jr4|j|n |j|Wdd|_XdS)N)rrrris_load_local_packet_read_load_local_packet_read_result_packet)r first_packetrrrrqs   zMySQLResult.readcCsld|_|jj}|jr0|j|d|_d|_n8|jrP|j|d|_d|_n|j|_|j d|_ dS)zw :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: TFNl) rrrrrrXrYread_length_encoded_integerrV_get_descriptionsr)rr[rrrrs    z!MySQLResult.init_unbuffered_querycCs<t|}|j|_|j|_|j|_|j|_|j|_|j|_dS)N)rrrrrTrUr)rr[ ok_packetrrrrszMySQLResult._read_ok_packetc Csx|jjstdt|}t|j|j}y |jWn|jjYnX|jj}|jsjt j dd|j |dS)NzF**WARN**: Received LOAD_LOCAL packet but local_infile option is false.izCommands Out of Sync) rrm RuntimeErrorr LoadLocalFilefilenamerrrrrr)rr[Z load_packetZsenderr^rrrrYs    z#MySQLResult._read_load_local_packetcCs(|js dSt|}|j|_|j|_dS)NFT) is_eof_packetrrTr)rrZwprrr_check_packet_is_eofs z MySQLResult._check_packet_is_eofcCs|j|_|j|jdS)N)r\rVr]_read_rowdata_packet)rr[rrrrZs zMySQLResult._read_result_packetcCsP|js dS|jj}|j|r4d|_d|_d|_dS|j|}d|_|f|_|S)NFr)rrrrcr_read_row_from_packetr)rrrowrrr_read_rowdata_packet_unbuffereds   z+MySQLResult._read_rowdata_packet_unbufferedcCs0x*|jr*|jj}|j|rd|_d|_qWdS)NF)rrrrc)rrrrrrs   z$MySQLResult._finish_unbuffered_querycCsNg}x0|jj}|j|r"d|_P|j|j|qWt||_t||_dS)z:Read a rowdata packet for each data row in the result set.N) rrrcappendrerrtupler)rrrrrrrds   z MySQLResult._read_rowdata_packetc Csg}xx|jD]n\}}y |j}Wntk r6PYnX|dk rp|dk rR|j|}tr`td||dk rp||}|j|q Wt|S)NzDEBUG: DATA = )r Zread_length_coded_string IndexErrorrrrrhri)rrrfr converterrrrrres   z!MySQLResult._read_row_from_packetc Csg|_g|_|jj}|jj}g}xt|jD]}|jjt}|jj ||j |j |j }|r|t j krp|}q|tkr|jdkrd}q|}qd}nd}|jjj|}|tjkrd}trtd|d||jj ||fq,W|jj} | jstdt||_ dS)z>Read a column descriptor packet for each column in the result.?Nrz DEBUG: field=z , converter=zProtocol error, expecting EOF)fieldsr rr6rrangerVrrrhrWZ type_coder ZJSON TEXT_TYPESZ charsetnrrrTZthroughrrrbAssertionErrorri) rr6Z conn_encodingrWr'fieldZ field_typerrkZ eof_packetrrrr]s8      zMySQLResult._get_descriptionsN)rMrNrOrrRrqrrrYrcrZrgrrdrer]rrrrrms     rc@seZdZddZddZdS)r`cCs||_||_dS)N)rar)rrarrrrr?szLoadLocalFile.__init__cCs|jjstjdd|j}zxyHt|jd2}t|jd }x|j|}|sJP|j |q:WWdQRXWn*t k rtj dd|jd YnXWd|j d XdS) z3Send data packets from the local file to the serverrr*rr iNizCan't find file 'rrbi@) rrrrrrarr>rqrrr)rconn open_filerchunkrrrrCs    zLoadLocalFile.send_dataN)rMrNrOrrrrrrr`>sr`ii)9rrrrZrrnrrr*rr2rr constantsrrrr r r Zcursorsr Z optionfiler protocolrrrrrrrrrGrw ImportErrorgetpassgetuserr{rHrZBITZBLOBZ LONG_BLOBZ MEDIUM_BLOBSTRINGZ TINY_BLOBZ VAR_STRINGZVARCHARZGEOMETRYrorrrr(r)rr`rrrrsh       R