Skip to content

Commit 47cff69

Browse files
committed
BUG22564149: Fix cmd_query_iter() when using bytestrings with Python 2
Executing cmd_query_iter() raises an exception when using bytestrings statements with Python 2. This patch verifies if the statements are already bytestrings before attempting to encode them. A test was added for regression.
1 parent c417153 commit 47cff69

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

lib/mysql/connector/connection.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
import time
3030

3131
from .authentication import get_auth_plugin
32-
from .catch23 import PY2, isstr
32+
from .catch23 import PY2, isstr, UNICODE_TYPES
3333
from .constants import (
3434
ClientFlag, ServerCmd, ServerFlag,
3535
flag_is_set, ShutdownType, NET_BUFFER_LENGTH
@@ -517,10 +517,9 @@ def cmd_query_iter(self, statements):
517517
Returns a generator.
518518
"""
519519
if not isinstance(statements, bytearray):
520-
if isstr(statements):
521-
statements = bytearray(statements.encode('utf-8'))
522-
else:
523-
statements = bytearray(statements)
520+
if isstr(statements) and isinstance(statements, UNICODE_TYPES):
521+
statements = statements.encode('utf8')
522+
statements = bytearray(statements)
524523

525524
# Handle the first query result
526525
yield self._handle_result(self._send_cmd(ServerCmd.QUERY, statements))

tests/test_bugs.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4433,3 +4433,30 @@ def test_parse_mysql_config(self):
44334433
self.assertEqual(2, len(info["include"]))
44344434
self.assertEqual(includes[0], info["include"][0])
44354435
self.assertEqual(includes[1], info["include"][1])
4436+
4437+
4438+
class BugOra22564149(tests.MySQLConnectorTests):
4439+
"""BUG#22564149: CMD_QUERY_ITER ERRONEOUSLY CALLS ".ENCODE('UTF8')" ON
4440+
BYTESTRINGS
4441+
"""
4442+
def setUp(self):
4443+
config = tests.get_mysql_config()
4444+
self.tbl = "BugOra22564149"
4445+
self.cnx = connection.MySQLConnection(**config)
4446+
self.cnx.cmd_query("DROP TABLE IF EXISTS {0}".format(self.tbl))
4447+
self.cnx.cmd_query("CREATE TABLE {0} (id INT, name VARCHAR(50))"
4448+
"".format(self.tbl))
4449+
4450+
def tearDown(self):
4451+
self.cnx.cmd_query("DROP TABLE IF EXISTS {0}".format(self.tbl))
4452+
self.cnx.close()
4453+
4454+
def test_cmd_query_iter(self):
4455+
stmt = (u"SELECT 1; INSERT INTO {0} VALUES (1, 'João'),(2, 'André'); "
4456+
u"SELECT 3")
4457+
results = []
4458+
for result in self.cnx.cmd_query_iter(
4459+
stmt.format(self.tbl).encode("utf-8")):
4460+
results.append(result)
4461+
if "columns" in result:
4462+
results.append(self.cnx.get_rows())

0 commit comments

Comments
 (0)