Skip to main content

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

Project description

SQL Stacktrace Context Manager

A utility for adding Python stacktraces to Django SQL queries as comments.

This can help figuring out where are queries getting triggered from, for example for tracking down N+1 queries.

Features

  • Targeted Application: Apply stacktraces only where needed, rather than globally
  • Multiple Interfaces: Available as a function-based context manager, class-based context manager, or decorator
  • Test Compatible: Works seamlessly with Django's assertNumQueries and other test utilities
  • Stacktrace Filtering: Focuses on application code by filtering out framework/library frames

Usage

As a Context Manager

from sql_traceback import sql_traceback, SqlTraceback

# Function-based style
with sql_traceback():
    # Queries here will have stacktraces added
    user = User.objects.select_related('profile').get(id=1)
    user.profile.do_a_thing()

# or

with SqlTraceback():
    # Queries here will have stacktraces added
    user = User.objects.select_related('profile').get(id=1)
    user.profile.do_a_thing()

With Django Tests

My preferred usecase as this will print out the location of the n+1 query (if there is one)

from django.test import TestCase
from sql_traceback import sql_traceback

class MyTest(TestCase):
    def test_something(self):
        with sql_traceback(), self.assertNumQueries(1):
            user = User.objects.select_related('profile').get(id=1)
            user.profile.do_a_thing()

As a Decorator

from sql_traceback import SqlTraceback

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

Example SQL query Output

SELECT "auth_user"."id", "auth_user"."username" FROM "auth_user" LIMIT 1;
/*
STACKTRACE:
# /path/to/my_project/my_app/views.py:42 in get_user
# /path/to/my_project/my_app/services.py:23 in fetch_data
*/;

Configuration

The context manager behavior can be controlled through environment variables:

  • ENABLE_SQL_TRACEBACK=1 - Enable/disable stacktrace generation (default: enabled)
  • PRINT_SQL_TRACEBACKS=1 - Print stacktraces to stderr during tests (default: disabled)

Development

Running Tests

This project uses tox to test against multiple database backends (SQLite, PostgreSQL, MySQL) and multiple Python versions (3.10, 3.11, 3.12, 3.13).

📚 For detailed testing documentation, see TESTING.md 🚀 For quick setup instructions, see QUICKSTART.md

Quick Start

# Build test container (one-time setup)
make build

# Start database containers
make up

# Run all tests (21 environments)
make test

# Or test specific combinations
make test TOX_ENV=py312-django52-sqlite
make test TOX_ENV=py312-django52-postgres
make test TOX_ENV=py310-django42-mysql

No Local Dependencies Needed!

All tests run inside Docker with UV managing multiple Python versions and tox handling test environments. Database drivers (psycopg, mysqlclient) are pre-installed in the container.

Test Specific Combinations

# Single environment
make test TOX_ENV=py312-django52-postgres
make test TOX_ENV=py313-django52-mysql

# Multiple environments
make test TOX_ENV="py312-django{42,52}-sqlite"

# All Django 5.2 environments
make test TOX_ENV="py{310,311,312,313}-django52-{sqlite,postgres,mysql}"

# See all available environments
docker-compose run --rm test tox list

Available Commands

make help              # Show all available commands and examples
make test              # Run all tests (21 environments)
make test TOX_ENV=...  # Run specific environment(s)
make build             # Build test container
make up                # Start database containers
make down              # Stop containers
make clean             # Remove containers and volumes
make shell             # Open shell in test container

CI/CD

The project uses GitHub Actions with a test matrix covering:

  • Python versions: 3.10, 3.11, 3.12, 3.13
  • Django versions: 4.2 LTS, 5.2 LTS
  • Databases: SQLite, PostgreSQL, MySQL
  • Total: 21 test combinations run in parallel

The CI uses the same Docker + tox setup as local development, ensuring consistency.

See the GitHub Actions workflow for implementation details.

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.1.0.tar.gz (6.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.1.0-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for django_traceback_in_sql-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d85ddd78e40c0b2ad88ccad464d48a8eb14dadb0dc1b31bdd4f69e8f7a952705
MD5 9fbf6f7b26779a6f4df5873f0e7ebc42
BLAKE2b-256 2853c82a3e10974a7ae09ff901d563fc065795979c172a147806ab374138140c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_traceback_in_sql-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 89a4aac392c3d03e316eec7826950584536ca18e9d136ed6d59523c0130f545c
MD5 290143e09c2b34d46c8e94af8ca58a5a
BLAKE2b-256 36a6879b8819ccc567006c17dfb290b87ad3056c12c8bd2692235b3d9dc76a31

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