Skip to content

Commit 72a20d4

Browse files
committed
fix pattern lookup match escaping on F expressions
Escape $regexMatch special characters instead of LIKE special chars.
1 parent e39c032 commit 72a20d4

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

django_mongodb/lookups.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,28 @@ def is_null(self, compiler, connection):
4646
return connection.mongo_operators["isnull"](lhs_mql, self.rhs)
4747

4848

49+
# from https://www.pcre.org/current/doc/html/pcre2pattern.html#SEC4
50+
REGEX_MATCH_ESCAPE_CHARS = (
51+
("\\", r"\\"), # general escape character
52+
("^", r"\^"), # start of string
53+
({"$literal": "$"}, r"\$"), # end of string
54+
(".", r"\."), # match any character
55+
("[", r"\["), # start character class definition
56+
("|", r"\|"), # start of alternative branch
57+
("(", r"\("), # start group or control verb
58+
(")", r"\)"), # end group or control verb
59+
("*", r"\*"), # 0 or more quantifier
60+
("+", r"\+"), # 1 or more quantifier
61+
("?", r"\?"), # 0 or 1 quantifier
62+
("{", r"\}"), # start min/max quantifier
63+
)
64+
65+
4966
def pattern_lookup_prep_lookup_value(self, value):
5067
if hasattr(self.rhs, "as_mql"):
51-
# If value is a column reference, escape regex special characters.
68+
# If value is a column reference, escape $regexMatch special chars.
5269
# Analogous to PatternLookup.get_rhs_op() / pattern_esc.
53-
for find, replacement in (("\\", r"\\"), ("%", r"\%"), ("_", r"\_")):
70+
for find, replacement in REGEX_MATCH_ESCAPE_CHARS:
5471
value = {"$replaceAll": {"input": value, "find": find, "replacement": replacement}}
5572
else:
5673
# If value is a literal, remove percent signs added by

0 commit comments

Comments
 (0)