Skip to content

Commit cd9a189

Browse files
committed
Replace sqlparse.filters.SerializerUnicode() usage
sqlparse's SerializerUnicode filter does a bunch of fancy whitespace processing which isn't needed because the resulting string will just be inserted into HTML. Replace with a simple EscapedStringSerializer that does nothing but convert the Statement to a properly-escaped string. In the process stop the escaping within BoldKeywordFilter to have a cleaner separation of concerns: BoldKeywordFilter now only handles marking up keywords as bold, while escaping is explicitly handled by the EscapedStringSerializer.
1 parent ee98c58 commit cd9a189

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

debug_toolbar/panels/sql/utils.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,27 @@ def process(self, stream):
1515
for token_type, value in stream:
1616
is_keyword = token_type in T.Keyword
1717
if is_keyword:
18-
yield T.Text, "<strong>"
19-
yield token_type, escape(value, quote=False)
18+
yield T.Other, "<strong>"
19+
yield token_type, value
2020
if is_keyword:
21-
yield T.Text, "</strong>"
21+
yield T.Other, "</strong>"
22+
23+
24+
def escaped_value(token):
25+
# Don't escape T.Whitespace tokens because AlignedIndentFilter inserts its tokens as
26+
# T.Whitesapce, and in our case those tokens are actually HTML.
27+
if token.ttype in (T.Other, T.Whitespace):
28+
return token.value
29+
return escape(token.value, quote=False)
30+
31+
32+
class EscapedStringSerializer:
33+
"""sqlparse post-processor to convert a Statement into a string escaped for
34+
inclusion in HTML ."""
35+
36+
@staticmethod
37+
def process(stmt):
38+
return "".join(escaped_value(token) for token in stmt.flatten())
2239

2340

2441
def reformat_sql(sql, with_toggle=False):
@@ -55,7 +72,7 @@ def get_filter_stack(prettify, aligned_indent):
5572
sqlparse.filters.AlignedIndentFilter(char="&nbsp;", n="<br/>")
5673
)
5774
stack.preprocess.append(BoldKeywordFilter())
58-
stack.postprocess.append(sqlparse.filters.SerializerUnicode()) # tokens -> strings
75+
stack.postprocess.append(EscapedStringSerializer()) # Statement -> str
5976
return stack
6077

6178

0 commit comments

Comments
 (0)