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.

transaction.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. from contextlib import ContextDecorator, contextmanager
  2. from django.db import (
  3. DEFAULT_DB_ALIAS,
  4. DatabaseError,
  5. Error,
  6. ProgrammingError,
  7. connections,
  8. )
  9. class TransactionManagementError(ProgrammingError):
  10. """Transaction management is used improperly."""
  11. pass
  12. def get_connection(using=None):
  13. """
  14. Get a database connection by name, or the default database connection
  15. if no name is provided. This is a private API.
  16. """
  17. if using is None:
  18. using = DEFAULT_DB_ALIAS
  19. return connections[using]
  20. def get_autocommit(using=None):
  21. """Get the autocommit status of the connection."""
  22. return get_connection(using).get_autocommit()
  23. def set_autocommit(autocommit, using=None):
  24. """Set the autocommit status of the connection."""
  25. return get_connection(using).set_autocommit(autocommit)
  26. def commit(using=None):
  27. """Commit a transaction."""
  28. get_connection(using).commit()
  29. def rollback(using=None):
  30. """Roll back a transaction."""
  31. get_connection(using).rollback()
  32. def savepoint(using=None):
  33. """
  34. Create a savepoint (if supported and required by the backend) inside the
  35. current transaction. Return an identifier for the savepoint that will be
  36. used for the subsequent rollback or commit.
  37. """
  38. return get_connection(using).savepoint()
  39. def savepoint_rollback(sid, using=None):
  40. """
  41. Roll back the most recent savepoint (if one exists). Do nothing if
  42. savepoints are not supported.
  43. """
  44. get_connection(using).savepoint_rollback(sid)
  45. def savepoint_commit(sid, using=None):
  46. """
  47. Commit the most recent savepoint (if one exists). Do nothing if
  48. savepoints are not supported.
  49. """
  50. get_connection(using).savepoint_commit(sid)
  51. def clean_savepoints(using=None):
  52. """
  53. Reset the counter used to generate unique savepoint ids in this thread.
  54. """
  55. get_connection(using).clean_savepoints()
  56. def get_rollback(using=None):
  57. """Get the "needs rollback" flag -- for *advanced use* only."""
  58. return get_connection(using).get_rollback()
  59. def set_rollback(rollback, using=None):
  60. """
  61. Set or unset the "needs rollback" flag -- for *advanced use* only.
  62. When `rollback` is `True`, trigger a rollback when exiting the innermost
  63. enclosing atomic block that has `savepoint=True` (that's the default). Use
  64. this to force a rollback without raising an exception.
  65. When `rollback` is `False`, prevent such a rollback. Use this only after
  66. rolling back to a known-good state! Otherwise, you break the atomic block
  67. and data corruption may occur.
  68. """
  69. return get_connection(using).set_rollback(rollback)
  70. @contextmanager
  71. def mark_for_rollback_on_error(using=None):
  72. """
  73. Internal low-level utility to mark a transaction as "needs rollback" when
  74. an exception is raised while not enforcing the enclosed block to be in a
  75. transaction. This is needed by Model.save() and friends to avoid starting a
  76. transaction when in autocommit mode and a single query is executed.
  77. It's equivalent to:
  78. connection = get_connection(using)
  79. if connection.get_autocommit():
  80. yield
  81. else:
  82. with transaction.atomic(using=using, savepoint=False):
  83. yield
  84. but it uses low-level utilities to avoid performance overhead.
  85. """
  86. try:
  87. yield
  88. except Exception:
  89. connection = get_connection(using)
  90. if connection.in_atomic_block:
  91. connection.needs_rollback = True
  92. raise
  93. def on_commit(func, using=None):
  94. """
  95. Register `func` to be called when the current transaction is committed.
  96. If the current transaction is rolled back, `func` will not be called.
  97. """
  98. get_connection(using).on_commit(func)
  99. #################################
  100. # Decorators / context managers #
  101. #################################
  102. class Atomic(ContextDecorator):
  103. """
  104. Guarantee the atomic execution of a given block.
  105. An instance can be used either as a decorator or as a context manager.
  106. When it's used as a decorator, __call__ wraps the execution of the
  107. decorated function in the instance itself, used as a context manager.
  108. When it's used as a context manager, __enter__ creates a transaction or a
  109. savepoint, depending on whether a transaction is already in progress, and
  110. __exit__ commits the transaction or releases the savepoint on normal exit,
  111. and rolls back the transaction or to the savepoint on exceptions.
  112. It's possible to disable the creation of savepoints if the goal is to
  113. ensure that some code runs within a transaction without creating overhead.
  114. A stack of savepoints identifiers is maintained as an attribute of the
  115. connection. None denotes the absence of a savepoint.
  116. This allows reentrancy even if the same AtomicWrapper is reused. For
  117. example, it's possible to define `oa = atomic('other')` and use `@oa` or
  118. `with oa:` multiple times.
  119. Since database connections are thread-local, this is thread-safe.
  120. An atomic block can be tagged as durable. In this case, raise a
  121. RuntimeError if it's nested within another atomic block. This guarantees
  122. that database changes in a durable block are committed to the database when
  123. the block exists without error.
  124. This is a private API.
  125. """
  126. def __init__(self, using, savepoint, durable):
  127. self.using = using
  128. self.savepoint = savepoint
  129. self.durable = durable
  130. self._from_testcase = False
  131. def __enter__(self):
  132. connection = get_connection(self.using)
  133. if (
  134. self.durable
  135. and connection.atomic_blocks
  136. and not connection.atomic_blocks[-1]._from_testcase
  137. ):
  138. raise RuntimeError(
  139. "A durable atomic block cannot be nested within another "
  140. "atomic block."
  141. )
  142. if not connection.in_atomic_block:
  143. # Reset state when entering an outermost atomic block.
  144. connection.commit_on_exit = True
  145. connection.needs_rollback = False
  146. if not connection.get_autocommit():
  147. # Pretend we're already in an atomic block to bypass the code
  148. # that disables autocommit to enter a transaction, and make a
  149. # note to deal with this case in __exit__.
  150. connection.in_atomic_block = True
  151. connection.commit_on_exit = False
  152. if connection.in_atomic_block:
  153. # We're already in a transaction; create a savepoint, unless we
  154. # were told not to or we're already waiting for a rollback. The
  155. # second condition avoids creating useless savepoints and prevents
  156. # overwriting needs_rollback until the rollback is performed.
  157. if self.savepoint and not connection.needs_rollback:
  158. sid = connection.savepoint()
  159. connection.savepoint_ids.append(sid)
  160. else:
  161. connection.savepoint_ids.append(None)
  162. else:
  163. connection.set_autocommit(
  164. False, force_begin_transaction_with_broken_autocommit=True
  165. )
  166. connection.in_atomic_block = True
  167. if connection.in_atomic_block:
  168. connection.atomic_blocks.append(self)
  169. def __exit__(self, exc_type, exc_value, traceback):
  170. connection = get_connection(self.using)
  171. if connection.in_atomic_block:
  172. connection.atomic_blocks.pop()
  173. if connection.savepoint_ids:
  174. sid = connection.savepoint_ids.pop()
  175. else:
  176. # Prematurely unset this flag to allow using commit or rollback.
  177. connection.in_atomic_block = False
  178. try:
  179. if connection.closed_in_transaction:
  180. # The database will perform a rollback by itself.
  181. # Wait until we exit the outermost block.
  182. pass
  183. elif exc_type is None and not connection.needs_rollback:
  184. if connection.in_atomic_block:
  185. # Release savepoint if there is one
  186. if sid is not None:
  187. try:
  188. connection.savepoint_commit(sid)
  189. except DatabaseError:
  190. try:
  191. connection.savepoint_rollback(sid)
  192. # The savepoint won't be reused. Release it to
  193. # minimize overhead for the database server.
  194. connection.savepoint_commit(sid)
  195. except Error:
  196. # If rolling back to a savepoint fails, mark for
  197. # rollback at a higher level and avoid shadowing
  198. # the original exception.
  199. connection.needs_rollback = True
  200. raise
  201. else:
  202. # Commit transaction
  203. try:
  204. connection.commit()
  205. except DatabaseError:
  206. try:
  207. connection.rollback()
  208. except Error:
  209. # An error during rollback means that something
  210. # went wrong with the connection. Drop it.
  211. connection.close()
  212. raise
  213. else:
  214. # This flag will be set to True again if there isn't a savepoint
  215. # allowing to perform the rollback at this level.
  216. connection.needs_rollback = False
  217. if connection.in_atomic_block:
  218. # Roll back to savepoint if there is one, mark for rollback
  219. # otherwise.
  220. if sid is None:
  221. connection.needs_rollback = True
  222. else:
  223. try:
  224. connection.savepoint_rollback(sid)
  225. # The savepoint won't be reused. Release it to
  226. # minimize overhead for the database server.
  227. connection.savepoint_commit(sid)
  228. except Error:
  229. # If rolling back to a savepoint fails, mark for
  230. # rollback at a higher level and avoid shadowing
  231. # the original exception.
  232. connection.needs_rollback = True
  233. else:
  234. # Roll back transaction
  235. try:
  236. connection.rollback()
  237. except Error:
  238. # An error during rollback means that something
  239. # went wrong with the connection. Drop it.
  240. connection.close()
  241. finally:
  242. # Outermost block exit when autocommit was enabled.
  243. if not connection.in_atomic_block:
  244. if connection.closed_in_transaction:
  245. connection.connection = None
  246. else:
  247. connection.set_autocommit(True)
  248. # Outermost block exit when autocommit was disabled.
  249. elif not connection.savepoint_ids and not connection.commit_on_exit:
  250. if connection.closed_in_transaction:
  251. connection.connection = None
  252. else:
  253. connection.in_atomic_block = False
  254. def atomic(using=None, savepoint=True, durable=False):
  255. # Bare decorator: @atomic -- although the first argument is called
  256. # `using`, it's actually the function being decorated.
  257. if callable(using):
  258. return Atomic(DEFAULT_DB_ALIAS, savepoint, durable)(using)
  259. # Decorator: @atomic(...) or context manager: with atomic(...): ...
  260. else:
  261. return Atomic(using, savepoint, durable)
  262. def _non_atomic_requests(view, using):
  263. try:
  264. view._non_atomic_requests.add(using)
  265. except AttributeError:
  266. view._non_atomic_requests = {using}
  267. return view
  268. def non_atomic_requests(using=None):
  269. if callable(using):
  270. return _non_atomic_requests(using, DEFAULT_DB_ALIAS)
  271. else:
  272. if using is None:
  273. using = DEFAULT_DB_ALIAS
  274. return lambda view: _non_atomic_requests(view, using)