utils.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import datetime
  2. import decimal
  3. import hashlib
  4. import logging
  5. import re
  6. from time import time
  7. from django.conf import settings
  8. from django.db.utils import NotSupportedError
  9. from django.utils.encoding import force_bytes
  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. self.db.validate_no_broken_transaction()
  57. with self.db.wrap_database_errors:
  58. if params is None:
  59. return self.cursor.execute(sql)
  60. else:
  61. return self.cursor.execute(sql, params)
  62. def executemany(self, sql, param_list):
  63. self.db.validate_no_broken_transaction()
  64. with self.db.wrap_database_errors:
  65. return self.cursor.executemany(sql, param_list)
  66. class CursorDebugWrapper(CursorWrapper):
  67. # XXX callproc isn't instrumented at this time.
  68. def execute(self, sql, params=None):
  69. start = time()
  70. try:
  71. return super().execute(sql, params)
  72. finally:
  73. stop = time()
  74. duration = stop - start
  75. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  76. self.db.queries_log.append({
  77. 'sql': sql,
  78. 'time': "%.3f" % duration,
  79. })
  80. logger.debug(
  81. '(%.3f) %s; args=%s', duration, sql, params,
  82. extra={'duration': duration, 'sql': sql, 'params': params}
  83. )
  84. def executemany(self, sql, param_list):
  85. start = time()
  86. try:
  87. return super().executemany(sql, param_list)
  88. finally:
  89. stop = time()
  90. duration = stop - start
  91. try:
  92. times = len(param_list)
  93. except TypeError: # param_list could be an iterator
  94. times = '?'
  95. self.db.queries_log.append({
  96. 'sql': '%s times: %s' % (times, sql),
  97. 'time': "%.3f" % duration,
  98. })
  99. logger.debug(
  100. '(%.3f) %s; args=%s', duration, sql, param_list,
  101. extra={'duration': duration, 'sql': sql, 'params': param_list}
  102. )
  103. ###############################################
  104. # Converters from database (string) to Python #
  105. ###############################################
  106. def typecast_date(s):
  107. return datetime.date(*map(int, s.split('-'))) if s else None # return None if s is null
  108. def typecast_time(s): # does NOT store time zone information
  109. if not s:
  110. return None
  111. hour, minutes, seconds = s.split(':')
  112. if '.' in seconds: # check whether seconds have a fractional part
  113. seconds, microseconds = seconds.split('.')
  114. else:
  115. microseconds = '0'
  116. return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6]))
  117. def typecast_timestamp(s): # does NOT store time zone information
  118. # "2005-07-29 15:48:00.590358-05"
  119. # "2005-07-29 09:56:00-05"
  120. if not s:
  121. return None
  122. if ' ' not in s:
  123. return typecast_date(s)
  124. d, t = s.split()
  125. # Extract timezone information, if it exists. Currently it's ignored.
  126. if '-' in t:
  127. t, tz = t.split('-', 1)
  128. tz = '-' + tz
  129. elif '+' in t:
  130. t, tz = t.split('+', 1)
  131. tz = '+' + tz
  132. else:
  133. tz = ''
  134. dates = d.split('-')
  135. times = t.split(':')
  136. seconds = times[2]
  137. if '.' in seconds: # check whether seconds have a fractional part
  138. seconds, microseconds = seconds.split('.')
  139. else:
  140. microseconds = '0'
  141. tzinfo = utc if settings.USE_TZ else None
  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]), tzinfo
  146. )
  147. ###############################################
  148. # Converters from Python to database (string) #
  149. ###############################################
  150. def rev_typecast_decimal(d):
  151. if d is None:
  152. return None
  153. return str(d)
  154. def truncate_name(name, length=None, hash_len=4):
  155. """
  156. Shorten a string to a repeatable mangled version with the given length.
  157. If a quote stripped name contains a username, e.g. USERNAME"."TABLE,
  158. truncate the table portion only.
  159. """
  160. match = re.match(r'([^"]+)"\."([^"]+)', name)
  161. table_name = match.group(2) if match else name
  162. if length is None or len(table_name) <= length:
  163. return name
  164. hsh = hashlib.md5(force_bytes(table_name)).hexdigest()[:hash_len]
  165. return '%s%s%s' % (match.group(1) + '"."' if match else '', table_name[:length - hash_len], hsh)
  166. def format_number(value, max_digits, decimal_places):
  167. """
  168. Format a number into a string with the requisite number of digits and
  169. decimal places.
  170. """
  171. if value is None:
  172. return None
  173. if isinstance(value, decimal.Decimal):
  174. context = decimal.getcontext().copy()
  175. if max_digits is not None:
  176. context.prec = max_digits
  177. if decimal_places is not None:
  178. value = value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)
  179. else:
  180. context.traps[decimal.Rounded] = 1
  181. value = context.create_decimal(value)
  182. return "{:f}".format(value)
  183. if decimal_places is not None:
  184. return "%.*f" % (decimal_places, value)
  185. return "{:f}".format(value)
  186. def strip_quotes(table_name):
  187. """
  188. Strip quotes off of quoted table names to make them safe for use in index
  189. names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  190. scheme) becomes 'USER"."TABLE'.
  191. """
  192. has_quotes = table_name.startswith('"') and table_name.endswith('"')
  193. return table_name[1:-1] if has_quotes else table_name