connections.py 52 KB

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