connections.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. # Python implementation of the MySQL client-server protocol
  2. # http://dev.mysql.com/doc/internals/en/client-server-protocol.html
  3. # Error codes:
  4. # https://dev.mysql.com/doc/refman/5.5/en/error-handling.html
  5. import errno
  6. import os
  7. import socket
  8. import struct
  9. import sys
  10. import traceback
  11. import warnings
  12. from . import _auth
  13. from .charset import charset_by_name, charset_by_id
  14. from .constants import CLIENT, COMMAND, CR, FIELD_TYPE, SERVER_STATUS
  15. from . import converters
  16. from .cursors import Cursor
  17. from .optionfile import Parser
  18. from .protocol import (
  19. dump_packet,
  20. MysqlPacket,
  21. FieldDescriptorPacket,
  22. OKPacketWrapper,
  23. EOFPacketWrapper,
  24. LoadLocalPacketWrapper,
  25. )
  26. from . import err, VERSION_STRING
  27. try:
  28. import ssl
  29. SSL_ENABLED = True
  30. except ImportError:
  31. ssl = None
  32. SSL_ENABLED = False
  33. try:
  34. import getpass
  35. DEFAULT_USER = getpass.getuser()
  36. del getpass
  37. except (ImportError, KeyError):
  38. # KeyError occurs when there's no entry in OS database for a current user.
  39. DEFAULT_USER = None
  40. DEBUG = False
  41. TEXT_TYPES = {
  42. FIELD_TYPE.BIT,
  43. FIELD_TYPE.BLOB,
  44. FIELD_TYPE.LONG_BLOB,
  45. FIELD_TYPE.MEDIUM_BLOB,
  46. FIELD_TYPE.STRING,
  47. FIELD_TYPE.TINY_BLOB,
  48. FIELD_TYPE.VAR_STRING,
  49. FIELD_TYPE.VARCHAR,
  50. FIELD_TYPE.GEOMETRY,
  51. }
  52. DEFAULT_CHARSET = "utf8mb4"
  53. MAX_PACKET_LEN = 2 ** 24 - 1
  54. def _pack_int24(n):
  55. return struct.pack("<I", n)[:3]
  56. # https://dev.mysql.com/doc/internals/en/integer.html#packet-Protocol::LengthEncodedInteger
  57. def _lenenc_int(i):
  58. if i < 0:
  59. raise ValueError(
  60. "Encoding %d is less than 0 - no representation in LengthEncodedInteger" % i
  61. )
  62. elif i < 0xFB:
  63. return bytes([i])
  64. elif i < (1 << 16):
  65. return b"\xfc" + struct.pack("<H", i)
  66. elif i < (1 << 24):
  67. return b"\xfd" + struct.pack("<I", i)[:3]
  68. elif i < (1 << 64):
  69. return b"\xfe" + struct.pack("<Q", i)
  70. else:
  71. raise ValueError(
  72. "Encoding %x is larger than %x - no representation in LengthEncodedInteger"
  73. % (i, (1 << 64))
  74. )
  75. class Connection:
  76. """
  77. Representation of a socket with a mysql server.
  78. The proper way to get an instance of this class is to call
  79. connect().
  80. Establish a connection to the MySQL database. Accepts several
  81. arguments:
  82. :param host: Host where the database server is located
  83. :param user: Username to log in as
  84. :param password: Password to use.
  85. :param database: Database to use, None to not use a particular one.
  86. :param port: MySQL port to use, default is usually OK. (default: 3306)
  87. :param bind_address: When the client has multiple network interfaces, specify
  88. the interface from which to connect to the host. Argument can be
  89. a hostname or an IP address.
  90. :param unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
  91. :param read_timeout: The timeout for reading from the connection in seconds (default: None - no timeout)
  92. :param write_timeout: The timeout for writing to the connection in seconds (default: None - no timeout)
  93. :param charset: Charset you want to use.
  94. :param sql_mode: Default SQL_MODE to use.
  95. :param read_default_file:
  96. Specifies my.cnf file to read these parameters from under the [client] section.
  97. :param conv:
  98. Conversion dictionary to use instead of the default one.
  99. This is used to provide custom marshalling and unmarshalling of types.
  100. See converters.
  101. :param use_unicode:
  102. Whether or not to default to unicode strings.
  103. This option defaults to true.
  104. :param client_flag: Custom flags to send to MySQL. Find potential values in constants.CLIENT.
  105. :param cursorclass: Custom cursor class to use.
  106. :param init_command: Initial SQL statement to run when connection is established.
  107. :param connect_timeout: Timeout before throwing an exception when connecting.
  108. (default: 10, min: 1, max: 31536000)
  109. :param ssl:
  110. A dict of arguments similar to mysql_ssl_set()'s parameters.
  111. :param ssl_ca: Path to the file that contains a PEM-formatted CA certificate
  112. :param ssl_cert: Path to the file that contains a PEM-formatted client certificate
  113. :param ssl_disabled: A boolean value that disables usage of TLS
  114. :param ssl_key: Path to the file that contains a PEM-formatted private key for the client certificate
  115. :param ssl_verify_cert: Set to true to check the validity of server certificates
  116. :param ssl_verify_identity: Set to true to check the server's identity
  117. :param read_default_group: Group to read from in the configuration file.
  118. :param autocommit: Autocommit mode. None means use server default. (default: False)
  119. :param local_infile: Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
  120. :param max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
  121. Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
  122. :param defer_connect: Don't explicitly connect on construction - wait for connect call.
  123. (default: False)
  124. :param auth_plugin_map: A dict of plugin names to a class that processes that plugin.
  125. The class will take the Connection object as the argument to the constructor.
  126. The class needs an authenticate method taking an authentication packet as
  127. an argument. For the dialog plugin, a prompt(echo, prompt) method can be used
  128. (if no authenticate method) for returning a string from the user. (experimental)
  129. :param server_public_key: SHA256 authentication plugin public key value. (default: None)
  130. :param binary_prefix: Add _binary prefix on bytes and bytearray. (default: False)
  131. :param compress: Not supported
  132. :param named_pipe: Not supported
  133. :param db: **DEPRECATED** Alias for database.
  134. :param passwd: **DEPRECATED** Alias for password.
  135. See `Connection <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_ in the
  136. specification.
  137. """
  138. _sock = None
  139. _auth_plugin_name = ""
  140. _closed = False
  141. _secure = False
  142. def __init__(
  143. self,
  144. *,
  145. user=None, # The first four arguments is based on DB-API 2.0 recommendation.
  146. password="",
  147. host=None,
  148. database=None,
  149. unix_socket=None,
  150. port=0,
  151. charset="",
  152. sql_mode=None,
  153. read_default_file=None,
  154. conv=None,
  155. use_unicode=True,
  156. client_flag=0,
  157. cursorclass=Cursor,
  158. init_command=None,
  159. connect_timeout=10,
  160. read_default_group=None,
  161. autocommit=False,
  162. local_infile=False,
  163. max_allowed_packet=16 * 1024 * 1024,
  164. defer_connect=False,
  165. auth_plugin_map=None,
  166. read_timeout=None,
  167. write_timeout=None,
  168. bind_address=None,
  169. binary_prefix=False,
  170. program_name=None,
  171. server_public_key=None,
  172. ssl=None,
  173. ssl_ca=None,
  174. ssl_cert=None,
  175. ssl_disabled=None,
  176. ssl_key=None,
  177. ssl_verify_cert=None,
  178. ssl_verify_identity=None,
  179. compress=None, # not supported
  180. named_pipe=None, # not supported
  181. passwd=None, # deprecated
  182. db=None, # deprecated
  183. ):
  184. if db is not None and database is None:
  185. # We will raise warining in 2022 or later.
  186. # See https://github.com/PyMySQL/PyMySQL/issues/939
  187. # warnings.warn("'db' is deprecated, use 'database'", DeprecationWarning, 3)
  188. database = db
  189. if passwd is not None and not password:
  190. # We will raise warining in 2022 or later.
  191. # See https://github.com/PyMySQL/PyMySQL/issues/939
  192. # warnings.warn(
  193. # "'passwd' is deprecated, use 'password'", DeprecationWarning, 3
  194. # )
  195. password = passwd
  196. if compress or named_pipe:
  197. raise NotImplementedError(
  198. "compress and named_pipe arguments are not supported"
  199. )
  200. self._local_infile = bool(local_infile)
  201. if self._local_infile:
  202. client_flag |= CLIENT.LOCAL_FILES
  203. if read_default_group and not read_default_file:
  204. if sys.platform.startswith("win"):
  205. read_default_file = "c:\\my.ini"
  206. else:
  207. read_default_file = "/etc/my.cnf"
  208. if read_default_file:
  209. if not read_default_group:
  210. read_default_group = "client"
  211. cfg = Parser()
  212. cfg.read(os.path.expanduser(read_default_file))
  213. def _config(key, arg):
  214. if arg:
  215. return arg
  216. try:
  217. return cfg.get(read_default_group, key)
  218. except Exception:
  219. return arg
  220. user = _config("user", user)
  221. password = _config("password", password)
  222. host = _config("host", host)
  223. database = _config("database", database)
  224. unix_socket = _config("socket", unix_socket)
  225. port = int(_config("port", port))
  226. bind_address = _config("bind-address", bind_address)
  227. charset = _config("default-character-set", charset)
  228. if not ssl:
  229. ssl = {}
  230. if isinstance(ssl, dict):
  231. for key in ["ca", "capath", "cert", "key", "cipher"]:
  232. value = _config("ssl-" + key, ssl.get(key))
  233. if value:
  234. ssl[key] = value
  235. self.ssl = False
  236. if not ssl_disabled:
  237. if ssl_ca or ssl_cert or ssl_key or ssl_verify_cert or ssl_verify_identity:
  238. ssl = {
  239. "ca": ssl_ca,
  240. "check_hostname": bool(ssl_verify_identity),
  241. "verify_mode": ssl_verify_cert
  242. if ssl_verify_cert is not None
  243. else False,
  244. }
  245. if ssl_cert is not None:
  246. ssl["cert"] = ssl_cert
  247. if ssl_key is not None:
  248. ssl["key"] = ssl_key
  249. if ssl:
  250. if not SSL_ENABLED:
  251. raise NotImplementedError("ssl module not found")
  252. self.ssl = True
  253. client_flag |= CLIENT.SSL
  254. self.ctx = self._create_ssl_ctx(ssl)
  255. self.host = host or "localhost"
  256. self.port = port or 3306
  257. if type(self.port) is not int:
  258. raise ValueError("port should be of type int")
  259. self.user = user or DEFAULT_USER
  260. self.password = password or b""
  261. if isinstance(self.password, str):
  262. self.password = self.password.encode("latin1")
  263. self.db = database
  264. self.unix_socket = unix_socket
  265. self.bind_address = bind_address
  266. if not (0 < connect_timeout <= 31536000):
  267. raise ValueError("connect_timeout should be >0 and <=31536000")
  268. self.connect_timeout = connect_timeout or None
  269. if read_timeout is not None and read_timeout <= 0:
  270. raise ValueError("read_timeout should be > 0")
  271. self._read_timeout = read_timeout
  272. if write_timeout is not None and write_timeout <= 0:
  273. raise ValueError("write_timeout should be > 0")
  274. self._write_timeout = write_timeout
  275. self.charset = charset or DEFAULT_CHARSET
  276. self.use_unicode = use_unicode
  277. self.encoding = charset_by_name(self.charset).encoding
  278. client_flag |= CLIENT.CAPABILITIES
  279. if self.db:
  280. client_flag |= CLIENT.CONNECT_WITH_DB
  281. self.client_flag = client_flag
  282. self.cursorclass = cursorclass
  283. self._result = None
  284. self._affected_rows = 0
  285. self.host_info = "Not connected"
  286. # specified autocommit mode. None means use server default.
  287. self.autocommit_mode = autocommit
  288. if conv is None:
  289. conv = converters.conversions
  290. # Need for MySQLdb compatibility.
  291. self.encoders = {k: v for (k, v) in conv.items() if type(k) is not int}
  292. self.decoders = {k: v for (k, v) in conv.items() if type(k) is int}
  293. self.sql_mode = sql_mode
  294. self.init_command = init_command
  295. self.max_allowed_packet = max_allowed_packet
  296. self._auth_plugin_map = auth_plugin_map or {}
  297. self._binary_prefix = binary_prefix
  298. self.server_public_key = server_public_key
  299. self._connect_attrs = {
  300. "_client_name": "pymysql",
  301. "_pid": str(os.getpid()),
  302. "_client_version": VERSION_STRING,
  303. }
  304. if program_name:
  305. self._connect_attrs["program_name"] = program_name
  306. if defer_connect:
  307. self._sock = None
  308. else:
  309. self.connect()
  310. def __enter__(self):
  311. return self
  312. def __exit__(self, *exc_info):
  313. del exc_info
  314. self.close()
  315. def _create_ssl_ctx(self, sslp):
  316. if isinstance(sslp, ssl.SSLContext):
  317. return sslp
  318. ca = sslp.get("ca")
  319. capath = sslp.get("capath")
  320. hasnoca = ca is None and capath is None
  321. ctx = ssl.create_default_context(cafile=ca, capath=capath)
  322. ctx.check_hostname = not hasnoca and sslp.get("check_hostname", True)
  323. verify_mode_value = sslp.get("verify_mode")
  324. if verify_mode_value is None:
  325. ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
  326. elif isinstance(verify_mode_value, bool):
  327. ctx.verify_mode = ssl.CERT_REQUIRED if verify_mode_value else ssl.CERT_NONE
  328. else:
  329. if isinstance(verify_mode_value, str):
  330. verify_mode_value = verify_mode_value.lower()
  331. if verify_mode_value in ("none", "0", "false", "no"):
  332. ctx.verify_mode = ssl.CERT_NONE
  333. elif verify_mode_value == "optional":
  334. ctx.verify_mode = ssl.CERT_OPTIONAL
  335. elif verify_mode_value in ("required", "1", "true", "yes"):
  336. ctx.verify_mode = ssl.CERT_REQUIRED
  337. else:
  338. ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
  339. if "cert" in sslp:
  340. ctx.load_cert_chain(sslp["cert"], keyfile=sslp.get("key"))
  341. if "cipher" in sslp:
  342. ctx.set_ciphers(sslp["cipher"])
  343. ctx.options |= ssl.OP_NO_SSLv2
  344. ctx.options |= ssl.OP_NO_SSLv3
  345. return ctx
  346. def close(self):
  347. """
  348. Send the quit message and close the socket.
  349. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
  350. in the specification.
  351. :raise Error: If the connection is already closed.
  352. """
  353. if self._closed:
  354. raise err.Error("Already closed")
  355. self._closed = True
  356. if self._sock is None:
  357. return
  358. send_data = struct.pack("<iB", 1, COMMAND.COM_QUIT)
  359. try:
  360. self._write_bytes(send_data)
  361. except Exception:
  362. pass
  363. finally:
  364. self._force_close()
  365. @property
  366. def open(self):
  367. """Return True if the connection is open"""
  368. return self._sock is not None
  369. def _force_close(self):
  370. """Close connection without QUIT message"""
  371. if self._sock:
  372. try:
  373. self._sock.close()
  374. except: # noqa
  375. pass
  376. self._sock = None
  377. self._rfile = None
  378. __del__ = _force_close
  379. def autocommit(self, value):
  380. self.autocommit_mode = bool(value)
  381. current = self.get_autocommit()
  382. if value != current:
  383. self._send_autocommit_mode()
  384. def get_autocommit(self):
  385. return bool(self.server_status & SERVER_STATUS.SERVER_STATUS_AUTOCOMMIT)
  386. def _read_ok_packet(self):
  387. pkt = self._read_packet()
  388. if not pkt.is_ok_packet():
  389. raise err.OperationalError(2014, "Command Out of Sync")
  390. ok = OKPacketWrapper(pkt)
  391. self.server_status = ok.server_status
  392. return ok
  393. def _send_autocommit_mode(self):
  394. """Set whether or not to commit after every execute()"""
  395. self._execute_command(
  396. COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" % self.escape(self.autocommit_mode)
  397. )
  398. self._read_ok_packet()
  399. def begin(self):
  400. """Begin transaction."""
  401. self._execute_command(COMMAND.COM_QUERY, "BEGIN")
  402. self._read_ok_packet()
  403. def commit(self):
  404. """
  405. Commit changes to stable storage.
  406. See `Connection.commit() <https://www.python.org/dev/peps/pep-0249/#commit>`_
  407. in the specification.
  408. """
  409. self._execute_command(COMMAND.COM_QUERY, "COMMIT")
  410. self._read_ok_packet()
  411. def rollback(self):
  412. """
  413. Roll back the current transaction.
  414. See `Connection.rollback() <https://www.python.org/dev/peps/pep-0249/#rollback>`_
  415. in the specification.
  416. """
  417. self._execute_command(COMMAND.COM_QUERY, "ROLLBACK")
  418. self._read_ok_packet()
  419. def show_warnings(self):
  420. """Send the "SHOW WARNINGS" SQL command."""
  421. self._execute_command(COMMAND.COM_QUERY, "SHOW WARNINGS")
  422. result = MySQLResult(self)
  423. result.read()
  424. return result.rows
  425. def select_db(self, db):
  426. """
  427. Set current db.
  428. :param db: The name of the db.
  429. """
  430. self._execute_command(COMMAND.COM_INIT_DB, db)
  431. self._read_ok_packet()
  432. def escape(self, obj, mapping=None):
  433. """Escape whatever value you pass to it.
  434. Non-standard, for internal use; do not use this in your applications.
  435. """
  436. if isinstance(obj, str):
  437. return "'" + self.escape_string(obj) + "'"
  438. if isinstance(obj, (bytes, bytearray)):
  439. ret = self._quote_bytes(obj)
  440. if self._binary_prefix:
  441. ret = "_binary" + ret
  442. return ret
  443. return converters.escape_item(obj, self.charset, mapping=mapping)
  444. def literal(self, obj):
  445. """Alias for escape()
  446. Non-standard, for internal use; do not use this in your applications.
  447. """
  448. return self.escape(obj, self.encoders)
  449. def escape_string(self, s):
  450. if self.server_status & SERVER_STATUS.SERVER_STATUS_NO_BACKSLASH_ESCAPES:
  451. return s.replace("'", "''")
  452. return converters.escape_string(s)
  453. def _quote_bytes(self, s):
  454. if self.server_status & SERVER_STATUS.SERVER_STATUS_NO_BACKSLASH_ESCAPES:
  455. return "'%s'" % (s.replace(b"'", b"''").decode("ascii", "surrogateescape"),)
  456. return converters.escape_bytes(s)
  457. def cursor(self, cursor=None):
  458. """
  459. Create a new cursor to execute queries with.
  460. :param cursor: The type of cursor to create; one of :py:class:`Cursor`,
  461. :py:class:`SSCursor`, :py:class:`DictCursor`, or :py:class:`SSDictCursor`.
  462. None means use Cursor.
  463. """
  464. if cursor:
  465. return cursor(self)
  466. return self.cursorclass(self)
  467. # The following methods are INTERNAL USE ONLY (called from Cursor)
  468. def query(self, sql, unbuffered=False):
  469. # if DEBUG:
  470. # print("DEBUG: sending query:", sql)
  471. if isinstance(sql, str):
  472. sql = sql.encode(self.encoding, "surrogateescape")
  473. self._execute_command(COMMAND.COM_QUERY, sql)
  474. self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  475. return self._affected_rows
  476. def next_result(self, unbuffered=False):
  477. self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  478. return self._affected_rows
  479. def affected_rows(self):
  480. return self._affected_rows
  481. def kill(self, thread_id):
  482. arg = struct.pack("<I", thread_id)
  483. self._execute_command(COMMAND.COM_PROCESS_KILL, arg)
  484. return self._read_ok_packet()
  485. def ping(self, reconnect=True):
  486. """
  487. Check if the server is alive.
  488. :param reconnect: If the connection is closed, reconnect.
  489. :raise Error: If the connection is closed and reconnect=False.
  490. """
  491. if self._sock is None:
  492. if reconnect:
  493. self.connect()
  494. reconnect = False
  495. else:
  496. raise err.Error("Already closed")
  497. try:
  498. self._execute_command(COMMAND.COM_PING, "")
  499. self._read_ok_packet()
  500. except Exception:
  501. if reconnect:
  502. self.connect()
  503. self.ping(False)
  504. else:
  505. raise
  506. def set_charset(self, charset):
  507. # Make sure charset is supported.
  508. encoding = charset_by_name(charset).encoding
  509. self._execute_command(COMMAND.COM_QUERY, "SET NAMES %s" % self.escape(charset))
  510. self._read_packet()
  511. self.charset = charset
  512. self.encoding = encoding
  513. def connect(self, sock=None):
  514. self._closed = False
  515. try:
  516. if sock is None:
  517. if self.unix_socket:
  518. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  519. sock.settimeout(self.connect_timeout)
  520. sock.connect(self.unix_socket)
  521. self.host_info = "Localhost via UNIX socket"
  522. self._secure = True
  523. if DEBUG:
  524. print("connected using unix_socket")
  525. else:
  526. kwargs = {}
  527. if self.bind_address is not None:
  528. kwargs["source_address"] = (self.bind_address, 0)
  529. while True:
  530. try:
  531. sock = socket.create_connection(
  532. (self.host, self.port), self.connect_timeout, **kwargs
  533. )
  534. break
  535. except (OSError, IOError) as e:
  536. if e.errno == errno.EINTR:
  537. continue
  538. raise
  539. self.host_info = "socket %s:%d" % (self.host, self.port)
  540. if DEBUG:
  541. print("connected using socket")
  542. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  543. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  544. sock.settimeout(None)
  545. self._sock = sock
  546. self._rfile = sock.makefile("rb")
  547. self._next_seq_id = 0
  548. self._get_server_information()
  549. self._request_authentication()
  550. if self.sql_mode is not None:
  551. c = self.cursor()
  552. c.execute("SET sql_mode=%s", (self.sql_mode,))
  553. if self.init_command is not None:
  554. c = self.cursor()
  555. c.execute(self.init_command)
  556. c.close()
  557. self.commit()
  558. if self.autocommit_mode is not None:
  559. self.autocommit(self.autocommit_mode)
  560. except BaseException as e:
  561. self._rfile = None
  562. if sock is not None:
  563. try:
  564. sock.close()
  565. except: # noqa
  566. pass
  567. if isinstance(e, (OSError, IOError, socket.error)):
  568. exc = err.OperationalError(
  569. 2003, "Can't connect to MySQL server on %r (%s)" % (self.host, e)
  570. )
  571. # Keep original exception and traceback to investigate error.
  572. exc.original_exception = e
  573. exc.traceback = traceback.format_exc()
  574. if DEBUG:
  575. print(exc.traceback)
  576. raise exc
  577. # If e is neither DatabaseError or IOError, It's a bug.
  578. # But raising AssertionError hides original error.
  579. # So just reraise it.
  580. raise
  581. def write_packet(self, payload):
  582. """Writes an entire "mysql packet" in its entirety to the network
  583. adding its length and sequence number.
  584. """
  585. # Internal note: when you build packet manually and calls _write_bytes()
  586. # directly, you should set self._next_seq_id properly.
  587. data = _pack_int24(len(payload)) + bytes([self._next_seq_id]) + payload
  588. if DEBUG:
  589. dump_packet(data)
  590. self._write_bytes(data)
  591. self._next_seq_id = (self._next_seq_id + 1) % 256
  592. def _read_packet(self, packet_type=MysqlPacket):
  593. """Read an entire "mysql packet" in its entirety from the network
  594. and return a MysqlPacket type that represents the results.
  595. :raise OperationalError: If the connection to the MySQL server is lost.
  596. :raise InternalError: If the packet sequence number is wrong.
  597. """
  598. buff = bytearray()
  599. while True:
  600. packet_header = self._read_bytes(4)
  601. # if DEBUG: dump_packet(packet_header)
  602. btrl, btrh, packet_number = struct.unpack("<HBB", packet_header)
  603. bytes_to_read = btrl + (btrh << 16)
  604. if packet_number != self._next_seq_id:
  605. self._force_close()
  606. if packet_number == 0:
  607. # MariaDB sends error packet with seqno==0 when shutdown
  608. raise err.OperationalError(
  609. CR.CR_SERVER_LOST,
  610. "Lost connection to MySQL server during query",
  611. )
  612. raise err.InternalError(
  613. "Packet sequence number wrong - got %d expected %d"
  614. % (packet_number, self._next_seq_id)
  615. )
  616. self._next_seq_id = (self._next_seq_id + 1) % 256
  617. recv_data = self._read_bytes(bytes_to_read)
  618. if DEBUG:
  619. dump_packet(recv_data)
  620. buff += recv_data
  621. # https://dev.mysql.com/doc/internals/en/sending-more-than-16mbyte.html
  622. if bytes_to_read == 0xFFFFFF:
  623. continue
  624. if bytes_to_read < MAX_PACKET_LEN:
  625. break
  626. packet = packet_type(bytes(buff), self.encoding)
  627. if packet.is_error_packet():
  628. if self._result is not None and self._result.unbuffered_active is True:
  629. self._result.unbuffered_active = False
  630. packet.raise_for_error()
  631. return packet
  632. def _read_bytes(self, num_bytes):
  633. self._sock.settimeout(self._read_timeout)
  634. while True:
  635. try:
  636. data = self._rfile.read(num_bytes)
  637. break
  638. except (IOError, OSError) as e:
  639. if e.errno == errno.EINTR:
  640. continue
  641. self._force_close()
  642. raise err.OperationalError(
  643. CR.CR_SERVER_LOST,
  644. "Lost connection to MySQL server during query (%s)" % (e,),
  645. )
  646. except BaseException:
  647. # Don't convert unknown exception to MySQLError.
  648. self._force_close()
  649. raise
  650. if len(data) < num_bytes:
  651. self._force_close()
  652. raise err.OperationalError(
  653. CR.CR_SERVER_LOST, "Lost connection to MySQL server during query"
  654. )
  655. return data
  656. def _write_bytes(self, data):
  657. self._sock.settimeout(self._write_timeout)
  658. try:
  659. self._sock.sendall(data)
  660. except IOError as e:
  661. self._force_close()
  662. raise err.OperationalError(
  663. CR.CR_SERVER_GONE_ERROR, "MySQL server has gone away (%r)" % (e,)
  664. )
  665. def _read_query_result(self, unbuffered=False):
  666. self._result = None
  667. if unbuffered:
  668. try:
  669. result = MySQLResult(self)
  670. result.init_unbuffered_query()
  671. except:
  672. result.unbuffered_active = False
  673. result.connection = None
  674. raise
  675. else:
  676. result = MySQLResult(self)
  677. result.read()
  678. self._result = result
  679. if result.server_status is not None:
  680. self.server_status = result.server_status
  681. return result.affected_rows
  682. def insert_id(self):
  683. if self._result:
  684. return self._result.insert_id
  685. else:
  686. return 0
  687. def _execute_command(self, command, sql):
  688. """
  689. :raise InterfaceError: If the connection is closed.
  690. :raise ValueError: If no username was specified.
  691. """
  692. if not self._sock:
  693. raise err.InterfaceError(0, "")
  694. # If the last query was unbuffered, make sure it finishes before
  695. # sending new commands
  696. if self._result is not None:
  697. if self._result.unbuffered_active:
  698. warnings.warn("Previous unbuffered result was left incomplete")
  699. self._result._finish_unbuffered_query()
  700. while self._result.has_next:
  701. self.next_result()
  702. self._result = None
  703. if isinstance(sql, str):
  704. sql = sql.encode(self.encoding)
  705. packet_size = min(MAX_PACKET_LEN, len(sql) + 1) # +1 is for command
  706. # tiny optimization: build first packet manually instead of
  707. # calling self..write_packet()
  708. prelude = struct.pack("<iB", packet_size, command)
  709. packet = prelude + sql[: packet_size - 1]
  710. self._write_bytes(packet)
  711. if DEBUG:
  712. dump_packet(packet)
  713. self._next_seq_id = 1
  714. if packet_size < MAX_PACKET_LEN:
  715. return
  716. sql = sql[packet_size - 1 :]
  717. while True:
  718. packet_size = min(MAX_PACKET_LEN, len(sql))
  719. self.write_packet(sql[:packet_size])
  720. sql = sql[packet_size:]
  721. if not sql and packet_size < MAX_PACKET_LEN:
  722. break
  723. def _request_authentication(self):
  724. # https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse
  725. if int(self.server_version.split(".", 1)[0]) >= 5:
  726. self.client_flag |= CLIENT.MULTI_RESULTS
  727. if self.user is None:
  728. raise ValueError("Did not specify a username")
  729. charset_id = charset_by_name(self.charset).id
  730. if isinstance(self.user, str):
  731. self.user = self.user.encode(self.encoding)
  732. data_init = struct.pack(
  733. "<iIB23s", self.client_flag, MAX_PACKET_LEN, charset_id, b""
  734. )
  735. if self.ssl and self.server_capabilities & CLIENT.SSL:
  736. self.write_packet(data_init)
  737. self._sock = self.ctx.wrap_socket(self._sock, server_hostname=self.host)
  738. self._rfile = self._sock.makefile("rb")
  739. self._secure = True
  740. data = data_init + self.user + b"\0"
  741. authresp = b""
  742. plugin_name = None
  743. if self._auth_plugin_name == "":
  744. plugin_name = b""
  745. authresp = _auth.scramble_native_password(self.password, self.salt)
  746. elif self._auth_plugin_name == "mysql_native_password":
  747. plugin_name = b"mysql_native_password"
  748. authresp = _auth.scramble_native_password(self.password, self.salt)
  749. elif self._auth_plugin_name == "caching_sha2_password":
  750. plugin_name = b"caching_sha2_password"
  751. if self.password:
  752. if DEBUG:
  753. print("caching_sha2: trying fast path")
  754. authresp = _auth.scramble_caching_sha2(self.password, self.salt)
  755. else:
  756. if DEBUG:
  757. print("caching_sha2: empty password")
  758. elif self._auth_plugin_name == "sha256_password":
  759. plugin_name = b"sha256_password"
  760. if self.ssl and self.server_capabilities & CLIENT.SSL:
  761. authresp = self.password + b"\0"
  762. elif self.password:
  763. authresp = b"\1" # request public key
  764. else:
  765. authresp = b"\0" # empty password
  766. if self.server_capabilities & CLIENT.PLUGIN_AUTH_LENENC_CLIENT_DATA:
  767. data += _lenenc_int(len(authresp)) + authresp
  768. elif self.server_capabilities & CLIENT.SECURE_CONNECTION:
  769. data += struct.pack("B", len(authresp)) + authresp
  770. else: # pragma: no cover - not testing against servers without secure auth (>=5.0)
  771. data += authresp + b"\0"
  772. if self.db and self.server_capabilities & CLIENT.CONNECT_WITH_DB:
  773. if isinstance(self.db, str):
  774. self.db = self.db.encode(self.encoding)
  775. data += self.db + b"\0"
  776. if self.server_capabilities & CLIENT.PLUGIN_AUTH:
  777. data += (plugin_name or b"") + b"\0"
  778. if self.server_capabilities & CLIENT.CONNECT_ATTRS:
  779. connect_attrs = b""
  780. for k, v in self._connect_attrs.items():
  781. k = k.encode("utf-8")
  782. connect_attrs += struct.pack("B", len(k)) + k
  783. v = v.encode("utf-8")
  784. connect_attrs += struct.pack("B", len(v)) + v
  785. data += struct.pack("B", len(connect_attrs)) + connect_attrs
  786. self.write_packet(data)
  787. auth_packet = self._read_packet()
  788. # if authentication method isn't accepted the first byte
  789. # will have the octet 254
  790. if auth_packet.is_auth_switch_request():
  791. if DEBUG:
  792. print("received auth switch")
  793. # https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest
  794. auth_packet.read_uint8() # 0xfe packet identifier
  795. plugin_name = auth_packet.read_string()
  796. if (
  797. self.server_capabilities & CLIENT.PLUGIN_AUTH
  798. and plugin_name is not None
  799. ):
  800. auth_packet = self._process_auth(plugin_name, auth_packet)
  801. else:
  802. # send legacy handshake
  803. data = _auth.scramble_old_password(self.password, self.salt) + b"\0"
  804. self.write_packet(data)
  805. auth_packet = self._read_packet()
  806. elif auth_packet.is_extra_auth_data():
  807. if DEBUG:
  808. print("received extra data")
  809. # https://dev.mysql.com/doc/internals/en/successful-authentication.html
  810. if self._auth_plugin_name == "caching_sha2_password":
  811. auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
  812. elif self._auth_plugin_name == "sha256_password":
  813. auth_packet = _auth.sha256_password_auth(self, auth_packet)
  814. else:
  815. raise err.OperationalError(
  816. "Received extra packet for auth method %r", self._auth_plugin_name
  817. )
  818. if DEBUG:
  819. print("Succeed to auth")
  820. def _process_auth(self, plugin_name, auth_packet):
  821. handler = self._get_auth_plugin_handler(plugin_name)
  822. if handler:
  823. try:
  824. return handler.authenticate(auth_packet)
  825. except AttributeError:
  826. if plugin_name != b"dialog":
  827. raise err.OperationalError(
  828. 2059,
  829. "Authentication plugin '%s'"
  830. " not loaded: - %r missing authenticate method"
  831. % (plugin_name, type(handler)),
  832. )
  833. if plugin_name == b"caching_sha2_password":
  834. return _auth.caching_sha2_password_auth(self, auth_packet)
  835. elif plugin_name == b"sha256_password":
  836. return _auth.sha256_password_auth(self, auth_packet)
  837. elif plugin_name == b"mysql_native_password":
  838. data = _auth.scramble_native_password(self.password, auth_packet.read_all())
  839. elif plugin_name == b"client_ed25519":
  840. data = _auth.ed25519_password(self.password, auth_packet.read_all())
  841. elif plugin_name == b"mysql_old_password":
  842. data = (
  843. _auth.scramble_old_password(self.password, auth_packet.read_all())
  844. + b"\0"
  845. )
  846. elif plugin_name == b"mysql_clear_password":
  847. # https://dev.mysql.com/doc/internals/en/clear-text-authentication.html
  848. data = self.password + b"\0"
  849. elif plugin_name == b"dialog":
  850. pkt = auth_packet
  851. while True:
  852. flag = pkt.read_uint8()
  853. echo = (flag & 0x06) == 0x02
  854. last = (flag & 0x01) == 0x01
  855. prompt = pkt.read_all()
  856. if prompt == b"Password: ":
  857. self.write_packet(self.password + b"\0")
  858. elif handler:
  859. resp = "no response - TypeError within plugin.prompt method"
  860. try:
  861. resp = handler.prompt(echo, prompt)
  862. self.write_packet(resp + b"\0")
  863. except AttributeError:
  864. raise err.OperationalError(
  865. 2059,
  866. "Authentication plugin '%s'"
  867. " not loaded: - %r missing prompt method"
  868. % (plugin_name, handler),
  869. )
  870. except TypeError:
  871. raise err.OperationalError(
  872. 2061,
  873. "Authentication plugin '%s'"
  874. " %r didn't respond with string. Returned '%r' to prompt %r"
  875. % (plugin_name, handler, resp, prompt),
  876. )
  877. else:
  878. raise err.OperationalError(
  879. 2059,
  880. "Authentication plugin '%s' (%r) not configured"
  881. % (plugin_name, handler),
  882. )
  883. pkt = self._read_packet()
  884. pkt.check_error()
  885. if pkt.is_ok_packet() or last:
  886. break
  887. return pkt
  888. else:
  889. raise err.OperationalError(
  890. 2059, "Authentication plugin '%s' not configured" % plugin_name
  891. )
  892. self.write_packet(data)
  893. pkt = self._read_packet()
  894. pkt.check_error()
  895. return pkt
  896. def _get_auth_plugin_handler(self, plugin_name):
  897. plugin_class = self._auth_plugin_map.get(plugin_name)
  898. if not plugin_class and isinstance(plugin_name, bytes):
  899. plugin_class = self._auth_plugin_map.get(plugin_name.decode("ascii"))
  900. if plugin_class:
  901. try:
  902. handler = plugin_class(self)
  903. except TypeError:
  904. raise err.OperationalError(
  905. 2059,
  906. "Authentication plugin '%s'"
  907. " not loaded: - %r cannot be constructed with connection object"
  908. % (plugin_name, plugin_class),
  909. )
  910. else:
  911. handler = None
  912. return handler
  913. # _mysql support
  914. def thread_id(self):
  915. return self.server_thread_id[0]
  916. def character_set_name(self):
  917. return self.charset
  918. def get_host_info(self):
  919. return self.host_info
  920. def get_proto_info(self):
  921. return self.protocol_version
  922. def _get_server_information(self):
  923. i = 0
  924. packet = self._read_packet()
  925. data = packet.get_all_data()
  926. self.protocol_version = data[i]
  927. i += 1
  928. server_end = data.find(b"\0", i)
  929. self.server_version = data[i:server_end].decode("latin1")
  930. i = server_end + 1
  931. self.server_thread_id = struct.unpack("<I", data[i : i + 4])
  932. i += 4
  933. self.salt = data[i : i + 8]
  934. i += 9 # 8 + 1(filler)
  935. self.server_capabilities = struct.unpack("<H", data[i : i + 2])[0]
  936. i += 2
  937. if len(data) >= i + 6:
  938. lang, stat, cap_h, salt_len = struct.unpack("<BHHB", data[i : i + 6])
  939. i += 6
  940. # TODO: deprecate server_language and server_charset.
  941. # mysqlclient-python doesn't provide it.
  942. self.server_language = lang
  943. try:
  944. self.server_charset = charset_by_id(lang).name
  945. except KeyError:
  946. # unknown collation
  947. self.server_charset = None
  948. self.server_status = stat
  949. if DEBUG:
  950. print("server_status: %x" % stat)
  951. self.server_capabilities |= cap_h << 16
  952. if DEBUG:
  953. print("salt_len:", salt_len)
  954. salt_len = max(12, salt_len - 9)
  955. # reserved
  956. i += 10
  957. if len(data) >= i + salt_len:
  958. # salt_len includes auth_plugin_data_part_1 and filler
  959. self.salt += data[i : i + salt_len]
  960. i += salt_len
  961. i += 1
  962. # AUTH PLUGIN NAME may appear here.
  963. if self.server_capabilities & CLIENT.PLUGIN_AUTH and len(data) >= i:
  964. # Due to Bug#59453 the auth-plugin-name is missing the terminating
  965. # NUL-char in versions prior to 5.5.10 and 5.6.2.
  966. # ref: https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake
  967. # didn't use version checks as mariadb is corrected and reports
  968. # earlier than those two.
  969. server_end = data.find(b"\0", i)
  970. if server_end < 0: # pragma: no cover - very specific upstream bug
  971. # not found \0 and last field so take it all
  972. self._auth_plugin_name = data[i:].decode("utf-8")
  973. else:
  974. self._auth_plugin_name = data[i:server_end].decode("utf-8")
  975. def get_server_info(self):
  976. return self.server_version
  977. Warning = err.Warning
  978. Error = err.Error
  979. InterfaceError = err.InterfaceError
  980. DatabaseError = err.DatabaseError
  981. DataError = err.DataError
  982. OperationalError = err.OperationalError
  983. IntegrityError = err.IntegrityError
  984. InternalError = err.InternalError
  985. ProgrammingError = err.ProgrammingError
  986. NotSupportedError = err.NotSupportedError
  987. class MySQLResult:
  988. def __init__(self, connection):
  989. """
  990. :type connection: Connection
  991. """
  992. self.connection = connection
  993. self.affected_rows = None
  994. self.insert_id = None
  995. self.server_status = None
  996. self.warning_count = 0
  997. self.message = None
  998. self.field_count = 0
  999. self.description = None
  1000. self.rows = None
  1001. self.has_next = None
  1002. self.unbuffered_active = False
  1003. def __del__(self):
  1004. if self.unbuffered_active:
  1005. self._finish_unbuffered_query()
  1006. def read(self):
  1007. try:
  1008. first_packet = self.connection._read_packet()
  1009. if first_packet.is_ok_packet():
  1010. self._read_ok_packet(first_packet)
  1011. elif first_packet.is_load_local_packet():
  1012. self._read_load_local_packet(first_packet)
  1013. else:
  1014. self._read_result_packet(first_packet)
  1015. finally:
  1016. self.connection = None
  1017. def init_unbuffered_query(self):
  1018. """
  1019. :raise OperationalError: If the connection to the MySQL server is lost.
  1020. :raise InternalError:
  1021. """
  1022. self.unbuffered_active = True
  1023. first_packet = self.connection._read_packet()
  1024. if first_packet.is_ok_packet():
  1025. self._read_ok_packet(first_packet)
  1026. self.unbuffered_active = False
  1027. self.connection = None
  1028. elif first_packet.is_load_local_packet():
  1029. self._read_load_local_packet(first_packet)
  1030. self.unbuffered_active = False
  1031. self.connection = None
  1032. else:
  1033. self.field_count = first_packet.read_length_encoded_integer()
  1034. self._get_descriptions()
  1035. # Apparently, MySQLdb picks this number because it's the maximum
  1036. # value of a 64bit unsigned integer. Since we're emulating MySQLdb,
  1037. # we set it to this instead of None, which would be preferred.
  1038. self.affected_rows = 18446744073709551615
  1039. def _read_ok_packet(self, first_packet):
  1040. ok_packet = OKPacketWrapper(first_packet)
  1041. self.affected_rows = ok_packet.affected_rows
  1042. self.insert_id = ok_packet.insert_id
  1043. self.server_status = ok_packet.server_status
  1044. self.warning_count = ok_packet.warning_count
  1045. self.message = ok_packet.message
  1046. self.has_next = ok_packet.has_next
  1047. def _read_load_local_packet(self, first_packet):
  1048. if not self.connection._local_infile:
  1049. raise RuntimeError(
  1050. "**WARN**: Received LOAD_LOCAL packet but local_infile option is false."
  1051. )
  1052. load_packet = LoadLocalPacketWrapper(first_packet)
  1053. sender = LoadLocalFile(load_packet.filename, self.connection)
  1054. try:
  1055. sender.send_data()
  1056. except:
  1057. self.connection._read_packet() # skip ok packet
  1058. raise
  1059. ok_packet = self.connection._read_packet()
  1060. if (
  1061. not ok_packet.is_ok_packet()
  1062. ): # pragma: no cover - upstream induced protocol error
  1063. raise err.OperationalError(2014, "Commands Out of Sync")
  1064. self._read_ok_packet(ok_packet)
  1065. def _check_packet_is_eof(self, packet):
  1066. if not packet.is_eof_packet():
  1067. return False
  1068. # TODO: Support CLIENT.DEPRECATE_EOF
  1069. # 1) Add DEPRECATE_EOF to CAPABILITIES
  1070. # 2) Mask CAPABILITIES with server_capabilities
  1071. # 3) if server_capabilities & CLIENT.DEPRECATE_EOF: use OKPacketWrapper instead of EOFPacketWrapper
  1072. wp = EOFPacketWrapper(packet)
  1073. self.warning_count = wp.warning_count
  1074. self.has_next = wp.has_next
  1075. return True
  1076. def _read_result_packet(self, first_packet):
  1077. self.field_count = first_packet.read_length_encoded_integer()
  1078. self._get_descriptions()
  1079. self._read_rowdata_packet()
  1080. def _read_rowdata_packet_unbuffered(self):
  1081. # Check if in an active query
  1082. if not self.unbuffered_active:
  1083. return
  1084. # EOF
  1085. packet = self.connection._read_packet()
  1086. if self._check_packet_is_eof(packet):
  1087. self.unbuffered_active = False
  1088. self.connection = None
  1089. self.rows = None
  1090. return
  1091. row = self._read_row_from_packet(packet)
  1092. self.affected_rows = 1
  1093. self.rows = (row,) # rows should tuple of row for MySQL-python compatibility.
  1094. return row
  1095. def _finish_unbuffered_query(self):
  1096. # After much reading on the MySQL protocol, it appears that there is,
  1097. # in fact, no way to stop MySQL from sending all the data after
  1098. # executing a query, so we just spin, and wait for an EOF packet.
  1099. while self.unbuffered_active:
  1100. packet = self.connection._read_packet()
  1101. if self._check_packet_is_eof(packet):
  1102. self.unbuffered_active = False
  1103. self.connection = None # release reference to kill cyclic reference.
  1104. def _read_rowdata_packet(self):
  1105. """Read a rowdata packet for each data row in the result set."""
  1106. rows = []
  1107. while True:
  1108. packet = self.connection._read_packet()
  1109. if self._check_packet_is_eof(packet):
  1110. self.connection = None # release reference to kill cyclic reference.
  1111. break
  1112. rows.append(self._read_row_from_packet(packet))
  1113. self.affected_rows = len(rows)
  1114. self.rows = tuple(rows)
  1115. def _read_row_from_packet(self, packet):
  1116. row = []
  1117. for encoding, converter in self.converters:
  1118. try:
  1119. data = packet.read_length_coded_string()
  1120. except IndexError:
  1121. # No more columns in this row
  1122. # See https://github.com/PyMySQL/PyMySQL/pull/434
  1123. break
  1124. if data is not None:
  1125. if encoding is not None:
  1126. data = data.decode(encoding)
  1127. if DEBUG:
  1128. print("DEBUG: DATA = ", data)
  1129. if converter is not None:
  1130. data = converter(data)
  1131. row.append(data)
  1132. return tuple(row)
  1133. def _get_descriptions(self):
  1134. """Read a column descriptor packet for each column in the result."""
  1135. self.fields = []
  1136. self.converters = []
  1137. use_unicode = self.connection.use_unicode
  1138. conn_encoding = self.connection.encoding
  1139. description = []
  1140. for i in range(self.field_count):
  1141. field = self.connection._read_packet(FieldDescriptorPacket)
  1142. self.fields.append(field)
  1143. description.append(field.description())
  1144. field_type = field.type_code
  1145. if use_unicode:
  1146. if field_type == FIELD_TYPE.JSON:
  1147. # When SELECT from JSON column: charset = binary
  1148. # When SELECT CAST(... AS JSON): charset = connection encoding
  1149. # This behavior is different from TEXT / BLOB.
  1150. # We should decode result by connection encoding regardless charsetnr.
  1151. # See https://github.com/PyMySQL/PyMySQL/issues/488
  1152. encoding = conn_encoding # SELECT CAST(... AS JSON)
  1153. elif field_type in TEXT_TYPES:
  1154. if field.charsetnr == 63: # binary
  1155. # TEXTs with charset=binary means BINARY types.
  1156. encoding = None
  1157. else:
  1158. encoding = conn_encoding
  1159. else:
  1160. # Integers, Dates and Times, and other basic data is encoded in ascii
  1161. encoding = "ascii"
  1162. else:
  1163. encoding = None
  1164. converter = self.connection.decoders.get(field_type)
  1165. if converter is converters.through:
  1166. converter = None
  1167. if DEBUG:
  1168. print(f"DEBUG: field={field}, converter={converter}")
  1169. self.converters.append((encoding, converter))
  1170. eof_packet = self.connection._read_packet()
  1171. assert eof_packet.is_eof_packet(), "Protocol error, expecting EOF"
  1172. self.description = tuple(description)
  1173. class LoadLocalFile:
  1174. def __init__(self, filename, connection):
  1175. self.filename = filename
  1176. self.connection = connection
  1177. def send_data(self):
  1178. """Send data packets from the local file to the server"""
  1179. if not self.connection._sock:
  1180. raise err.InterfaceError(0, "")
  1181. conn = self.connection
  1182. try:
  1183. with open(self.filename, "rb") as open_file:
  1184. packet_size = min(
  1185. conn.max_allowed_packet, 16 * 1024
  1186. ) # 16KB is efficient enough
  1187. while True:
  1188. chunk = open_file.read(packet_size)
  1189. if not chunk:
  1190. break
  1191. conn.write_packet(chunk)
  1192. except IOError:
  1193. raise err.OperationalError(1017, f"Can't find file '{self.filename}'")
  1194. finally:
  1195. # send the empty packet to signify we are done sending data
  1196. conn.write_packet(b"")