Query printer coroutine

 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 6 years, 3 months ago
  2. Variable._resolve_lookup monkeypatch by showell 4 years, 5 months ago
  3. a template tag to invoke a method on an object with a variable by Scanner 6 years, 11 months ago
  4. Output sql_queries in Firebug console when in debug mode by wojas 4 years, 1 month ago
  5. Unit Test Profiling by justquick 5 years, 2 months ago

Comments

(Forgotten your password?)