utils.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import datetime
  2. import decimal
  3. import functools
  4. import logging
  5. import time
  6. from contextlib import contextmanager
  7. from django.db import NotSupportedError
  8. from django.utils.crypto import md5
  9. from django.utils.dateparse import parse_time
  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(
  56. sql, params, many=False, executor=self._execute
  57. )
  58. def executemany(self, sql, param_list):
  59. return self._execute_with_wrappers(
  60. sql, param_list, many=True, executor=self._executemany
  61. )
  62. def _execute_with_wrappers(self, sql, params, many, executor):
  63. context = {"connection": self.db, "cursor": self}
  64. for wrapper in reversed(self.db.execute_wrappers):
  65. executor = functools.partial(wrapper, executor)
  66. return executor(sql, params, many, context)
  67. def _execute(self, sql, params, *ignored_wrapper_args):
  68. self.db.validate_no_broken_transaction()
  69. with self.db.wrap_database_errors:
  70. if params is None:
  71. # params default might be backend specific.
  72. return self.cursor.execute(sql)
  73. else:
  74. return self.cursor.execute(sql, params)
  75. def _executemany(self, sql, param_list, *ignored_wrapper_args):
  76. self.db.validate_no_broken_transaction()
  77. with self.db.wrap_database_errors:
  78. return self.cursor.executemany(sql, param_list)
  79. class CursorDebugWrapper(CursorWrapper):
  80. # XXX callproc isn't instrumented at this time.
  81. def execute(self, sql, params=None):
  82. with self.debug_sql(sql, params, use_last_executed_query=True):
  83. return super().execute(sql, params)
  84. def executemany(self, sql, param_list):
  85. with self.debug_sql(sql, param_list, many=True):
  86. return super().executemany(sql, param_list)
  87. @contextmanager
  88. def debug_sql(
  89. self, sql=None, params=None, use_last_executed_query=False, many=False
  90. ):
  91. start = time.monotonic()
  92. try:
  93. yield
  94. finally:
  95. stop = time.monotonic()
  96. duration = stop - start
  97. if use_last_executed_query:
  98. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  99. try:
  100. times = len(params) if many else ""
  101. except TypeError:
  102. # params could be an iterator.
  103. times = "?"
  104. self.db.queries_log.append(
  105. {
  106. "sql": "%s times: %s" % (times, sql) if many else sql,
  107. "time": "%.3f" % duration,
  108. }
  109. )
  110. logger.debug(
  111. "(%.3f) %s; args=%s; alias=%s",
  112. duration,
  113. sql,
  114. params,
  115. self.db.alias,
  116. extra={
  117. "duration": duration,
  118. "sql": sql,
  119. "params": params,
  120. "alias": self.db.alias,
  121. },
  122. )
  123. @contextmanager
  124. def debug_transaction(connection, sql):
  125. start = time.monotonic()
  126. try:
  127. yield
  128. finally:
  129. if connection.queries_logged:
  130. stop = time.monotonic()
  131. duration = stop - start
  132. connection.queries_log.append(
  133. {
  134. "sql": "%s" % sql,
  135. "time": "%.3f" % duration,
  136. }
  137. )
  138. logger.debug(
  139. "(%.3f) %s; args=%s; alias=%s",
  140. duration,
  141. sql,
  142. None,
  143. connection.alias,
  144. extra={
  145. "duration": duration,
  146. "sql": sql,
  147. "alias": connection.alias,
  148. },
  149. )
  150. def split_tzname_delta(tzname):
  151. """
  152. Split a time zone name into a 3-tuple of (name, sign, offset).
  153. """
  154. for sign in ["+", "-"]:
  155. if sign in tzname:
  156. name, offset = tzname.rsplit(sign, 1)
  157. if offset and parse_time(offset):
  158. return name, sign, offset
  159. return tzname, None, None
  160. ###############################################
  161. # Converters from database (string) to Python #
  162. ###############################################
  163. def typecast_date(s):
  164. return (
  165. datetime.date(*map(int, s.split("-"))) if s else None
  166. ) # return None if s is null
  167. def typecast_time(s): # does NOT store time zone information
  168. if not s:
  169. return None
  170. hour, minutes, seconds = s.split(":")
  171. if "." in seconds: # check whether seconds have a fractional part
  172. seconds, microseconds = seconds.split(".")
  173. else:
  174. microseconds = "0"
  175. return datetime.time(
  176. int(hour), int(minutes), int(seconds), int((microseconds + "000000")[:6])
  177. )
  178. def typecast_timestamp(s): # does NOT store time zone information
  179. # "2005-07-29 15:48:00.590358-05"
  180. # "2005-07-29 09:56:00-05"
  181. if not s:
  182. return None
  183. if " " not in s:
  184. return typecast_date(s)
  185. d, t = s.split()
  186. # Remove timezone information.
  187. if "-" in t:
  188. t, _ = t.split("-", 1)
  189. elif "+" in t:
  190. t, _ = t.split("+", 1)
  191. dates = d.split("-")
  192. times = t.split(":")
  193. seconds = times[2]
  194. if "." in seconds: # check whether seconds have a fractional part
  195. seconds, microseconds = seconds.split(".")
  196. else:
  197. microseconds = "0"
  198. return datetime.datetime(
  199. int(dates[0]),
  200. int(dates[1]),
  201. int(dates[2]),
  202. int(times[0]),
  203. int(times[1]),
  204. int(seconds),
  205. int((microseconds + "000000")[:6]),
  206. )
  207. ###############################################
  208. # Converters from Python to database (string) #
  209. ###############################################
  210. def split_identifier(identifier):
  211. """
  212. Split an SQL identifier into a two element tuple of (namespace, name).
  213. The identifier could be a table, column, or sequence name might be prefixed
  214. by a namespace.
  215. """
  216. try:
  217. namespace, name = identifier.split('"."')
  218. except ValueError:
  219. namespace, name = "", identifier
  220. return namespace.strip('"'), name.strip('"')
  221. def truncate_name(identifier, length=None, hash_len=4):
  222. """
  223. Shorten an SQL identifier to a repeatable mangled version with the given
  224. length.
  225. If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
  226. truncate the table portion only.
  227. """
  228. namespace, name = split_identifier(identifier)
  229. if length is None or len(name) <= length:
  230. return identifier
  231. digest = names_digest(name, length=hash_len)
  232. return "%s%s%s" % (
  233. '%s"."' % namespace if namespace else "",
  234. name[: length - hash_len],
  235. digest,
  236. )
  237. def names_digest(*args, length):
  238. """
  239. Generate a 32-bit digest of a set of arguments that can be used to shorten
  240. identifying names.
  241. """
  242. h = md5(usedforsecurity=False)
  243. for arg in args:
  244. h.update(arg.encode())
  245. return h.hexdigest()[:length]
  246. def format_number(value, max_digits, decimal_places):
  247. """
  248. Format a number into a string with the requisite number of digits and
  249. decimal places.
  250. """
  251. if value is None:
  252. return None
  253. context = decimal.getcontext().copy()
  254. if max_digits is not None:
  255. context.prec = max_digits
  256. if decimal_places is not None:
  257. value = value.quantize(
  258. decimal.Decimal(1).scaleb(-decimal_places), context=context
  259. )
  260. else:
  261. context.traps[decimal.Rounded] = 1
  262. value = context.create_decimal(value)
  263. return "{:f}".format(value)
  264. def strip_quotes(table_name):
  265. """
  266. Strip quotes off of quoted table names to make them safe for use in index
  267. names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  268. scheme) becomes 'USER"."TABLE'.
  269. """
  270. has_quotes = table_name.startswith('"') and table_name.endswith('"')
  271. return table_name[1:-1] if has_quotes else table_name