Skip to content
Open
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
6 changes: 6 additions & 0 deletions pymysql/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,12 @@ def escape(self, obj, mapping=None) -> str:

if mapping is None:
mapping = self.encoders

# Types without an encoder fall back to escape_str, which always uses
# backslash escapes. Escape them here so NO_BACKSLASH_ESCAPES is respected.
if not mapping.get(type(obj)) and mapping.get(str) is converters.escape_str:
return f"'{self._escape_string(str(obj))}'"

return converters.escape_item(obj, self.encoding, mapping=mapping)

def literal(self, obj) -> str:
Expand Down
19 changes: 19 additions & 0 deletions pymysql/tests/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -963,6 +963,25 @@ class Custom(str):
mapping = {str: pymysql.converters.escape_string}
self.assertEqual(con.escape(Custom("foobar"), mapping), "'foobar'")

def test_escape_fallback_no_backslash_escapes(self):
con = self.connect()
cur = con.cursor()

class Custom:
def __init__(self, value):
self.value = value

def __str__(self):
return self.value

values = ("foo'bar", "foo\\bar", "foo\\' OR 1=1 -- ")
for sql_mode in ("", "NO_BACKSLASH_ESCAPES"):
cur.execute("SET sql_mode=%s", (sql_mode,))
for value in values:
with self.subTest(sql_mode=sql_mode, value=value):
cur.execute("SELECT %s", (Custom(value),))
self.assertEqual(cur.fetchone(), (value,))

def test_escape_no_default(self):
con = self.connect()

Expand Down