Permalink
Browse files

Added an option to shell_plus to print SQL queries

shell_plus with --print-sql will print SQL queries as they're issued
  • Loading branch information...
1 parent d5b33b3 commit 541b564281fe7e4108c524ea2b141766d8c2702c @acdha acdha committed with jezdez Mar 12, 2010
Showing with 29 additions and 5 deletions.
  1. +29 −5 django_extensions/management/commands/shell_plus.py
@@ -10,6 +10,8 @@ class Command(NoArgsCommand):
help='Tells Django to use plain Python, not BPython nor IPython.'),
make_option('--no-pythonrc', action='store_true', dest='no_pythonrc',
help='Tells Django to use plain Python, not IPython.'),
+ make_option('--print-sql', action='store_true', default=False,
+ help="Print SQL queries as they're executed"),
)
help = "Like the 'shell' command but autoloads the models of all installed Django apps."
@@ -26,6 +28,28 @@ def handle_noargs(self, **options):
use_plain = options.get('plain', False)
use_pythonrc = not options.get('no_pythonrc', True)
+ if options.get("print_sql", False):
+ # Code from http://gist.github.com/118990
+ from django.db.backends import util
+ try:
+ import sqlparse
+ except ImportError:
+ sqlparse = None
+
+ class PrintQueryWrapper(util.CursorDebugWrapper):
+ def execute(self, sql, params=()):
+ try:
+ return self.cursor.execute(sql, params)
+ finally:
+ raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params)
+ if sqlparse:
+ print sqlparse.format(raw_sql, reindent=True)
+ else:
+ print raw_sql
+ print
+
+ util.CursorDebugWrapper = PrintQueryWrapper
+
# Set up a dictionary to serve as the environment for the shell, so
# that tab completion works on objects that are imported at runtime.
# See ticket 5082.
@@ -80,11 +104,11 @@ def handle_noargs(self, **options):
# We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
# conventions and get $PYTHONSTARTUP first then import user.
if use_pythonrc:
- pythonrc = os.environ.get("PYTHONSTARTUP")
- if pythonrc and os.path.isfile(pythonrc):
- try:
- execfile(pythonrc)
- except NameError:
+ pythonrc = os.environ.get("PYTHONSTARTUP")
+ if pythonrc and os.path.isfile(pythonrc):
+ try:
+ execfile(pythonrc)
+ except NameError:
pass
# This will import .pythonrc.py as a side-effect
import user

0 comments on commit 541b564

Please sign in to comment.