transaction.py 12 KB

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