You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 8.3KB

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