Skip to content

Commit

Permalink
feat: collapse whitespace in multiline sql (#20)
Browse files Browse the repository at this point in the history
When used in conjunction with the colorizing output, only the first line of the SQL is colored. This is due to the logging filter assuming anything after the first line is a traceback; something to present in without color. Unfortunately, this breaks the intent of the SQL logging.

Linebreaks in SQL logging aren't important. Getting rid of them doesn't hurt readability. In fact, even without the colorization, readability is improved because more lines fit on one screen.

This does not catch all SQL with line breaks... I'll have to update the logic again later if I care.
  • Loading branch information
crccheck authored Apr 5, 2023
1 parent d1e475f commit 64c3ca9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion project_runpy/heidi.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ class ReadableSqlFilter(logging.Filter):

def filter(self, record):
# https://github.com/django/django/blob/febe136d4c3310ec8901abecca3ea5ba2be3952c/django/db/backends/utils.py#L106-L131
duration, sql, *__ = record.args
duration, sql, *record_args = record.args
if sql and "\n" in sql[:28]:
sql = " ".join(sql.strip().split())
record.args = (duration, sql, *record_args)
if not sql or "SELECT" not in sql[:28]:
# WISHLIST what's the most performant way to see if 'SELECT' was
# used?
Expand Down
19 changes: 19 additions & 0 deletions test_project_runpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,25 @@ def test_filter_formats_ignores_select_without_from(self):
self.assertTrue(logging_filter.filter(record))
self.assertEqual(original_sql, record.args[1])

def test_filter_collapses_multiline_sql(self):
long_sql = """
(0.002)
SELECT VERSION(),
@@sql_mode,
@@default_storage_engine,
@@sql_auto_is_null,
@@lower_case_table_names,
CONVERT_TZ('2001-01-01 01:00:00', 'UTC', 'UTC') IS NOT NULL
; args=None
"""
logging_filter = ReadableSqlFilter()
record = mock.MagicMock(args=(1.0, long_sql))
self.assertIn("\n", record.args[1])

self.assertTrue(logging_filter.filter(record))

self.assertNotIn("\n", record.args[1])


if __name__ == "__main__":
unittest.main()

0 comments on commit 64c3ca9

Please sign in to comment.