Development of an internal social media platform with personalised dashboards for students
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.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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.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. 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. return self.cursor.execute(sql)
  69. else:
  70. return self.cursor.execute(sql, params)
  71. def _executemany(self, sql, param_list, *ignored_wrapper_args):
  72. self.db.validate_no_broken_transaction()
  73. with self.db.wrap_database_errors:
  74. return self.cursor.executemany(sql, param_list)
  75. class CursorDebugWrapper(CursorWrapper):
  76. # XXX callproc isn't instrumented at this time.
  77. def execute(self, sql, params=None):
  78. start = time()
  79. try:
  80. return super().execute(sql, params)
  81. finally:
  82. stop = time()
  83. duration = stop - start
  84. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  85. self.db.queries_log.append({
  86. 'sql': sql,
  87. 'time': "%.3f" % duration,
  88. })
  89. logger.debug(
  90. '(%.3f) %s; args=%s', duration, sql, params,
  91. extra={'duration': duration, 'sql': sql, 'params': params}
  92. )
  93. def executemany(self, sql, param_list):
  94. start = time()
  95. try:
  96. return super().executemany(sql, param_list)
  97. finally:
  98. stop = time()
  99. duration = stop - start
  100. try:
  101. times = len(param_list)
  102. except TypeError: # param_list could be an iterator
  103. times = '?'
  104. self.db.queries_log.append({
  105. 'sql': '%s times: %s' % (times, sql),
  106. 'time': "%.3f" % duration,
  107. })
  108. logger.debug(
  109. '(%.3f) %s; args=%s', duration, sql, param_list,
  110. extra={'duration': duration, 'sql': sql, 'params': param_list}
  111. )
  112. ###############################################
  113. # Converters from database (string) to Python #
  114. ###############################################
  115. def typecast_date(s):
  116. return datetime.date(*map(int, s.split('-'))) if s else None # return None if s is null
  117. def typecast_time(s): # does NOT store time zone information
  118. if not s:
  119. return None
  120. hour, minutes, seconds = s.split(':')
  121. if '.' in seconds: # check whether seconds have a fractional part
  122. seconds, microseconds = seconds.split('.')
  123. else:
  124. microseconds = '0'
  125. return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6]))
  126. def typecast_timestamp(s): # does NOT store time zone information
  127. # "2005-07-29 15:48:00.590358-05"
  128. # "2005-07-29 09:56:00-05"
  129. if not s:
  130. return None
  131. if ' ' not in s:
  132. return typecast_date(s)
  133. d, t = s.split()
  134. # Extract timezone information, if it exists. Currently it's ignored.
  135. if '-' in t:
  136. t, tz = t.split('-', 1)
  137. tz = '-' + tz
  138. elif '+' in t:
  139. t, tz = t.split('+', 1)
  140. tz = '+' + tz
  141. else:
  142. tz = ''
  143. dates = d.split('-')
  144. times = t.split(':')
  145. seconds = times[2]
  146. if '.' in seconds: # check whether seconds have a fractional part
  147. seconds, microseconds = seconds.split('.')
  148. else:
  149. microseconds = '0'
  150. tzinfo = utc if settings.USE_TZ else None
  151. return datetime.datetime(
  152. int(dates[0]), int(dates[1]), int(dates[2]),
  153. int(times[0]), int(times[1]), int(seconds),
  154. int((microseconds + '000000')[:6]), tzinfo
  155. )
  156. ###############################################
  157. # Converters from Python to database (string) #
  158. ###############################################
  159. def rev_typecast_decimal(d):
  160. if d is None:
  161. return None
  162. return str(d)
  163. def split_identifier(identifier):
  164. """
  165. Split a SQL identifier into a two element tuple of (namespace, name).
  166. The identifier could be a table, column, or sequence name might be prefixed
  167. by a namespace.
  168. """
  169. try:
  170. namespace, name = identifier.split('"."')
  171. except ValueError:
  172. namespace, name = '', identifier
  173. return namespace.strip('"'), name.strip('"')
  174. def truncate_name(identifier, length=None, hash_len=4):
  175. """
  176. Shorten a SQL identifier to a repeatable mangled version with the given
  177. length.
  178. If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
  179. truncate the table portion only.
  180. """
  181. namespace, name = split_identifier(identifier)
  182. if length is None or len(name) <= length:
  183. return identifier
  184. digest = hashlib.md5(force_bytes(name)).hexdigest()[:hash_len]
  185. return '%s%s%s' % ('%s"."' % namespace if namespace else '', name[:length - hash_len], digest)
  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. if isinstance(value, decimal.Decimal):
  194. context = decimal.getcontext().copy()
  195. if max_digits is not None:
  196. context.prec = max_digits
  197. if decimal_places is not None:
  198. value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context)
  199. else:
  200. context.traps[decimal.Rounded] = 1
  201. value = context.create_decimal(value)
  202. return "{:f}".format(value)
  203. if decimal_places is not None:
  204. return "%.*f" % (decimal_places, value)
  205. return "{:f}".format(value)
  206. def strip_quotes(table_name):
  207. """
  208. Strip quotes off of quoted table names to make them safe for use in index
  209. names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  210. scheme) becomes 'USER"."TABLE'.
  211. """
  212. has_quotes = table_name.startswith('"') and table_name.endswith('"')
  213. return table_name[1:-1] if has_quotes else table_name