Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/MySQLdb/_mysql.c
Original file line number Diff line number Diff line change
Expand Up @@ -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.";
Expand All @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions tests/test__mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
6 changes: 4 additions & 2 deletions tests/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,)


Expand Down
Loading