Login

Query printer coroutine

Author:
fnl
Posted:
April 25, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

If you would like to see the latest queries you have done when running a unittest, this is not so easy. You have to initialize the queries list and set DEBUG to True manually. Then you have to figure out a way to print the queries you want to see just now and format them. I.e., monitoring queries when doing TDD is a bit of a hassle, and this should help.

This little helper does all this for you; your UnitTest only needs to import django.db.connection and store the current length (offset) of the queries list. Then, using Python's coroutine functionality, all you have to do is send that offset to the QueryPrinter coroutine (which you can, for example, initialize as a global variable or a class variable of your UnitTest) and you get the latest SQL printed as a simple table.

 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Debugging queries in django for Django."""

from django.conf import settings
from django.db import connection

def coroutine(func):
    def start(*args, **kwargs):
        cr = func(*args, **kwargs)
        cr.next()
        return cr
    return start

@coroutine
def QueryPrinter():
    """Initialize a query printer coroutine.
    
    Example use:
    >>> query_printer = QueryPrinter()
    >>> offset = len(conntection.queries)
    >>> # do some stuff that creates SQL queries
    >>> query_printer.send(offset)
    
    Now it would print the queries if this example had some. Example Output
    looks like:
    
    2 QUERIES AT OFFSET 556
    Time/s | SQL
    00.006 | 'SELECT ...'
    00.006 | 'INSERT INTO ...'
    """
    connection.queries = []
    settings.DEBUG = True
    offset = 0
    
    while True:
        diff = len(connection.queries) - offset
        
        if diff:
            print diff, "QUERIES AT OFFSET", offset
            print "Time/s | SQL"
            
            for query in connection.queries[offset:]:
                print "%06.3f | '%s'" % (float(query['time']), query['sql'])
        offset = (yield)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.