utils.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import datetime
  2. import decimal
  3. import functools
  4. import hashlib
  5. import logging
  6. import time
  7. from contextlib import contextmanager
  8. from django.conf import settings
  9. from django.db.utils import NotSupportedError
  10. from django.utils.timezone import utc
  11. logger = logging.getLogger('django.db.backends')
  12. class CursorWrapper:
  13. def __init__(self, cursor, db):
  14. self.cursor = cursor
  15. self.db = db
  16. WRAP_ERROR_ATTRS = frozenset(['fetchone', 'fetchmany', 'fetchall', 'nextset'])
  17. def __getattr__(self, attr):
  18. cursor_attr = getattr(self.cursor, attr)
  19. if attr in CursorWrapper.WRAP_ERROR_ATTRS:
  20. return self.db.wrap_database_errors(cursor_attr)
  21. else:
  22. return cursor_attr
  23. def __iter__(self):
  24. with self.db.wrap_database_errors:
  25. yield from self.cursor
  26. def __enter__(self):
  27. return self
  28. def __exit__(self, type, value, traceback):
  29. # Close instead of passing through to avoid backend-specific behavior
  30. # (#17671). Catch errors liberally because errors in cleanup code
  31. # aren't useful.
  32. try:
  33. self.close()
  34. except self.db.Database.Error:
  35. pass
  36. # The following methods cannot be implemented in __getattr__, because the
  37. # code must run when the method is invoked, not just when it is accessed.
  38. def callproc(self, procname, params=None, kparams=None):
  39. # Keyword parameters for callproc aren't supported in PEP 249, but the
  40. # database driver may support them (e.g. cx_Oracle).
  41. if kparams is not None and not self.db.features.supports_callproc_kwargs:
  42. raise NotSupportedError(
  43. 'Keyword parameters for callproc are not supported on this '
  44. 'database backend.'
  45. )
  46. self.db.validate_no_broken_transaction()
  47. with self.db.wrap_database_errors:
  48. if params is None and kparams is None:
  49. return self.cursor.callproc(procname)
  50. elif kparams is None:
  51. return self.cursor.callproc(procname, params)
  52. else:
  53. params = params or ()
  54. return self.cursor.callproc(procname, params, kparams)
  55. def execute(self, sql, params=None):
  56. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  57. def executemany(self, sql, param_list):
  58. return self._execute_with_wrappers(sql, param_list, many=True, executor=self._executemany)
  59. def _execute_with_wrappers(self, sql, params, many, executor):
  60. context = {'connection': self.db, 'cursor': self}
  61. for wrapper in reversed(self.db.execute_wrappers):
  62. executor = functools.partial(wrapper, executor)
  63. return executor(sql, params, many, context)
  64. def _execute(self, sql, params, *ignored_wrapper_args):
  65. self.db.validate_no_broken_transaction()
  66. with self.db.wrap_database_errors:
  67. if params is None:
  68. # params default might be backend specific.
  69. return self.cursor.execute(sql)
  70. else:
  71. return self.cursor.execute(sql, params)
  72. def _executemany(self, sql, param_list, *ignored_wrapper_args):
  73. self.db.validate_no_broken_transaction()
  74. with self.db.wrap_database_errors:
  75. return self.cursor.executemany(sql, param_list)
  76. class CursorDebugWrapper(CursorWrapper):
  77. # XXX callproc isn't instrumented at this time.
  78. def execute(self, sql, params=None):
  79. with self.debug_sql(sql, params, use_last_executed_query=True):
  80. return super().execute(sql, params)
  81. def executemany(self, sql, param_list):
  82. with self.debug_sql(sql, param_list, many=True):
  83. return super().executemany(sql, param_list)
  84. @contextmanager
  85. def debug_sql(self, sql=None, params=None, use_last_executed_query=False, many=False):
  86. start = time.monotonic()
  87. try:
  88. yield
  89. finally:
  90. stop = time.monotonic()
  91. duration = stop - start
  92. if use_last_executed_query:
  93. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  94. try:
  95. times = len(params) if many else ''
  96. except TypeError:
  97. # params could be an iterator.
  98. times = '?'
  99. self.db.queries_log.append({
  100. 'sql': '%s times: %s' % (times, sql) if many else sql,
  101. 'time': '%.3f' % duration,
  102. })
  103. logger.debug(
  104. '(%.3f) %s; args=%s',
  105. duration,
  106. sql,
  107. params,
  108. extra={'duration': duration, 'sql': sql, 'params': params},
  109. )
  110. ###############################################
  111. # Converters from database (string) to Python #
  112. ###############################################
  113. def typecast_date(s):
  114. return datetime.date(*map(int, s.split('-'))) if s else None # return None if s is null
  115. def typecast_time(s): # does NOT store time zone information
  116. if not s:
  117. return None
  118. hour, minutes, seconds = s.split(':')
  119. if '.' in seconds: # check whether seconds have a fractional part
  120. seconds, microseconds = seconds.split('.')
  121. else:
  122. microseconds = '0'
  123. return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6]))
  124. def typecast_timestamp(s): # does NOT store time zone information
  125. # "2005-07-29 15:48:00.590358-05"
  126. # "2005-07-29 09:56:00-05"
  127. if not s:
  128. return None
  129. if ' ' not in s:
  130. return typecast_date(s)
  131. d, t = s.split()
  132. # Remove timezone information.
  133. if '-' in t:
  134. t, _ = t.split('-', 1)
  135. elif '+' in t:
  136. t, _ = t.split('+', 1)
  137. dates = d.split('-')
  138. times = t.split(':')
  139. seconds = times[2]
  140. if '.' in seconds: # check whether seconds have a fractional part
  141. seconds, microseconds = seconds.split('.')
  142. else:
  143. microseconds = '0'
  144. tzinfo = utc if settings.USE_TZ else None
  145. return datetime.datetime(
  146. int(dates[0]), int(dates[1]), int(dates[2]),
  147. int(times[0]), int(times[1]), int(seconds),
  148. int((microseconds + '000000')[:6]), tzinfo
  149. )
  150. ###############################################
  151. # Converters from Python to database (string) #
  152. ###############################################
  153. def split_identifier(identifier):
  154. """
  155. Split a SQL identifier into a two element tuple of (namespace, name).
  156. The identifier could be a table, column, or sequence name might be prefixed
  157. by a namespace.
  158. """
  159. try:
  160. namespace, name = identifier.split('"."')
  161. except ValueError:
  162. namespace, name = '', identifier
  163. return namespace.strip('"'), name.strip('"')
  164. def truncate_name(identifier, length=None, hash_len=4):
  165. """
  166. Shorten a SQL identifier to a repeatable mangled version with the given
  167. length.
  168. If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
  169. truncate the table portion only.
  170. """
  171. namespace, name = split_identifier(identifier)
  172. if length is None or len(name) <= length:
  173. return identifier
  174. digest = names_digest(name, length=hash_len)
  175. return '%s%s%s' % ('%s"."' % namespace if namespace else '', name[:length - hash_len], digest)
  176. def names_digest(*args, length):
  177. """
  178. Generate a 32-bit digest of a set of arguments that can be used to shorten
  179. identifying names.
  180. """
  181. h = hashlib.md5()
  182. for arg in args:
  183. h.update(arg.encode())
  184. return h.hexdigest()[:length]
  185. def format_number(value, max_digits, decimal_places):
  186. """
  187. Format a number into a string with the requisite number of digits and
  188. decimal places.
  189. """
  190. if value is None:
  191. return None
  192. context = decimal.getcontext().copy()
  193. if max_digits is not None:
  194. context.prec = max_digits
  195. if decimal_places is not None:
  196. value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context)
  197. else:
  198. context.traps[decimal.Rounded] = 1
  199. value = context.create_decimal(value)
  200. return "{:f}".format(value)
  201. def strip_quotes(table_name):
  202. """
  203. Strip quotes off of quoted table names to make them safe for use in index
  204. names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  205. scheme) becomes 'USER"."TABLE'.
  206. """
  207. has_quotes = table_name.startswith('"') and table_name.endswith('"')
  208. return table_name[1:-1] if has_quotes else table_name