Skip to content

Optimize SQL reformatting #1574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 12, 2022
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
27 changes: 22 additions & 5 deletions debug_toolbar/panels/sql/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
from functools import lru_cache

import sqlparse
from django.utils.html import escape
Expand Down Expand Up @@ -32,22 +33,38 @@ def reformat_sql(sql, with_toggle=False):


def parse_sql(sql, aligned_indent=False):
return _parse_sql(
sql,
dt_settings.get_config()["PRETTIFY_SQL"],
aligned_indent,
)


@lru_cache(maxsize=128)
def _parse_sql(sql, pretty, aligned_indent):
stack = get_filter_stack(pretty, aligned_indent)
return "".join(stack.run(sql))


@lru_cache(maxsize=None)
def get_filter_stack(prettify, aligned_indent):
stack = sqlparse.engine.FilterStack()
if dt_settings.get_config()["PRETTIFY_SQL"]:
if prettify:
stack.enable_grouping()
if aligned_indent:
stack.stmtprocess.append(
sqlparse.filters.AlignedIndentFilter(char="&nbsp;", n="<br/>")
)
stack.preprocess.append(BoldKeywordFilter()) # add our custom filter
stack.postprocess.append(sqlparse.filters.SerializerUnicode()) # tokens -> strings
return "".join(stack.run(sql))
return stack


simplify_re = re.compile(r"SELECT</strong> (...........*?) <strong>FROM")


def simplify(sql):
expr = r"SELECT</strong> (...........*?) <strong>FROM"
sub = r"SELECT</strong> &#8226;&#8226;&#8226; <strong>FROM"
return re.sub(expr, sub, sql)
return simplify_re.sub(r"SELECT</strong> &#8226;&#8226;&#8226; <strong>FROM", sql)


def contrasting_color_generator():
Expand Down
2 changes: 1 addition & 1 deletion docs/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Next version
* Reset settings when overridden in tests. Packages or projects using
django-debug-toolbar can now use Django’s test settings tools, like
``@override_settings``, to reconfigure the toolbar during tests.
* Optimize rendering of SQL panel, saving about 15% of its run time.
* Optimize rendering of SQL panel, saving about 30% of its run time.

3.2.4 (2021-12-15)
------------------
Expand Down