Skip to content

Commit 41f49cf

Browse files
authored
Escape bytearray contents as bytes in string literals (#817)
Passing `bytearray(b'ab')` as a query parameter currently sends the Python text `bytearray(b'ab')` to the server. Escape the underlying two bytes so the parameter behaves like `b'ab'`. This also applies to `bytearray` subclasses. On free-threaded builds, the copy is protected by the bytearray's critical section. The new low-level tests failed before the fix and passed with the rebuilt CPython 3.14 wheel (32 tests passed locally). The updated database test checks the returned value with `binary_prefix` enabled and disabled and is left to CI. Ruff and `git diff --check` passed. Related discussion in #816. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * `bytearray` values are now handled consistently with `bytes` when creating SQL literals, including values containing quotes, null bytes, or backslashes. Subclasses are processed from their byte contents rather than their string representation. * **Documentation** * Clarified how `string_literal` handles byte-like values versus other objects. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent eef31ea commit 41f49cf

3 files changed

Lines changed: 27 additions & 5 deletions

File tree

‎src/MySQLdb/_mysql.c‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,9 +1194,8 @@ _mysql_escape_string(
11941194
static const char _mysql_string_literal__doc__[] =
11951195
"string_literal(obj) -- converts object obj into a SQL string literal.\n\
11961196
This means, any special SQL characters are escaped, and it is enclosed\n\
1197-
within single quotes. In other words, it performs:\n\
1198-
\n\
1199-
\"'%s'\" % escape_string(str(obj))\n\
1197+
within single quotes. For bytes and bytearray, the byte contents are\n\
1198+
escaped directly. Other objects are converted to strings first.\n\
12001199
\n\
12011200
Use connection.string_literal(obj), if you use it at all.\n\
12021201
_mysql.string_literal(obj) cannot handle character sets.";
@@ -1221,6 +1220,16 @@ _mysql_string_literal(
12211220
s = o;
12221221
Py_INCREF(s);
12231222
}
1223+
else if (PyByteArray_Check(o)) {
1224+
#ifdef Py_GIL_DISABLED
1225+
Py_BEGIN_CRITICAL_SECTION(o);
1226+
#endif
1227+
s = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(o), PyByteArray_GET_SIZE(o));
1228+
#ifdef Py_GIL_DISABLED
1229+
Py_END_CRITICAL_SECTION();
1230+
#endif
1231+
if (!s) goto error;
1232+
}
12241233
else {
12251234
PyObject *t = PyObject_Str(o);
12261235
if (!t) goto error;

‎tests/test__mysql.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@
44
from MySQLdb.connections import Connection
55

66

7+
@pytest.mark.parametrize("data", [b"", b"a'\x00\\\xffb"])
8+
def test_string_literal_bytearray(data):
9+
class Subclass(bytearray):
10+
def __str__(self):
11+
raise AssertionError("string_literal should use the byte contents")
12+
13+
expected = _mysql.string_literal(data)
14+
assert _mysql.string_literal(bytearray(data)) == expected
15+
assert _mysql.string_literal(Subclass(data)) == expected
16+
17+
718
def test_result_type():
819
with pytest.raises(TypeError):
920
_mysql.result(b"xyz")

‎tests/test_connection.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,13 @@ def test_literal_bytearray_subclass(binary_prefix):
4949
class Subclass(bytearray):
5050
pass
5151

52-
value = Subclass(b"BAR")
52+
data = b"A'\x00\\B"
53+
value = Subclass(data)
5354
with connection_factory(binary_prefix=binary_prefix) as conn:
55+
assert conn.literal(value) == conn.literal(data)
5456
cursor = conn.cursor()
5557
cursor.execute("SELECT %s", (value,))
56-
expected = str(value).encode(conn.encoding) if binary_prefix else str(value)
58+
expected = data if binary_prefix else data.decode(conn.encoding)
5759
assert cursor.fetchone() == (expected,)
5860

5961

0 commit comments

Comments
 (0)