Skip to main content

Contextmanager for annotation the relevant stack trace to SQL queries as a comment

Project description

django-traceback-in-sql

Test Suite Ruff uv

PyPi Version image Supported Python Versions Supported Django versions

Annotates the stacktrace into the SQL query as a comment at runtime. Helpful for tracking down where queries are ran from within code, for example for analysing query counts in unit tests when trying to prevent N+1s.

Compatibility

  • Python 3.9–3.13
  • Django 4.2, 5.2
  • SQLite, PostgreSQL, MySQL

Quick Examples

Find N+1 queries in Django unit tests

from django.contrib.auth import get_user_model
from django.test import TestCase
from sql_traceback import sql_traceback


User = get_user_model()


class Test(TestCase):
    def test_something(self):
        with sql_traceback(), self.assertNumQueries(0):
            _ = User.objects.count()

If the assert gets triggered, you will see something like the following output:

E   AssertionError: 1 != 0 : 1 queries executed, 0 expected
E   Captured queries were:
E   1. SELECT COUNT(*) AS `__count` FROM `auth_user`
E   /*
E   STACKTRACE:
E   # /path/to/tests/test_test_test.py:12 in test_something
E   */

In pytest-django tests

The above equivalent would look like so

import pytest
from django.contrib.auth import get_user_model
from sql_traceback import sql_traceback


User = get_user_model()


@pytest.mark.django_db
def test_something(django_assert_num_queries):
    with sql_traceback(), django_assert_num_queries(0):
        _ = User.objects.count()

and when pytest is ran with the -v flag, you will see the following in the output

E               Queries:
E               ========
E
E               SELECT COUNT(*) AS `__count` FROM `auth_user`
E               /*
E               STACKTRACE:
E               # /path/to/tests/tests/test_test_test.py:12 in test_something
E               */

As a context manager

from django.db import connection
from sql_traceback import sql_traceback
from services import get_user_count

with sql_traceback():
    get_user_count()

print(connection.queries[-1]['sql'])

Should print output

SELECT COUNT(*) AS "__count" FROM "auth_user"
/*
STACKTRACE:
# /path/to/project/services.py:5 in get_user_count
*/

As a decorator

from sql_traceback import SqlTraceback

@SqlTraceback()
def get_users():
    return User.objects.filter(is_active=True)

Configuration

Optional settings in your Django settings.py:

SQL_TRACEBACK_ENABLED = True                      # Enable/disable stacktracing (default: True)
SQL_TRACEBACK_MAX_FRAMES = 15                     # Max number of stack frames (default: 15)
SQL_TRACEBACK_FILTER_SITEPACKAGES = True          # Filter out third-party packages (e.g., **django**, requests, pluggy, etc.) (default: True)
SQL_TRACEBACK_FILTER_TESTING_FRAMEWORKS = True    # Filter out pytest/unittest frames (pytest + unittest) (default: True)
SQL_TRACEBACK_FILTER_STDLIB = True                # Filter out Python standard library frames (e.g., threading, contextlib, etc.) (default: True)
SQL_TRACEBACK_MIN_APP_FRAMES = 1                  # Minimum application frames required (default: 1)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_traceback_in_sql-0.2.3.tar.gz (27.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_traceback_in_sql-0.2.3-py3-none-any.whl (32.1 kB view details)

Uploaded Python 3

File details

Details for the file django_traceback_in_sql-0.2.3.tar.gz.

File metadata

File hashes

Hashes for django_traceback_in_sql-0.2.3.tar.gz
Algorithm Hash digest
SHA256 f2211b7b0fcfe989714f597e732b5e9c3a876f675c142fa327e2070b6e2307e5
MD5 0b73bc3eef8e71683a7c58d3e2c486ba
BLAKE2b-256 50a156e6286dbb52a8d158e6ba87b88c964c31b2687571e09a3affbbe5ffc203

See more details on using hashes here.

File details

Details for the file django_traceback_in_sql-0.2.3-py3-none-any.whl.

File metadata

File hashes

Hashes for django_traceback_in_sql-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 67cc78b36dd082c13fb698b5c2066182913f2f05a944fafdc461bbf7bed9a7cb
MD5 d3a425c81d037d8bc5aedee18d7e0a19
BLAKE2b-256 5503829d5e2a5e5d6f6cb8c25cfe928eba0ad3942df70ff409e7eb81a3286ee4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page