Skip to content

Rename SQLPanel context var to control SQL access. #1615

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
May 3, 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
9 changes: 6 additions & 3 deletions debug_toolbar/panels/sql/tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
except ImportError:
PostgresJson = None

recording = contextvars.ContextVar("debug-toolbar-recording", default=True)
# Prevents SQL queries from being sent to the DB. It's used
# by the TemplatePanel to prevent the toolbar from issuing
# additional queries.
allow_sql = contextvars.ContextVar("debug-toolbar-allow-sql", default=True)


class SQLQueryTriggered(Exception):
Expand All @@ -32,7 +35,7 @@ def cursor(*args, **kwargs):
# See:
# https://github.com/jazzband/django-debug-toolbar/pull/615
# https://github.com/jazzband/django-debug-toolbar/pull/896
if recording.get():
if allow_sql.get():
wrapper = NormalCursorWrapper
else:
wrapper = ExceptionCursorWrapper
Expand All @@ -43,7 +46,7 @@ def chunked_cursor(*args, **kwargs):
# solves https://github.com/jazzband/django-debug-toolbar/issues/1239
cursor = connection._djdt_chunked_cursor(*args, **kwargs)
if not isinstance(cursor, BaseCursorWrapper):
if recording.get():
if allow_sql.get():
wrapper = NormalCursorWrapper
else:
wrapper = ExceptionCursorWrapper
Expand Down
6 changes: 3 additions & 3 deletions debug_toolbar/panels/templates/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from django.utils.translation import gettext_lazy as _

from debug_toolbar.panels import Panel
from debug_toolbar.panels.sql.tracking import SQLQueryTriggered, recording
from debug_toolbar.panels.sql.tracking import SQLQueryTriggered, allow_sql
from debug_toolbar.panels.templates import views

# Monkey-patch to enable the template_rendered signal. The receiver returns
Expand Down Expand Up @@ -118,7 +118,7 @@ def _store_template_info(self, sender, **kwargs):
value.model._meta.label,
)
else:
token = recording.set(False)
token = allow_sql.set(False)
try:
saferepr(value) # this MAY trigger a db query
except SQLQueryTriggered:
Expand All @@ -130,7 +130,7 @@ def _store_template_info(self, sender, **kwargs):
else:
temp_layer[key] = value
finally:
recording.reset(token)
allow_sql.reset(token)
pformatted = pformat(temp_layer)
self.pformat_layers.append((context_layer, pformatted))
context_list.append(pformatted)
Expand Down
15 changes: 8 additions & 7 deletions tests/panels/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

from ..base import BaseTestCase
from ..models import PostgresJSON
from ..sync import database_sync_to_async


def sql_call(use_iterator=False):
Expand Down Expand Up @@ -98,19 +97,21 @@ async def test_cursor_wrapper_async(self, mock_wrapper):
wraps=sql_tracking.NormalCursorWrapper,
)
async def test_cursor_wrapper_asyncio_ctx(self, mock_wrapper):
self.assertTrue(sql_tracking.recording.get())
self.assertTrue(sql_tracking.allow_sql.get())
await sync_to_async(sql_call)()

async def task():
sql_tracking.recording.set(False)
# Calling this in another context requires the db connections
# to be closed properly.
await database_sync_to_async(sql_call)()
sql_tracking.allow_sql.set(False)
# By disabling sql_tracking.allow_sql, we are indicating that any
# future SQL queries should be stopped. If SQL query occurs,
# it raises an exception.
with self.assertRaises(sql_tracking.SQLQueryTriggered):
await sync_to_async(sql_call)()

# Ensure this is called in another context
await asyncio.create_task(task())
# Because it was called in another context, it should not have affected ours
self.assertTrue(sql_tracking.recording.get())
self.assertTrue(sql_tracking.allow_sql.get())
self.assertEqual(mock_wrapper.call_count, 1)

def test_generate_server_timing(self):
Expand Down