utils.py 8.2 KB

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