Created
January 9, 2020 10:13
-
-
Save bogdandm/03efc8fb0441382382571b60ffef4cf0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from django.conf import settings | |
from django.db.backends import utils | |
truncate = 1000 | |
try: | |
import sqlparse | |
sqlparse_format_kwargs_defaults = dict( | |
reindent_aligned=True, | |
truncate_strings=500, | |
) | |
sqlparse_format_kwargs = getattr(settings, 'SHELL_PLUS_SQLPARSE_FORMAT_KWARGS', sqlparse_format_kwargs_defaults) | |
except ImportError: | |
sqlparse = None | |
try: | |
import pygments.lexers | |
import pygments.formatters | |
pygments_formatter = getattr(settings, 'SHELL_PLUS_PYGMENTS_FORMATTER', pygments.formatters.TerminalFormatter) | |
pygments_formatter_kwargs = getattr(settings, 'SHELL_PLUS_PYGMENTS_FORMATTER_KWARGS', {}) | |
except ImportError: | |
pygments = None | |
class PrintQueryWrapper(utils.CursorDebugWrapper): | |
def execute(self, sql, params=()): | |
starttime = time.time() | |
try: | |
return utils.CursorWrapper.execute(self, sql, params) | |
finally: | |
execution_time = time.time() - starttime | |
raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params) | |
if sqlparse: | |
raw_sql = raw_sql[:truncate] | |
raw_sql = sqlparse.format(raw_sql, **sqlparse_format_kwargs) | |
if pygments: | |
raw_sql = pygments.highlight( | |
raw_sql, | |
pygments.lexers.get_lexer_by_name("sql"), | |
pygments_formatter(**pygments_formatter_kwargs), | |
) | |
print(raw_sql) | |
print("") | |
print('Execution time: %.6fs [Database: %s]' % (execution_time, self.db.alias)) | |
print("") | |
utils.CursorDebugWrapper = PrintQueryWrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment