o {nh @sDddlmZddlmZmZmZmZmZmZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZddlmZmZddlmZmZmZmZmZddlmZdd lmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*dd lm+Z+m,Z,zddl-Z-dZ.Wn e/ydZ-dZ.Ynwz ddl0Z0e01Z2[0Wn e/e3fydZ2YnwdZ4ej5ddZ6erne6dkrdde7dDZ8ddZ9nddZ9eresddl:m;Z;ddZej?ej@ejAejBejCejDejEh ZFdZGdZHddZId d!ZJGd"d#d#eKZLGd$d%d%eKZMGd&d'd'eKZNdS)()print_function)PY2 range_type text_typestr_typeJYTHON IRONPYTHONN)_auth)charset_by_name charset_by_id)CLIENTCOMMANDCR FIELD_TYPE SERVER_STATUS) converters)Cursor)Parser) dump_packet MysqlPacketFieldDescriptorPacketOKPacketWrapperEOFPacketWrapperLoadLocalPacketWrapper)byte2intint2byte)errVERSION_STRINGTF)cCs(g|]}|dkr t|nt|dqS)i)chr).0ir&>/usr/local/lib/python3.10/dist-packages/pymysql/connections.py 6s(r(cCs|dtS)Nlatin1)decode translate_surrogateescape_tablesr&r&r'_fast_surrogateescape8r0cCs |ddS)Nasciisurrogateescape)r+r.r&r&r'r0;s )SocketIOcCstt||SN)ioBufferedReaderr4sockmoder&r&r' _makefileFr1r;cCs ||Sr5)makefiler8r&r&r'r;J utf8mb4cCstd|ddS)NZ%dad?d@Z&dAdBZ'e(fdCdDZ)dEdFZ*dGdHZ+dbdIdJZ,dKdLZ-dMdNZ.dOdPZ/dQdRZ0dSdTZ1dUdVZ2dWdXZ3dYdZZ4d[d\Z5d]d^Z6d_d`Z7e8j9Z9e8j:Z:e8j;Z;e8jZ>e8j?Z?e8j@Z@e8jAZAe8jBZBdS)d Connectiona 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 unmarshaling of types. See converters. :param use_unicode: Whether or not to default to unicode strings. This option defaults to true for Py3k. :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 read_default_group: Group to read from in the configuration file. :param compress: Not supported :param named_pipe: Not supported :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 contruction - 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 authenticaiton plugin public key value. (default: None) :param db: Alias for database. (for compatibility to MySQLdb) :param passwd: Alias for password. (for compatibility to MySQLdb) :param binary_prefix: Add _binary prefix on bytes and bytearray. (default: False) See `Connection `_ in the specification. NFr rHc!$sb| dur tjddkr d} |dur|dur|}|dur|s|}|s#|r'tdt||_|jr4| tjO} rC| sCtjdrAd} nd} | rsIdt t j | fd d }!|!d |}|!d |}|!d |}|!d|}|!d|}t|!d|}|!d|}|!d|}|si}t|trdD]}"|!d|"||"}#|#r|#||"<qd|_|rtstdd|_| tjO} |||_|pd|_|pd|_|pt|_|pd|_t|jtr|jd|_||_||_||_ d|krdkst!dt!d|pd|_"|dur |dkr t!d||_#|dur|dkrt!d||_$|r*||_%d|_&nt'|_%d|_&| dur8| |_&t(|j%j)|_)| tj*O} |jrM| tj+O} | |_,| |_-d|_.d|_/d|_0||_1| durgt2j3} d d!| 4D|_5d"d!| 4D|_6||_7||_8||_9|pi|_:||_;| |_t?d$|_@|r||j@d%<|rd|_AdS|BdS)&NrrTz3compress and named_pipe arguments are not supportedwinz c:\my.iniz /etc/my.cnfclientcs.|r|Sz|WSty|YSwr5)get Exception)keyargcfgread_default_groupr&r'_configs z$Connection.__init__.._configuserpasswordhostdatabasesocketportz bind-addresszdefault-character-set)cacapathcertrTcipherzssl-Fzssl module not found localhosti r*i3z+connect_timeout should be >0 and <=31536000zread_timeout should be >= 0zwrite_timeout should be >= 0z Not connectedcSs"i|] \}}t|tur||qSr&typeintr$kvr&r&r' 0"z'Connection.__init__..cSs"i|] \}}t|tur||qSr&rfrir&r&r'rl1rmpymysql) _client_name_pid_client_version program_name)Csys version_infoNotImplementedErrorbool _local_infiler LOCAL_FILESplatform startswithrreadospath expanduserrh isinstancedictrRssl SSL_ENABLEDSSL_create_ssl_ctxctxr\r_ DEFAULT_USERrZr[rencodedb unix_socket bind_addressrKconnect_timeout _read_timeout_write_timeoutcharset use_unicodeDEFAULT_CHARSETr encoding CAPABILITIESCONNECT_WITH_DB client_flag cursorclass_result_affected_rows host_infoautocommit_moder conversionsitemsencodersdecoderssql_mode init_commandmax_allowed_packet_auth_plugin_map_binary_prefixserver_public_keystrgetpidr_connect_attrs_sockconnect)$selfr\rZr[r]r_rrrread_default_fileconvrrrrrrrXcompress named_pipe autocommitrpasswd local_infiler defer_connectauth_plugin_map read_timeout write_timeoutr binary_prefixrrrrYrTvaluer&rVr'__init__s                              zConnection.__init__cCst|tjr|S|d}|d}|duo|du}tj||d}| o)|dd|_|r0tjntj|_d|vrD|j |d|ddd |vrO| |d |j tj O_ |j tj O_ |S) Nr`ra)cafileracheck_hostnameTrbrT)keyfilerc)rr SSLContextrRcreate_default_contextr CERT_NONE CERT_REQUIRED verify_modeload_cert_chain set_ciphersoptions OP_NO_SSLv2 OP_NO_SSLv3)rsslpr`rahasnocarr&r&r'rGs   zConnection._create_ssl_ctxcCs~|jrtdd|_|jdurdStddtj}zz||Wn t y+YnwW| dSW| dS| w)z Send the quit message and close the socket. See `Connection.close() `_ in the specification. :raise Error: If the connection is already closed. Already closedTN`_ in the specification. COMMITNrrr&r&r'commit zConnection.commitcCr)z Roll back the current transaction. See `Connection.rollback() `_ in the specification. ROLLBACKNrrr&r&r'rollbackrzConnection.rollbackcCs$|tjdt|}||jS)z%Send the "SHOW WARNINGS" SQL command.z SHOW WARNINGS)rrr MySQLResultr{rows)rresultr&r&r' show_warningsszConnection.show_warningscCs|tj||dS)zI Set current db. :param db: The name of the db. N)rr COM_INIT_DBr)rrr&r&r' select_dbs zConnection.select_dbcCsXt|trd||dSt|ttfr#||}|jr!d|}|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) rr escape_stringbytes bytearray _quote_bytesrr escape_itemr)robjrretr&r&r'rs  zConnection.escapecCs|||jS)zjAlias for escape() Non-standard, for internal use; do not use this in your applications. )rr)rrr&r&r'literalszConnection.literalcCs"|jtj@r |ddSt|S)Nrz'')rr"SERVER_STATUS_NO_BACKSLASH_ESCAPESreplacerrrr/r&r&r'rs   zConnection.escape_stringcCs,|jtj@rdt|ddfSt|S)Nz'%s''s'')rrrr0rr escape_bytesrr&r&r'rs  zConnection._quote_bytescCs|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. )r)rcursorr&r&r'rs zConnection.cursorcCstdt|S)z%Context manager that returns a CursorzHContext manager API of Connection object is deprecated; Use conn.begin())warningswarnDeprecationWarningrrr&r&r' __enter__s zConnection.__enter__cCs|r|dS|dS)z2On successful exit, commit. On exception, rollbackN)rr)rexcr tracebackr&r&r'__exit__s  zConnection.__exit__cCsTt|trtststr||j}n||jd}|tj ||j |d|_ |j S)Nr3 unbuffered) rrrr rrrrrr_read_query_resultr)rsqlr r&r&r'queryszConnection.querycCs|j|d|_|jS)Nr )r r)rr r&r&r' next_resultszConnection.next_resultcC|jSr5)rrr&r&r' affected_rows zConnection.affected_rowscCs"td|}|tj||S)Nr@)rArBrrCOM_PROCESS_KILLr)r thread_idrUr&r&r'kills zConnection.killTcCsp|jdur|r|d}ntdz|tjd|WdSty7|r6|| dYdSw)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. NFrrN) rrrrrrCOM_PINGrrSping)r reconnectr&r&r'rs   zConnection.pingcCs:t|j}|tjd|||||_||_dS)Nz SET NAMES %s)r rrrrrrr)rrrr&r&r' set_charset+s  zConnection.set_charsetc CsDd|_z|dur|jr,ttjtj}||j||jd|_d|_ t r+t dnTi}|j dur:|j df|d< ztj |j|jf|jfi|}Wnttfyg}z |jtjkrbWYd}~q:d}~wwd|j|jf|_t rwt d|tjtjd |d|tjtjd ||_t|d |_d|_|||jdur| }|!d |jf|j"dur| }|!|j"|#|$|j%dur|&|j%WdSWdSt'y!}z:d|_|durz|#WnYt(|tttj)frt*+d d |j|f}||_,t-.|_-t rt |j-|d}~ww)NFzLocalhost via UNIX socketTzconnected using unix_socketrsource_addressz socket %s:%dzconnected using socketrrbzSET sql_mode=%siz(Can't connect to MySQL server on %r (%s))/rrr^AF_UNIX SOCK_STREAM settimeoutrrr_secureDEBUGprintrcreate_connectionr\r_OSErrorIOErrorerrnoEINTR setsockopt IPPROTO_TCP TCP_NODELAY SOL_SOCKET SO_KEEPALIVErr;r _next_seq_id_get_server_information_request_authenticationrrexecuterrrrr BaseExceptionrerrorrroriginal_exceptionr format_exc)rr9kwargsecrr&r&r'r4s               zConnection.connectcCsDtt|t|j|}trt||||jdd|_dS)zwWrites an entire "mysql packet" in its entirety to the network addings its length and sequence number. rr)N)rDlenrr+rrr)rpayloaddatar&r&r' write_packet}s  zConnection.write_packetc Csd} |d}td|\}}}||d>}||jkr5||dkr+ttjdt d||jf|jd d |_||}t rHt |||7}|d krQq|t krVnq|||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. reTz|jdkrd}|j rt"rt#dt$|j |j!}n%t"rt#dn|jdkrd}|jr|jtj@r|j d }n|j rd}nd }|jtj%@r|t&t'||7}n|jtj(@r|tdt'||7}n||d 7}|j)r|jtj*@rt |j)t r |j) |j|_)||j)d 7}|jtj+@r#||pdd 7}|jtj,@red}|j-.D]'\}}| d}|tdt'||7}| d}|tdt'||7}q1|tdt'||7}|||/} | 0rt"rzt#d| 1| 2}|jtj+@r|dur|3|| } nAt4|j |j!d }|||/} n-| 5rt"rt#d|jdkrt6|| } n|jdkrt7|| } nt89d|jt"rt#ddSdS)N.rrzDid not specify a usernamezO_ trtd|td|d}|d7}t |||kr|j ||||7_ ||7}|d7}|j tj@rt ||kr|d|}|dkr||dd|_dS|||d|_dSdSdS)Nrrr`r*r@r: rGrr!zrrrrnr6server_languager nameserver_charsetKeyErrorrrr maxr rvrp) rr%rKr8 server_endlangstatcap_hsalt_lenr&r&r'r,sN     z"Connection._get_server_informationcCrr5)rjrr&r&r'get_server_info rzConnection.get_server_infor5)F)T)C__name__ __module__ __qualname____doc__rrprrrrrrpropertyrr__del__rrrrrrrrrrrrrrrrr rrrrrrr9rrr=rr rTrr-r{rrrrrr,rrWarningrrV DatabaseError DataErrorrIntegrityErrorr@ProgrammingErrorNotSupportedErrorr&r&r&r'rMts=            I ' *h8? rMc@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) rRrrTr warning_countmessage field_count descriptionrrXrQ)rrRr&r&r'rs zMySQLResult.__init__cCs|jr |dSdSr5)rQrWrr&r&r'r-s zMySQLResult.__del__cCsjz0|j}|r||n|r||n||Wd|_dSWd|_dSWd|_dSd|_wr5)rRrrris_load_local_packet_read_load_local_packet_read_result_packetr first_packetr&r&r'r{1s      zMySQLResult.readcCspd|_|j}|r||d|_d|_dS|r*||d|_d|_dS||_| d|_ dS)zw :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: TFNl) rQrRrrrrrread_length_encoded_integerr_get_descriptionsrrr&r&r'rP>s       z!MySQLResult.init_unbuffered_querycCs<t|}|j|_|j|_|j|_|j|_|j|_|j|_dSr5)rrrTrrrrX)rr ok_packetr&r&r'rWs zMySQLResult._read_ok_packetcCsr|jjstdt|}t|j|j}z|Wn |j|j}|s2t dd| |dS)NzF**WARN**: Received LOAD_LOCAL packet but local_infile option is false.rzCommands Out of Sync) rRrw RuntimeErrorr LoadLocalFilefilenamerrrrrr)rr load_packetsenderrr&r&r'r`s    z#MySQLResult._read_load_local_packetcCs(|sdSt|}|j|_|j|_dS)NFT) is_eof_packetrrrX)rrKwpr&r&r'_check_packet_is_eofqs z MySQLResult._check_packet_is_eofcCs||_||dSr5)rrr_read_rowdata_packetrr&r&r'r}s  zMySQLResult._read_result_packetcCsP|jsdS|j}||rd|_d|_d|_dS||}d|_|f|_|S)NFr)rQrRrrr_read_row_from_packetr)rrKrowr&r&r'_read_rowdata_packet_unbuffereds   z+MySQLResult._read_rowdata_packet_unbufferedcCs4|jr|j}||rd|_d|_|jsdSdSrO)rQrRrr)rrKr&r&r'rWs   z$MySQLResult._finish_unbuffered_querycCsLg} |j}||rd|_n |||qt||_t||_dS)z:Read a rowdata packet for each data row in the result set.TN) rRrrappendrr6rtupler)rrrKr&r&r'rs   z MySQLResult._read_rowdata_packetc Csg}|jD]9\}}z|}Wn tyYt|Sw|dur9|dur*||}tr1td||dur9||}||qt|S)NzDEBUG: DATA = )rread_length_coded_string IndexErrorr+rr rr)rrKrr converterr8r&r&r'rs     z!MySQLResult._read_row_from_packetc Csg|_g|_|jj}|jj}g}t|jD]V}|jt}|j || | |j }|rI|t j kr7|}n|tvrF|jdkrCd}n|}nd}nd}|jj|}|tjurYd}trctd|||j ||fq|j} | syJdt||_ dS)z>Read a column descriptor packet for each column in the result.?Nr2zDEBUG: field={}, converter={}zProtocol error, expecting EOF)fieldsrrRrrrrrrrr type_coderJSON TEXT_TYPES charsetnrrrRthroughrr formatrr) rr conn_encodingrr%field field_typerr eof_packetr&r&r'rs6      zMySQLResult._get_descriptionsN)rrrrrr{rPrrrrrrWrrrr&r&r&r'rs     rc@seZdZddZddZdS)rcCs||_||_dSr5)rrR)rrrRr&r&r'rs zLoadLocalFile.__init__c Cs|jjs td|j}zGz-t|jd}t|jd} ||}|s$n| |qWdn1s4wYWnt yKt dd |jwW| ddS| dw) z3Send data packets from the local file to the serverrUri@TNizCan't find file '{0}'re) rRrrrVrrrYrr{r9r#rr)rconn open_filer[chunkr&r&r'rs(     zLoadLocalFile.send_dataN)rrrrrr&r&r&r'rs r)O __future__r_compatrrrrrr r$r6r|r^rArsrrrNr rr r constantsr rrrrrcursorsr optionfilerprotocolrrrrrrutilrrrrrr ImportErrorgetpassgetuserrrrrt _py_versionranger-r0 _socketior4r;BITBLOB LONG_BLOB MEDIUM_BLOBSTRING TINY_BLOB VAR_STRINGVARCHARGEOMETRYrrrArDrLobjectrMrrr&r&r&r's            .N