Login

print SQL statements

Author:
zuzelvp
Posted:
February 9, 2010
Language:
Python
Version:
1.1
Tags:
sql runserver command
Score:
0 (after 0 ratings)

Modifies the as_sql methods to print the queries.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from optparse import make_option
import os
import types

from django.core.management.commands.runserver import Command as BaseCommand
from django.db.models.sql import query
from django.db.models.sql import subqueries


class Command(BaseCommand):
    help = "Works as runserver but prints every SQL statement used."

    def handle(self, *args, **kwargs):
        log_query(query.Query)
        log_query(subqueries.DeleteQuery)
        log_query(subqueries.InsertQuery)
        log_query(subqueries.UpdateQuery)
        super(Command, self).handle(*args, **kwargs)


def log_query(cls):
    original_as_sql = cls.as_sql.im_func
    def new_as_sql(*args, **kwargs):
        q, args = original_as_sql(*args, **kwargs)
        print q.replace('"', '') % args
        print
        return q, args
    cls.as_sql = types.MethodType(new_as_sql, None, cls)

More like this

  1. Pretty print SQL of query sets by peterbe 6 years ago
  2. SQL Log To Console Middleware by davepeck 5 years, 9 months ago
  3. Output sql_queries in Firebug console when in debug mode by wojas 5 years, 2 months ago
  4. SQL Printing Middleware by ericflo 7 years, 11 months ago
  5. Color SQL logging middleware by moe 7 years, 3 months ago

Comments

Please login first before commenting.