﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
36380	SQL is formatted for logging regardless of whether it will be logged	Jacob Walls	Jacob Walls	"I have an endpoint that generates several large SQL strings. It performs 10x worse (300ms -> 3000ms) on the main branch. Traced it to eager formatting of SQL.

To reproduce, print or throw inside `format_debug_sql()`, and run a project without logging queries (i.e. without a `django.db` entry in `LOGGING` configured at the `DEBUG` level).

{{{#!diff
diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py
index fea73bc1e4..4c106f59e3 100644
--- a/django/db/backends/base/operations.py
+++ b/django/db/backends/base/operations.py
@@ -791,4 +791,5 @@ class BaseDatabaseOperations:
 
     def format_debug_sql(self, sql):
         # Hook for backends (e.g. NoSQL) to customize formatting.
+        print('eager formatting...')
         return sqlparse.format(sql, reindent=True, keyword_case=""upper"")
}}}

Regression in d8f093908c504ae0dbc39d3f5231f7d7920dde37 (#35448).

We might want a benchmark in django-asv for views with long SQL strings?

This fix works for me; I can submit a patch with tests in the next few days:

{{{#!diff
diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py
index 568f510a67..ae810ffd12 100644
--- a/django/db/backends/utils.py
+++ b/django/db/backends/utils.py
@@ -10,6 +10,7 @@ from hashlib import md5
 from django.apps import apps
 from django.db import NotSupportedError
 from django.utils.dateparse import parse_time
+from django.utils.functional import lazy
 
 logger = logging.getLogger(""django.db.backends"")
 
@@ -151,7 +152,7 @@ class CursorDebugWrapper(CursorWrapper):
             logger.debug(
                 ""(%.3f) %s; args=%s; alias=%s"",
                 duration,
-                self.db.ops.format_debug_sql(sql),
+                lazy(self.db.ops.format_debug_sql)(sql),
                 params,
                 self.db.alias,
                 extra={
}}}"	Bug	assigned	Database layer (models, ORM)	dev	Release blocker		debug-sql	Tim Graham	Accepted	0	0	0	0	0	0
