|
| 1 | +# Code obtained from django-debug-toolbar sql panel tracking |
| 2 | +from __future__ import absolute_import, unicode_literals |
| 3 | + |
| 4 | +import json |
| 5 | +from threading import local |
| 6 | +from time import time |
| 7 | + |
| 8 | +from django.utils import six |
| 9 | +from django.utils.encoding import force_text |
| 10 | + |
| 11 | + |
| 12 | +class SQLQueryTriggered(Exception): |
| 13 | + """Thrown when template panel triggers a query""" |
| 14 | + |
| 15 | + |
| 16 | +class ThreadLocalState(local): |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + self.enabled = True |
| 20 | + |
| 21 | + @property |
| 22 | + def Wrapper(self): |
| 23 | + if self.enabled: |
| 24 | + return NormalCursorWrapper |
| 25 | + return ExceptionCursorWrapper |
| 26 | + |
| 27 | + def recording(self, v): |
| 28 | + self.enabled = v |
| 29 | + |
| 30 | + |
| 31 | +state = ThreadLocalState() |
| 32 | +recording = state.recording # export function |
| 33 | + |
| 34 | + |
| 35 | +def wrap_cursor(connection, panel): |
| 36 | + if not hasattr(connection, '_djdt_cursor'): |
| 37 | + connection._djdt_cursor = connection.cursor |
| 38 | + |
| 39 | + def cursor(): |
| 40 | + return state.Wrapper(connection._djdt_cursor(), connection, panel) |
| 41 | + |
| 42 | + connection.cursor = cursor |
| 43 | + return cursor |
| 44 | + |
| 45 | + |
| 46 | +def unwrap_cursor(connection): |
| 47 | + if hasattr(connection, '_djdt_cursor'): |
| 48 | + del connection._djdt_cursor |
| 49 | + del connection.cursor |
| 50 | + |
| 51 | + |
| 52 | +class ExceptionCursorWrapper(object): |
| 53 | + """ |
| 54 | + Wraps a cursor and raises an exception on any operation. |
| 55 | + Used in Templates panel. |
| 56 | + """ |
| 57 | + |
| 58 | + def __init__(self, cursor, db, logger): |
| 59 | + pass |
| 60 | + |
| 61 | + def __getattr__(self, attr): |
| 62 | + raise SQLQueryTriggered() |
| 63 | + |
| 64 | + |
| 65 | +class NormalCursorWrapper(object): |
| 66 | + """ |
| 67 | + Wraps a cursor and logs queries. |
| 68 | + """ |
| 69 | + |
| 70 | + def __init__(self, cursor, db, logger): |
| 71 | + self.cursor = cursor |
| 72 | + # Instance of a BaseDatabaseWrapper subclass |
| 73 | + self.db = db |
| 74 | + # logger must implement a ``record`` method |
| 75 | + self.logger = logger |
| 76 | + |
| 77 | + def _quote_expr(self, element): |
| 78 | + if isinstance(element, six.string_types): |
| 79 | + return "'%s'" % force_text(element).replace("'", "''") |
| 80 | + else: |
| 81 | + return repr(element) |
| 82 | + |
| 83 | + def _quote_params(self, params): |
| 84 | + if not params: |
| 85 | + return params |
| 86 | + if isinstance(params, dict): |
| 87 | + return dict((key, self._quote_expr(value)) |
| 88 | + for key, value in params.items()) |
| 89 | + return list(map(self._quote_expr, params)) |
| 90 | + |
| 91 | + def _decode(self, param): |
| 92 | + try: |
| 93 | + return force_text(param, strings_only=True) |
| 94 | + except UnicodeDecodeError: |
| 95 | + return '(encoded string)' |
| 96 | + |
| 97 | + def _record(self, method, sql, params): |
| 98 | + start_time = time() |
| 99 | + try: |
| 100 | + return method(sql, params) |
| 101 | + finally: |
| 102 | + stop_time = time() |
| 103 | + duration = (stop_time - start_time) |
| 104 | + _params = '' |
| 105 | + try: |
| 106 | + _params = json.dumps(list(map(self._decode, params))) |
| 107 | + except Exception: |
| 108 | + pass # object not JSON serializable |
| 109 | + |
| 110 | + alias = getattr(self.db, 'alias', 'default') |
| 111 | + conn = self.db.connection |
| 112 | + vendor = getattr(conn, 'vendor', 'unknown') |
| 113 | + |
| 114 | + params = { |
| 115 | + 'vendor': vendor, |
| 116 | + 'alias': alias, |
| 117 | + 'sql': self.db.ops.last_executed_query( |
| 118 | + self.cursor, sql, self._quote_params(params)), |
| 119 | + 'duration': duration, |
| 120 | + 'raw_sql': sql, |
| 121 | + 'params': _params, |
| 122 | + 'start_time': start_time, |
| 123 | + 'stop_time': stop_time, |
| 124 | + 'is_slow': duration > 10, |
| 125 | + 'is_select': sql.lower().strip().startswith('select'), |
| 126 | + } |
| 127 | + |
| 128 | + if vendor == 'postgresql': |
| 129 | + # If an erroneous query was ran on the connection, it might |
| 130 | + # be in a state where checking isolation_level raises an |
| 131 | + # exception. |
| 132 | + try: |
| 133 | + iso_level = conn.isolation_level |
| 134 | + except conn.InternalError: |
| 135 | + iso_level = 'unknown' |
| 136 | + params.update({ |
| 137 | + 'trans_id': self.logger.get_transaction_id(alias), |
| 138 | + 'trans_status': conn.get_transaction_status(), |
| 139 | + 'iso_level': iso_level, |
| 140 | + 'encoding': conn.encoding, |
| 141 | + }) |
| 142 | + |
| 143 | + # We keep `sql` to maintain backwards compatibility |
| 144 | + self.logger.record(**params) |
| 145 | + |
| 146 | + def callproc(self, procname, params=()): |
| 147 | + return self._record(self.cursor.callproc, procname, params) |
| 148 | + |
| 149 | + def execute(self, sql, params=()): |
| 150 | + return self._record(self.cursor.execute, sql, params) |
| 151 | + |
| 152 | + def executemany(self, sql, param_list): |
| 153 | + return self._record(self.cursor.executemany, sql, param_list) |
| 154 | + |
| 155 | + def __getattr__(self, attr): |
| 156 | + return getattr(self.cursor, attr) |
| 157 | + |
| 158 | + def __iter__(self): |
| 159 | + return iter(self.cursor) |
| 160 | + |
| 161 | + def __enter__(self): |
| 162 | + return self |
| 163 | + |
| 164 | + def __exit__(self, type, value, traceback): |
| 165 | + self.close() |
0 commit comments