connections.py 48 KB

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