Skip to content

Commit 411169d

Browse files
committed
Small review changes and hide SQL annotation behind a setting
1 parent 30cebbc commit 411169d

File tree

5 files changed

+54
-11
lines changed

5 files changed

+54
-11
lines changed

psqlextra/compiler.py

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import django
99

10+
from django.conf import settings
1011
from django.core.exceptions import SuspiciousOperation
1112
from django.db.models import Expression, Model, Q
1213
from django.db.models.fields.related import RelatedField
@@ -24,12 +25,43 @@
2425

2526

2627
def append_caller_to_sql(sql):
28+
"""Append the caller to SQL queries.
29+
30+
Adds the calling file and function as an SQL comment to each query.
31+
Examples:
32+
INSERT INTO "tests_47ee19d1" ("id", "title")
33+
VALUES (1, 'Test')
34+
RETURNING "tests_47ee19d1"."id"
35+
/* 998020 test_append_caller_to_sql_crud .../django-postgres-extra/tests/test_append_caller_to_sql.py 55 */
36+
37+
SELECT "tests_47ee19d1"."id", "tests_47ee19d1"."title"
38+
FROM "tests_47ee19d1"
39+
WHERE "tests_47ee19d1"."id" = 1
40+
LIMIT 1
41+
/* 998020 test_append_caller_to_sql_crud .../django-postgres-extra/tests/test_append_caller_to_sql.py 69 */
42+
43+
UPDATE "tests_47ee19d1"
44+
SET "title" = 'success'
45+
WHERE "tests_47ee19d1"."id" = 1
46+
/* 998020 test_append_caller_to_sql_crud .../django-postgres-extra/tests/test_append_caller_to_sql.py 64 */
47+
48+
DELETE FROM "tests_47ee19d1"
49+
WHERE "tests_47ee19d1"."id" IN (1)
50+
/* 998020 test_append_caller_to_sql_crud .../django-postgres-extra/tests/test_append_caller_to_sql.py 74 */
51+
52+
Slow and blocking queries could be easily tracked down to their originator
53+
within the source code using the "pg_stat_activity" table.
54+
55+
Enable "PSQLEXTRA_ANNOTATE_SQL" within the database settings to enable this feature.
56+
"""
57+
58+
if not getattr(settings, "PSQLEXTRA_ANNOTATE_SQL", None):
59+
return sql
60+
2761
try:
2862
# Search for the first non-Django caller
2963
stack = inspect.stack()
30-
i = 0
3164
for stack_frame in stack[1:]:
32-
i += 1
3365
frame_filename = stack_frame[1]
3466
frame_line = stack_frame[2]
3567
frame_function = stack_frame[3]
@@ -148,7 +180,6 @@ def as_sql(self, return_id=False):
148180
self._rewrite_insert(sql, params, return_id)
149181
for sql, params in super().as_sql()
150182
]
151-
print(f"InsertConflictCompiler {queries}")
152183

153184
return queries
154185

@@ -196,12 +227,11 @@ def _rewrite_insert(self, sql, params, return_id=False):
196227
self.qn(self.query.model._meta.pk.attname) if return_id else "*"
197228
)
198229

199-
if hasattr(self.query, "conflict_action"):
200-
(sql, params) = self._rewrite_insert_on_conflict(
201-
sql, params, self.query.conflict_action.value, returning
202-
)
230+
(sql, params) = self._rewrite_insert_on_conflict(
231+
sql, params, self.query.conflict_action.value, returning
232+
)
203233

204-
return (append_caller_to_sql(sql), params)
234+
return append_caller_to_sql(sql), params
205235

206236
def _rewrite_insert_on_conflict(
207237
self, sql, params, conflict_action: ConflictAction, returning

tests/test_append_caller_to_sql.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import pytest
22

33
from django.db import connection, models
4-
from django.test.utils import CaptureQueriesContext
4+
from django.test.utils import CaptureQueriesContext, override_settings
55

66
from psqlextra.compiler import append_caller_to_sql
77

@@ -22,27 +22,36 @@ def mockedFunction():
2222
return append_caller_to_sql("sql")
2323

2424

25+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=False)
26+
def test_disable_append_caller_to_sql():
27+
commented_sql = mockedFunction()
28+
assert commented_sql == "sql"
29+
30+
2531
@pytest.mark.parametrize(
2632
"entry_point",
2733
[
2834
MockedClass().mockedMethod,
2935
psqlextraSimulated().callMockedClass,
3036
],
3137
)
38+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=True)
3239
def test_append_caller_to_sql_class(entry_point):
3340
commented_sql = entry_point()
3441
assert commented_sql.startswith("sql /* ")
3542
assert "mockedMethod" in commented_sql
3643
assert __file__ in commented_sql
3744

3845

46+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=True)
3947
def test_append_caller_to_sql_function():
4048
commented_sql = mockedFunction()
4149
assert commented_sql.startswith("sql /* ")
4250
assert "mockedFunction" in commented_sql
4351
assert __file__ in commented_sql
4452

4553

54+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=True)
4655
def test_append_caller_to_sql_crud():
4756
model = get_fake_model(
4857
{

tests/test_on_conflict.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from django.core.exceptions import SuspiciousOperation
55
from django.db import connection, models
6-
from django.test.utils import CaptureQueriesContext
6+
from django.test.utils import CaptureQueriesContext, override_settings
77
from django.utils import timezone
88

99
from psqlextra.fields import HStoreField
@@ -14,6 +14,7 @@
1414

1515

1616
@pytest.mark.parametrize("conflict_action", ConflictAction.all())
17+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=True)
1718
def test_on_conflict(conflict_action):
1819
"""Tests whether simple inserts work correctly."""
1920

tests/test_query.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from django.db import connection, models
22
from django.db.models import Case, F, Q, Value, When
3-
from django.test.utils import CaptureQueriesContext
3+
from django.test.utils import CaptureQueriesContext, override_settings
44

55
from psqlextra.expressions import HStoreRef
66
from psqlextra.fields import HStoreField
@@ -137,6 +137,7 @@ def test_query_hstore_value_update_escape():
137137
assert inst.title.get("en") == "console.log('test')"
138138

139139

140+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=True)
140141
def test_query_comment():
141142
"""Tests whether the query is commented."""
142143

tests/test_view_models.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from django.core.exceptions import ImproperlyConfigured
44
from django.db import models
5+
from django.test.utils import override_settings
56

67
from psqlextra.models import PostgresMaterializedViewModel, PostgresViewModel
78

@@ -11,6 +12,7 @@
1112
@pytest.mark.parametrize(
1213
"model_base", [PostgresViewModel, PostgresMaterializedViewModel]
1314
)
15+
@override_settings(PSQLEXTRA_ANNOTATE_SQL=True)
1416
def test_view_model_meta_query_set(model_base):
1517
"""Tests whether you can set a :see:QuerySet to be used as the underlying
1618
query for a view."""

0 commit comments

Comments
 (0)