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.2.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.2-py3-none-any.whl (32.0 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for django_traceback_in_sql-0.2.2.tar.gz
Algorithm Hash digest
SHA256 55dff1a18c99ad7c9c7397853295bf30fb93174c7058151c20aee23500509d6a
MD5 a6d387b966d56ffecd51a6e4b467973b
BLAKE2b-256 da716d24b5cf474603e7b969aad2203aa859cfc9f9e896283eacfff25e758885

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_traceback_in_sql-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 be772760b44d3d8c4ec088874b8494708e61088d809a0f1d1fb6285fca4e1878
MD5 7b6111713b66b6fd543c90a9ebb53eec
BLAKE2b-256 56a089659c9ca29f747b196875132bb92b80623f9fb358f9a9ee2f3be23d034c

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