Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 9.0KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. def split_tzname_delta(tzname):
  124. """
  125. Split a time zone name into a 3-tuple of (name, sign, offset).
  126. """
  127. for sign in ["+", "-"]:
  128. if sign in tzname:
  129. name, offset = tzname.rsplit(sign, 1)
  130. if offset and parse_time(offset):
  131. return name, sign, offset
  132. return tzname, None, None
  133. ###############################################
  134. # Converters from database (string) to Python #
  135. ###############################################
  136. def typecast_date(s):
  137. return (
  138. datetime.date(*map(int, s.split("-"))) if s else None
  139. ) # return None if s is null
  140. def typecast_time(s): # does NOT store time zone information
  141. if not s:
  142. return None
  143. hour, minutes, seconds = s.split(":")
  144. if "." in seconds: # check whether seconds have a fractional part
  145. seconds, microseconds = seconds.split(".")
  146. else:
  147. microseconds = "0"
  148. return datetime.time(
  149. int(hour), int(minutes), int(seconds), int((microseconds + "000000")[:6])
  150. )
  151. def typecast_timestamp(s): # does NOT store time zone information
  152. # "2005-07-29 15:48:00.590358-05"
  153. # "2005-07-29 09:56:00-05"
  154. if not s:
  155. return None
  156. if " " not in s:
  157. return typecast_date(s)
  158. d, t = s.split()
  159. # Remove timezone information.
  160. if "-" in t:
  161. t, _ = t.split("-", 1)
  162. elif "+" in t:
  163. t, _ = t.split("+", 1)
  164. dates = d.split("-")
  165. times = t.split(":")
  166. seconds = times[2]
  167. if "." in seconds: # check whether seconds have a fractional part
  168. seconds, microseconds = seconds.split(".")
  169. else:
  170. microseconds = "0"
  171. return datetime.datetime(
  172. int(dates[0]),
  173. int(dates[1]),
  174. int(dates[2]),
  175. int(times[0]),
  176. int(times[1]),
  177. int(seconds),
  178. int((microseconds + "000000")[:6]),
  179. )
  180. ###############################################
  181. # Converters from Python to database (string) #
  182. ###############################################
  183. def split_identifier(identifier):
  184. """
  185. Split an SQL identifier into a two element tuple of (namespace, name).
  186. The identifier could be a table, column, or sequence name might be prefixed
  187. by a namespace.
  188. """
  189. try:
  190. namespace, name = identifier.split('"."')
  191. except ValueError:
  192. namespace, name = "", identifier
  193. return namespace.strip('"'), name.strip('"')
  194. def truncate_name(identifier, length=None, hash_len=4):
  195. """
  196. Shorten an SQL identifier to a repeatable mangled version with the given
  197. length.
  198. If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
  199. truncate the table portion only.
  200. """
  201. namespace, name = split_identifier(identifier)
  202. if length is None or len(name) <= length:
  203. return identifier
  204. digest = names_digest(name, length=hash_len)
  205. return "%s%s%s" % (
  206. '%s"."' % namespace if namespace else "",
  207. name[: length - hash_len],
  208. digest,
  209. )
  210. def names_digest(*args, length):
  211. """
  212. Generate a 32-bit digest of a set of arguments that can be used to shorten
  213. identifying names.
  214. """
  215. h = md5(usedforsecurity=False)
  216. for arg in args:
  217. h.update(arg.encode())
  218. return h.hexdigest()[:length]
  219. def format_number(value, max_digits, decimal_places):
  220. """
  221. Format a number into a string with the requisite number of digits and
  222. decimal places.
  223. """
  224. if value is None:
  225. return None
  226. context = decimal.getcontext().copy()
  227. if max_digits is not None:
  228. context.prec = max_digits
  229. if decimal_places is not None:
  230. value = value.quantize(
  231. decimal.Decimal(1).scaleb(-decimal_places), context=context
  232. )
  233. else:
  234. context.traps[decimal.Rounded] = 1
  235. value = context.create_decimal(value)
  236. return "{:f}".format(value)
  237. def strip_quotes(table_name):
  238. """
  239. Strip quotes off of quoted table names to make them safe for use in index
  240. names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
  241. scheme) becomes 'USER"."TABLE'.
  242. """
  243. has_quotes = table_name.startswith('"') and table_name.endswith('"')
  244. return table_name[1:-1] if has_quotes else table_name