June 1st 2010

Appending the request URL to SQL statements in Django

import sys

from django.http import HttpRequest
from django.db.backends import BaseDatabaseWrapper, util

class URLCursor(util.CursorDebugWrapper):
    def execute(self, sql, *args):
        f = sys._getframe()
        while f:
            request = f.f_locals.get('request')
            if isinstance(request, HttpRequest):
                sql += ' -- %s' % repr(request.path)[2:-1].replace('%', '%%')
            f = f.f_back

        return self.cursor.execute(sql, *args)

fn = BaseDatabaseWrapper.cursor
BaseDatabaseWrapper.cursor = lambda self: URLCursor(fn(self), self)

Now your SQL statements look like:

SELECT "auth_user"."id", [..] WHERE "auth_user"."id" = 1 -- /login

This allows you to quickly go from a misbehaving query in your production environment to the view that is executing it.

You can subscribe to new posts via email or RSS.