Skip to content

Instantly share code, notes, and snippets.

@jemerick
Created June 2, 2010 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jemerick/422401 to your computer and use it in GitHub Desktop.
Save jemerick/422401 to your computer and use it in GitHub Desktop.
### Appending URL to SQL query for logging
via http://chris-lamb.co.uk/2010/06/01/appending-request-url-sql-statements-django/
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.
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('%', '%%')
break
f = f.f_back
return self.cursor.execute(sql, *args)
fn = BaseDatabaseWrapper.cursor
BaseDatabaseWrapper.cursor = lambda self: URLCursor(fn(self), self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment