Login

Query printer coroutine

Author:
fnl
Posted:
April 25, 2009
Language:
Python
Version:
1.0
Tags:
queries unittest debugging printing for connection
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. SQLLoggerMidleware + infobar by robvdl 7 years, 4 months ago
  2. Variable._resolve_lookup monkeypatch by showell 5 years, 6 months ago
  3. a template tag to invoke a method on an object with a variable by Scanner 8 years ago
  4. Output sql_queries in Firebug console when in debug mode by wojas 5 years, 2 months ago
  5. Unit Test Profiling by justquick 6 years, 3 months ago

Comments

Please login first before commenting.