transaction.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. """
  2. This module implements a transaction manager that can be used to define
  3. transaction handling in a request or view function. It is used by transaction
  4. control middleware and decorators.
  5. The transaction manager can be in managed or in auto state. Auto state means the
  6. system is using a commit-on-save strategy (actually it's more like
  7. commit-on-change). As soon as the .save() or .delete() (or related) methods are
  8. called, a commit is made.
  9. Managed transactions don't do those commits, but will need some kind of manual
  10. or implicit commits or rollbacks.
  11. """
  12. try:
  13. import thread
  14. except ImportError:
  15. import dummy_thread as thread
  16. try:
  17. from functools import wraps
  18. except ImportError:
  19. from django.utils.functional import wraps # Python 2.4 fallback.
  20. from django.db import connections, DEFAULT_DB_ALIAS
  21. from django.conf import settings
  22. class TransactionManagementError(Exception):
  23. """
  24. This exception is thrown when something bad happens with transaction
  25. management.
  26. """
  27. pass
  28. # The states are dictionaries of dictionaries of lists. The key to the outer
  29. # dict is the current thread, and the key to the inner dictionary is the
  30. # connection alias and the list is handled as a stack of values.
  31. state = {}
  32. savepoint_state = {}
  33. # The dirty flag is set by *_unless_managed functions to denote that the
  34. # code under transaction management has changed things to require a
  35. # database commit.
  36. # This is a dictionary mapping thread to a dictionary mapping connection
  37. # alias to a boolean.
  38. dirty = {}
  39. def enter_transaction_management(managed=True, using=None):
  40. """
  41. Enters transaction management for a running thread. It must be balanced with
  42. the appropriate leave_transaction_management call, since the actual state is
  43. managed as a stack.
  44. The state and dirty flag are carried over from the surrounding block or
  45. from the settings, if there is no surrounding block (dirty is always false
  46. when no current block is running).
  47. """
  48. if using is None:
  49. using = DEFAULT_DB_ALIAS
  50. connection = connections[using]
  51. thread_ident = thread.get_ident()
  52. if thread_ident in state and state[thread_ident].get(using):
  53. state[thread_ident][using].append(state[thread_ident][using][-1])
  54. else:
  55. state.setdefault(thread_ident, {})
  56. state[thread_ident][using] = [settings.TRANSACTIONS_MANAGED]
  57. if thread_ident not in dirty or using not in dirty[thread_ident]:
  58. dirty.setdefault(thread_ident, {})
  59. dirty[thread_ident][using] = False
  60. connection._enter_transaction_management(managed)
  61. def leave_transaction_management(using=None):
  62. """
  63. Leaves transaction management for a running thread. A dirty flag is carried
  64. over to the surrounding block, as a commit will commit all changes, even
  65. those from outside. (Commits are on connection level.)
  66. """
  67. if using is None:
  68. using = DEFAULT_DB_ALIAS
  69. connection = connections[using]
  70. connection._leave_transaction_management(is_managed(using=using))
  71. thread_ident = thread.get_ident()
  72. if thread_ident in state and state[thread_ident].get(using):
  73. del state[thread_ident][using][-1]
  74. else:
  75. raise TransactionManagementError("This code isn't under transaction management")
  76. if dirty.get(thread_ident, {}).get(using, False):
  77. rollback(using=using)
  78. raise TransactionManagementError("Transaction managed block ended with pending COMMIT/ROLLBACK")
  79. dirty[thread_ident][using] = False
  80. def is_dirty(using=None):
  81. """
  82. Returns True if the current transaction requires a commit for changes to
  83. happen.
  84. """
  85. if using is None:
  86. using = DEFAULT_DB_ALIAS
  87. return dirty.get(thread.get_ident(), {}).get(using, False)
  88. def set_dirty(using=None):
  89. """
  90. Sets a dirty flag for the current thread and code streak. This can be used
  91. to decide in a managed block of code to decide whether there are open
  92. changes waiting for commit.
  93. """
  94. if using is None:
  95. using = DEFAULT_DB_ALIAS
  96. thread_ident = thread.get_ident()
  97. if thread_ident in dirty and using in dirty[thread_ident]:
  98. dirty[thread_ident][using] = True
  99. else:
  100. raise TransactionManagementError("This code isn't under transaction management")
  101. def set_clean(using=None):
  102. """
  103. Resets a dirty flag for the current thread and code streak. This can be used
  104. to decide in a managed block of code to decide whether a commit or rollback
  105. should happen.
  106. """
  107. if using is None:
  108. using = DEFAULT_DB_ALIAS
  109. thread_ident = thread.get_ident()
  110. if thread_ident in dirty and using in dirty[thread_ident]:
  111. dirty[thread_ident][using] = False
  112. else:
  113. raise TransactionManagementError("This code isn't under transaction management")
  114. clean_savepoints(using=using)
  115. def clean_savepoints(using=None):
  116. if using is None:
  117. using = DEFAULT_DB_ALIAS
  118. thread_ident = thread.get_ident()
  119. if thread_ident in savepoint_state and using in savepoint_state[thread_ident]:
  120. del savepoint_state[thread_ident][using]
  121. def is_managed(using=None):
  122. """
  123. Checks whether the transaction manager is in manual or in auto state.
  124. """
  125. if using is None:
  126. using = DEFAULT_DB_ALIAS
  127. thread_ident = thread.get_ident()
  128. if thread_ident in state and using in state[thread_ident]:
  129. if state[thread_ident][using]:
  130. return state[thread_ident][using][-1]
  131. return settings.TRANSACTIONS_MANAGED
  132. def managed(flag=True, using=None):
  133. """
  134. Puts the transaction manager into a manual state: managed transactions have
  135. to be committed explicitly by the user. If you switch off transaction
  136. management and there is a pending commit/rollback, the data will be
  137. commited.
  138. """
  139. if using is None:
  140. using = DEFAULT_DB_ALIAS
  141. connection = connections[using]
  142. thread_ident = thread.get_ident()
  143. top = state.get(thread_ident, {}).get(using, None)
  144. if top:
  145. top[-1] = flag
  146. if not flag and is_dirty(using=using):
  147. connection._commit()
  148. set_clean(using=using)
  149. else:
  150. raise TransactionManagementError("This code isn't under transaction management")
  151. def commit_unless_managed(using=None):
  152. """
  153. Commits changes if the system is not in managed transaction mode.
  154. """
  155. if using is None:
  156. using = DEFAULT_DB_ALIAS
  157. connection = connections[using]
  158. if not is_managed(using=using):
  159. connection._commit()
  160. clean_savepoints(using=using)
  161. else:
  162. set_dirty(using=using)
  163. def rollback_unless_managed(using=None):
  164. """
  165. Rolls back changes if the system is not in managed transaction mode.
  166. """
  167. if using is None:
  168. using = DEFAULT_DB_ALIAS
  169. connection = connections[using]
  170. if not is_managed(using=using):
  171. connection._rollback()
  172. else:
  173. set_dirty(using=using)
  174. def commit(using=None):
  175. """
  176. Does the commit itself and resets the dirty flag.
  177. """
  178. if using is None:
  179. using = DEFAULT_DB_ALIAS
  180. connection = connections[using]
  181. connection._commit()
  182. set_clean(using=using)
  183. def rollback(using=None):
  184. """
  185. This function does the rollback itself and resets the dirty flag.
  186. """
  187. if using is None:
  188. using = DEFAULT_DB_ALIAS
  189. connection = connections[using]
  190. connection._rollback()
  191. set_clean(using=using)
  192. def savepoint(using=None):
  193. """
  194. Creates a savepoint (if supported and required by the backend) inside the
  195. current transaction. Returns an identifier for the savepoint that will be
  196. used for the subsequent rollback or commit.
  197. """
  198. if using is None:
  199. using = DEFAULT_DB_ALIAS
  200. connection = connections[using]
  201. thread_ident = thread.get_ident()
  202. if thread_ident in savepoint_state and using in savepoint_state[thread_ident]:
  203. savepoint_state[thread_ident][using].append(None)
  204. else:
  205. savepoint_state.setdefault(thread_ident, {})
  206. savepoint_state[thread_ident][using] = [None]
  207. tid = str(thread_ident).replace('-', '')
  208. sid = "s%s_x%d" % (tid, len(savepoint_state[thread_ident][using]))
  209. connection._savepoint(sid)
  210. return sid
  211. def savepoint_rollback(sid, using=None):
  212. """
  213. Rolls back the most recent savepoint (if one exists). Does nothing if
  214. savepoints are not supported.
  215. """
  216. if using is None:
  217. using = DEFAULT_DB_ALIAS
  218. connection = connections[using]
  219. thread_ident = thread.get_ident()
  220. if thread_ident in savepoint_state and using in savepoint_state[thread_ident]:
  221. connection._savepoint_rollback(sid)
  222. def savepoint_commit(sid, using=None):
  223. """
  224. Commits the most recent savepoint (if one exists). Does nothing if
  225. savepoints are not supported.
  226. """
  227. if using is None:
  228. using = DEFAULT_DB_ALIAS
  229. connection = connections[using]
  230. thread_ident = thread.get_ident()
  231. if thread_ident in savepoint_state and using in savepoint_state[thread_ident]:
  232. connection._savepoint_commit(sid)
  233. ##############
  234. # DECORATORS #
  235. ##############
  236. def autocommit(using=None):
  237. """
  238. Decorator that activates commit on save. This is Django's default behavior;
  239. this decorator is useful if you globally activated transaction management in
  240. your settings file and want the default behavior in some view functions.
  241. """
  242. def inner_autocommit(func, db=None):
  243. def _autocommit(*args, **kw):
  244. try:
  245. enter_transaction_management(managed=False, using=db)
  246. managed(False, using=db)
  247. return func(*args, **kw)
  248. finally:
  249. leave_transaction_management(using=db)
  250. return wraps(func)(_autocommit)
  251. # Note that although the first argument is *called* `using`, it
  252. # may actually be a function; @autocommit and @autocommit('foo')
  253. # are both allowed forms.
  254. if using is None:
  255. using = DEFAULT_DB_ALIAS
  256. if callable(using):
  257. return inner_autocommit(using, DEFAULT_DB_ALIAS)
  258. return lambda func: inner_autocommit(func, using)
  259. def commit_on_success(using=None):
  260. """
  261. This decorator activates commit on response. This way, if the view function
  262. runs successfully, a commit is made; if the viewfunc produces an exception,
  263. a rollback is made. This is one of the most common ways to do transaction
  264. control in Web apps.
  265. """
  266. def inner_commit_on_success(func, db=None):
  267. def _commit_on_success(*args, **kw):
  268. try:
  269. enter_transaction_management(using=db)
  270. managed(True, using=db)
  271. try:
  272. res = func(*args, **kw)
  273. except:
  274. # All exceptions must be handled here (even string ones).
  275. if is_dirty(using=db):
  276. rollback(using=db)
  277. raise
  278. else:
  279. if is_dirty(using=db):
  280. try:
  281. commit(using=db)
  282. except:
  283. rollback(using=db)
  284. raise
  285. return res
  286. finally:
  287. leave_transaction_management(using=db)
  288. return wraps(func)(_commit_on_success)
  289. # Note that although the first argument is *called* `using`, it
  290. # may actually be a function; @autocommit and @autocommit('foo')
  291. # are both allowed forms.
  292. if using is None:
  293. using = DEFAULT_DB_ALIAS
  294. if callable(using):
  295. return inner_commit_on_success(using, DEFAULT_DB_ALIAS)
  296. return lambda func: inner_commit_on_success(func, using)
  297. def commit_manually(using=None):
  298. """
  299. Decorator that activates manual transaction control. It just disables
  300. automatic transaction control and doesn't do any commit/rollback of its
  301. own -- it's up to the user to call the commit and rollback functions
  302. themselves.
  303. """
  304. def inner_commit_manually(func, db=None):
  305. def _commit_manually(*args, **kw):
  306. try:
  307. enter_transaction_management(using=db)
  308. managed(True, using=db)
  309. return func(*args, **kw)
  310. finally:
  311. leave_transaction_management(using=db)
  312. return wraps(func)(_commit_manually)
  313. # Note that although the first argument is *called* `using`, it
  314. # may actually be a function; @autocommit and @autocommit('foo')
  315. # are both allowed forms.
  316. if using is None:
  317. using = DEFAULT_DB_ALIAS
  318. if callable(using):
  319. return inner_commit_manually(using, DEFAULT_DB_ALIAS)
  320. return lambda func: inner_commit_manually(func, using)