From 0b6ee044b550303d2c4268cff63c184f7e1c58ce Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Wed, 18 Nov 2026 09:46:35 +0000 Subject: [PATCH] Escape bytearray contents as bytes in string literals --- src/MySQLdb/_mysql.c | 15 ++++++++++++--- tests/test__mysql.py | 11 +++++++++++ tests/test_connection.py | 6 ++++-- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/MySQLdb/_mysql.c b/src/MySQLdb/_mysql.c index 813a872c..7b54b575 100644 --- a/src/MySQLdb/_mysql.c +++ b/src/MySQLdb/_mysql.c @@ -1194,9 +1194,8 @@ _mysql_escape_string( static const char _mysql_string_literal__doc__[] = "string_literal(obj) -- converts object obj into a SQL string literal.\n\ This means, any special SQL characters are escaped, and it is enclosed\n\ -within single quotes. In other words, it performs:\n\ -\n\ -\"'%s'\" % escape_string(str(obj))\n\ +within single quotes. For bytes and bytearray, the byte contents are\n\ +escaped directly. Other objects are converted to strings first.\n\ \n\ Use connection.string_literal(obj), if you use it at all.\n\ _mysql.string_literal(obj) cannot handle character sets."; @@ -1221,6 +1220,16 @@ _mysql_string_literal( s = o; Py_INCREF(s); } + else if (PyByteArray_Check(o)) { +#ifdef Py_GIL_DISABLED + Py_BEGIN_CRITICAL_SECTION(o); +#endif + s = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(o), PyByteArray_GET_SIZE(o)); +#ifdef Py_GIL_DISABLED + Py_END_CRITICAL_SECTION(); +#endif + if (!s) goto error; + } else { PyObject *t = PyObject_Str(o); if (!t) goto error; diff --git a/tests/test__mysql.py b/tests/test__mysql.py index 0ef1fb94..bbb4f3c9 100644 --- a/tests/test__mysql.py +++ b/tests/test__mysql.py @@ -4,6 +4,17 @@ from MySQLdb.connections import Connection +@pytest.mark.parametrize("data", [b"", b"a'\x00\\\xffb"]) +def test_string_literal_bytearray(data): + class Subclass(bytearray): + def __str__(self): + raise AssertionError("string_literal should use the byte contents") + + expected = _mysql.string_literal(data) + assert _mysql.string_literal(bytearray(data)) == expected + assert _mysql.string_literal(Subclass(data)) == expected + + def test_result_type(): with pytest.raises(TypeError): _mysql.result(b"xyz") diff --git a/tests/test_connection.py b/tests/test_connection.py index ea6a1e46..6efacdd9 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -49,11 +49,13 @@ def test_literal_bytearray_subclass(binary_prefix): class Subclass(bytearray): pass - value = Subclass(b"BAR") + data = b"A'\x00\\B" + value = Subclass(data) with connection_factory(binary_prefix=binary_prefix) as conn: + assert conn.literal(value) == conn.literal(data) cursor = conn.cursor() cursor.execute("SELECT %s", (value,)) - expected = str(value).encode(conn.encoding) if binary_prefix else str(value) + expected = data if binary_prefix else data.decode(conn.encoding) assert cursor.fetchone() == (expected,)