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 sql_traceback import sql_traceback

with sql_traceback():
    user = User.objects.select_related('profile').get(id=1)
    user.profile.do_something()

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.1.tar.gz (12.7 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.1-py3-none-any.whl (18.8 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for django_traceback_in_sql-0.2.1.tar.gz
Algorithm Hash digest
SHA256 dc39a25526677279deba8aeb6c2d3d70cdd848ae6738e30e5690049d674ca070
MD5 ac5e4d1fbb2e7e5745f05ba742623b4c
BLAKE2b-256 2fad53a8187a01032d3f6f1d37e1edffaf350ff7ea57a5cf4bfa83014c1e7aa4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_traceback_in_sql-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a4212973e46f4f70f2579cff364e854a8eb19dad5d93fc9bc1a07718c167b13a
MD5 d6a81e7c20ac88f5962d490aff1cc307
BLAKE2b-256 d14e9292779a74809e42ec1c65763c5d805f4ea8f801c81c105270959065e2a6

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