utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import datetime
  2. import decimal
  3. import functools
  4. import logging
  5. import time
  6. import warnings
  7. from contextlib import contextmanager
  8. from hashlib import md5
  9. from django.apps import apps
  10. from django.db import NotSupportedError
  11. from django.utils.dateparse import parse_time
  12. logger = logging.getLogger("django.db.backends")
  13. class CursorWrapper:
  14. def __init__(self, cursor, db):
  15. self.cursor = cursor
  16. self.db = db
  17. WRAP_ERROR_ATTRS = frozenset(["fetchone", "fetchmany", "fetchall", "nextset"])
  18. APPS_NOT_READY_WARNING_MSG = (
  19. "Accessing the database during app initialization is discouraged. To fix this "
  20. "warning, avoid executing queries in AppConfig.ready() or when your app "
  21. "modules are imported."
  22. )
  23. def __getattr__(self, attr):
  24. cursor_attr = getattr(self.cursor, attr)
  25. if attr in CursorWrapper.WRAP_ERROR_ATTRS:
  26. return self.db.wrap_database_errors(cursor_attr)
  27. else:
  28. return cursor_attr
  29. def __iter__(self):
  30. with self.db.wrap_database_errors:
  31. yield from self.cursor
  32. def __enter__(self):
  33. return self
  34. def __exit__(self, type, value, traceback):
  35. # Close instead of passing through to avoid backend-specific behavior
  36. # (#17671). Catch errors liberally because errors in cleanup code
  37. # aren't useful.
  38. try:
  39. self.close()
  40. except self.db.Database.Error:
  41. pass
  42. # The following methods cannot be implemented in __getattr__, because the
  43. # code must run when the method is invoked, not just when it is accessed.
  44. def callproc(self, procname, params=None, kparams=None):
  45. # Keyword parameters for callproc aren't supported in PEP 249, but the
  46. # database driver may support them (e.g. oracledb).
  47. if kparams is not None and not self.db.features.supports_callproc_kwargs:
  48. raise NotSupportedError(
  49. "Keyword parameters for callproc are not supported on this "
  50. "database backend."
  51. )
  52. # Raise a warning during app initialization (stored_app_configs is only
  53. # ever set during testing).
  54. if not apps.ready and not apps.stored_app_configs:
  55. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning)
  56. self.db.validate_no_broken_transaction()
  57. with self.db.wrap_database_errors:
  58. if params is None and kparams is None:
  59. return self.cursor.callproc(procname)
  60. elif kparams is None:
  61. return self.cursor.callproc(procname, params)
  62. else:
  63. params = params or ()
  64. return self.cursor.callproc(procname, params, kparams)
  65. def execute(self, sql, params=None):
  66. return self._execute_with_wrappers(
  67. sql, params, many=False, executor=self._execute
  68. )
  69. def executemany(self, sql, param_list):
  70. return self._execute_with_wrappers(
  71. sql, param_list, many=True, executor=self._executemany
  72. )
  73. def _execute_with_wrappers(self, sql, params, many, executor):
  74. context = {"connection": self.db, "cursor": self}
  75. for wrapper in reversed(self.db.execute_wrappers):
  76. executor = functools.partial(wrapper, executor)
  77. return executor(sql, params, many, context)
  78. def _execute(self, sql, params, *ignored_wrapper_args):
  79. # Raise a warning during app initialization (stored_app_configs is only
  80. # ever set during testing).
  81. if not apps.ready and not apps.stored_app_configs:
  82. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning)
  83. self.db.validate_no_broken_transaction()
  84. with self.db.wrap_database_errors:
  85. if params is None:
  86. # params default might be backend specific.
  87. return self.cursor.execute(sql)
  88. else:
  89. return self.cursor.execute(sql, params)
  90. def _executemany(self, sql, param_list, *ignored_wrapper_args):
  91. # Raise a warning during app initialization (stored_app_configs is only
  92. # ever set during testing).
  93. if not apps.ready and not apps.stored_app_configs:
  94. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning)
  95. self.db.validate_no_broken_transaction()
  96. with self.db.wrap_database_errors:
  97. return self.cursor.executemany(sql, param_list)
  98. class CursorDebugWrapper(CursorWrapper):
  99. # XXX callproc isn't instrumented at this time.
  100. def execute(self, sql, params=None):
  101. with self.debug_sql(sql, params, use_last_executed_query=True):
  102. return super().execute(sql, params)
  103. def executemany(self, sql, param_list):
  104. with self.debug_sql(sql, param_list, many=True):
  105. return super().executemany(sql, param_list)
  106. @contextmanager
  107. def debug_sql(
  108. self, sql=None, params=None, use_last_executed_query=False, many=False
  109. ):
  110. start = time.monotonic()
  111. try:
  112. yield
  113. finally:
  114. stop = time.monotonic()
  115. duration = stop - start
  116. if use_last_executed_query:
  117. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  118. try:
  119. times = len(params) if many else ""
  120. except TypeError:
  121. # params could be an iterator.
  122. times = "?"
  123. self.db.queries_log.append(
  124. {
  125. "sql": "%s times: %s" % (times, sql) if many else sql,
  126. "time": "%.3f" % duration,
  127. }
  128. )
  129. logger.debug(
  130. "(%.3f) %s; args=%s; alias=%s",
  131. duration,
  132. sql,
  133. params,
  134. self.db.alias,
  135. extra={
  136. "duration": duration,
  137. "sql": sql,
  138. "params": params,
  139. "alias": self.db.alias,
  140. },
  141. )
  142. @contextmanager
  143. def debug_transaction(connection, sql):
  144. start = time.monotonic()
  145. try:
  146. yield
  147. finally:
  148. if connection.queries_logged:
  149. stop = time.monotonic()
  150. duration = stop - start
  151. connection.queries_log.append(
  152. {
  153. "sql": "%s" % sql,
  154. "time": "%.3f" % duration,
  155. }
  156. )
  157. logger.debug(
  158. "(%.3f) %s; args=%s; alias=%s",
  159. duration,
  160. sql,
  161. None,
  162. connection.alias,
  163. extra={
  164. "duration": duration,
  165. "sql": sql,
  166. "alias": connection.alias,
  167. },
  168. )
  169. def split_tzname_delta(tzname):
  170. """
  171. Split a time zone name into a 3-tuple of (name, sign, offset).
  172. """
  173. for sign in ["+", "-"]:
  174. if sign in tzname:
  175. name, offset = tzname.rsplit(sign, 1)
  176. if offset and parse_time(offset):
  177. return name, sign, offset
  178. return tzname, None, None
  179. ###############################################
  180. # Converters from database (string) to Python #
  181. ###############################################
  182. def typecast_date(s):
  183. return (
  184. datetime.date(*map(int, s.split("-"))) if s else None
  185. ) # return None if s is null
  186. def typecast_time(s): # does NOT store time zone information
  187. if not s:
  188. return None
  189. hour, minutes, seconds = s.split(":")
  190. if "." in seconds: # check whether seconds have a fractional part
  191. seconds, microseconds = seconds.split(".")
  192. else:
  193. microseconds = "0"
  194. return datetime.time(
  195. int(hour), int(minutes), int(seconds), int((microseconds + "000000")[:6])
  196. )
  197. def typecast_timestamp(s): # does NOT store time zone information
  198. # "2005-07-29 15:48:00.590358-05"
  199. # "2005-07-29 09:56:00-05"
  200. if not s:
  201. return None
  202. if " " not in s:
  203. return typecast_date(s)
  204. d, t = s.split()
  205. # Remove timezone information.
  206. if "-" in t:
  207. t, _ = t.split("-", 1)
  208. elif "+" in t:
  209. t, _ = t.split("+", 1)
  210. dates = d.split("-")
  211. times = t.split(":")
  212. seconds = times[2]
  213. if "." in seconds: # check whether seconds have a fractional part
  214. seconds, microseconds = seconds.split(".")
  215. else:
  216. microseconds = "0"
  217. return datetime.datetime(
  218. int(dates[0]),
  219. int(dates[1]),
  220. int(dates[2]),
  221. int(times[0]),
  222. int(times[1]),
  223. int(seconds),
  224. int((microseconds + "000000")[:6]),
  225. )
  226. ###############################################
  227. # Converters from Python to database (string) #
  228. ###############################################
  229. def split_identifier(identifier):
  230. """
  231. Split an SQL identifier into a two element tuple of (namespace, name).
  232. The identifier could be a table, column, or sequence name might be prefixed
  233. by a namespace.
  234. """
  235. try:
  236. namespace, name = identifier.split('"."')
  237. except ValueError:
  238. namespace, name = "", identifier
  239. return namespace.strip('"'), name.strip('"')
  240. def truncate_name(identifier, length=None, hash_len=4):
  241. """
  242. Shorten an SQL identifier to a repeatable mangled version with the given
  243. length.
  244. If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
  245. truncate the table portion only.
  246. """
  247. namespace, name = split_identifier(identifier)
  248. if length is None or len(name) <= length:
  249. return identifier
  250. digest = names_digest(name, length=hash_len)
  251. return "%s%s%s" % (
  252. '%s"."' % namespace if namespace else "",
  253. name[: length - hash_len],
  254. digest,
  255. )
  256. def names_digest(*args, length):
  257. """
  258. Generate a 32-bit digest of a set of arguments that can be used to shorten
  259. identifying names.
  260. """
  261. h = md5(usedforsecurity=False)
  262. for arg in args:
  263. h.update(arg.encode())
  264. return h.hexdigest()[:length]
  265. def format_number(value, max_digits, decimal_places):
  266. """
  267. Format a number into a string with the requisite number of digits and
  268. decimal places.
  269. """
  270. if value is None:
  271. return None
  272. context = decimal.getcontext().copy()
  273. if max_digits is not None:
  274. context.prec = max_digits
  275. if decimal_places is not None:
  276. value = value.quantize(
  277. decimal.Decimal(1).scaleb(-decimal_places), context=context
  278. )
  279. else:
  280. context.traps[decimal.Rounded] = 1
  281. value = context.create_decimal(value)
  282. return "{:f}".format(value)
  283. def strip_quotes(table_name):
  284. """
  285. Strip quotes off of quoted table names to make them safe for use in index
  286. names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  287. scheme) becomes 'USER"."TABLE'.
  288. """
  289. has_quotes = table_name.startswith('"') and table_name.endswith('"')
  290. return table_name[1:-1] if has_quotes else table_name