/
debugsqlshell.py
28 lines (22 loc) · 976 Bytes
/
debugsqlshell.py
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 time import time
import sqlparse
from django.core.management.commands.shell import Command # noqa
from django.db import connection
from django.db.backends import utils as db_backends_utils
from django.db.backends.postgresql import base as psql_base
# 'debugsqlshell' is the same as the 'shell'.
class PrintQueryWrapper(db_backends_utils.CursorDebugWrapper):
def execute(self, sql, params=()):
start_time = time()
try:
return self.cursor.execute(sql, params)
finally:
raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params)
end_time = time()
duration = (end_time - start_time) * 1000
formatted_sql = sqlparse.format(raw_sql, reindent=True)
print("{} [{:.2f}ms]".format(formatted_sql, duration))
if connection.vendor == "postgresql":
psql_base.CursorDebugWrapper = PrintQueryWrapper
else:
db_backends_utils.CursorDebugWrapper = PrintQueryWrapper