transactions.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. ==============================
  2. Managing database transactions
  3. ==============================
  4. .. module:: django.db.transaction
  5. Django gives you a few ways to control how database transactions are managed,
  6. if you're using a database that supports transactions.
  7. Django's default transaction behavior
  8. =====================================
  9. Django's default behavior is to run with an open transaction which it
  10. commits automatically when any built-in, data-altering model function is
  11. called. For example, if you call ``model.save()`` or ``model.delete()``, the
  12. change will be committed immediately.
  13. This is much like the auto-commit setting for most databases. As soon as you
  14. perform an action that needs to write to the database, Django produces the
  15. ``INSERT``/``UPDATE``/``DELETE`` statements and then does the ``COMMIT``.
  16. There's no implicit ``ROLLBACK``.
  17. Tying transactions to HTTP requests
  18. ===================================
  19. The recommended way to handle transactions in Web requests is to tie them to
  20. the request and response phases via Django's ``TransactionMiddleware``.
  21. It works like this: When a request starts, Django starts a transaction. If the
  22. response is produced without problems, Django commits any pending transactions.
  23. If the view function produces an exception, Django rolls back any pending
  24. transactions.
  25. To activate this feature, just add the ``TransactionMiddleware`` middleware to
  26. your :setting:`MIDDLEWARE_CLASSES` setting::
  27. MIDDLEWARE_CLASSES = (
  28. 'django.middleware.cache.UpdateCacheMiddleware',
  29. 'django.contrib.sessions.middleware.SessionMiddleware',
  30. 'django.middleware.common.CommonMiddleware',
  31. 'django.middleware.transaction.TransactionMiddleware',
  32. 'django.middleware.cache.FetchFromCacheMiddleware',
  33. )
  34. The order is quite important. The transaction middleware applies not only to
  35. view functions, but also for all middleware modules that come after it. So if
  36. you use the session middleware after the transaction middleware, session
  37. creation will be part of the transaction.
  38. The various cache middlewares are an exception:
  39. :class:`~django.middleware.cache.CacheMiddleware`,
  40. :class:`~django.middleware.cache.UpdateCacheMiddleware`, and
  41. :class:`~django.middleware.cache.FetchFromCacheMiddleware` are never affected.
  42. Even when using database caching, Django's cache backend uses its own
  43. database cursor (which is mapped to its own database connection internally).
  44. .. _transaction-management-functions:
  45. Controlling transaction management in views
  46. ===========================================
  47. .. versionchanged:: 1.3
  48. Transaction management context managers are new in Django 1.3.
  49. For most people, implicit request-based transactions work wonderfully. However,
  50. if you need more fine-grained control over how transactions are managed, you can
  51. use a set of functions in ``django.db.transaction`` to control transactions on a
  52. per-function or per-code-block basis.
  53. These functions, described in detail below, can be used in two different ways:
  54. * As a decorator_ on a particular function. For example::
  55. from django.db import transaction
  56. @transaction.commit_on_success
  57. def viewfunc(request):
  58. # ...
  59. # this code executes inside a transaction
  60. # ...
  61. * As a `context manager`_ around a particular block of code::
  62. from django.db import transaction
  63. def viewfunc(request):
  64. # ...
  65. # this code executes using default transaction management
  66. # ...
  67. with transaction.commit_on_success():
  68. # ...
  69. # this code executes inside a transaction
  70. # ...
  71. Both techniques work with all supported version of Python. However, in Python
  72. 2.5, you must add ``from __future__ import with_statement`` at the beginning
  73. of your module if you are using the ``with`` statement.
  74. .. _decorator: http://docs.python.org/glossary.html#term-decorator
  75. .. _context manager: http://docs.python.org/glossary.html#term-context-manager
  76. For maximum compatibility, all of the examples below show transactions using the
  77. decorator syntax, but all of the follow functions may be used as context
  78. managers, too.
  79. .. note::
  80. Although the examples below use view functions as examples, these
  81. decorators and context managers can be used anywhere in your code
  82. that you need to deal with transactions.
  83. .. _topics-db-transactions-autocommit:
  84. .. function:: autocommit
  85. Use the ``autocommit`` decorator to switch a view function to Django's
  86. default commit behavior, regardless of the global transaction setting.
  87. Example::
  88. from django.db import transaction
  89. @transaction.autocommit
  90. def viewfunc(request):
  91. ....
  92. @transaction.autocommit(using="my_other_database")
  93. def viewfunc2(request):
  94. ....
  95. Within ``viewfunc()``, transactions will be committed as soon as you call
  96. ``model.save()``, ``model.delete()``, or any other function that writes to
  97. the database. ``viewfunc2()`` will have this same behavior, but for the
  98. ``"my_other_database"`` connection.
  99. .. function:: commit_on_success
  100. Use the ``commit_on_success`` decorator to use a single transaction for all
  101. the work done in a function::
  102. from django.db import transaction
  103. @transaction.commit_on_success
  104. def viewfunc(request):
  105. ....
  106. @transaction.commit_on_success(using="my_other_database")
  107. def viewfunc2(request):
  108. ....
  109. If the function returns successfully, then Django will commit all work done
  110. within the function at that point. If the function raises an exception,
  111. though, Django will roll back the transaction.
  112. .. function:: commit_manually
  113. Use the ``commit_manually`` decorator if you need full control over
  114. transactions. It tells Django you'll be managing the transaction on your
  115. own.
  116. If your view changes data and doesn't ``commit()`` or ``rollback()``,
  117. Django will raise a ``TransactionManagementError`` exception.
  118. Manual transaction management looks like this::
  119. from django.db import transaction
  120. @transaction.commit_manually
  121. def viewfunc(request):
  122. ...
  123. # You can commit/rollback however and whenever you want
  124. transaction.commit()
  125. ...
  126. # But you've got to remember to do it yourself!
  127. try:
  128. ...
  129. except:
  130. transaction.rollback()
  131. else:
  132. transaction.commit()
  133. @transaction.commit_manually(using="my_other_database")
  134. def viewfunc2(request):
  135. ....
  136. .. _topics-db-transactions-requirements:
  137. Requirements for transaction handling
  138. =====================================
  139. .. versionadded:: 1.3
  140. Django requires that every transaction that is opened is closed before
  141. the completion of a request. If you are using :func:`autocommit` (the
  142. default commit mode) or :func:`commit_on_success`, this will be done
  143. for you automatically. However, if you are manually managing
  144. transactions (using the :func:`commit_manually` decorator), you must
  145. ensure that the transaction is either committed or rolled back before
  146. a request is completed.
  147. This applies to all database operations, not just write operations. Even
  148. if your transaction only reads from the database, the transaction must
  149. be committed or rolled back before you complete a request.
  150. How to globally deactivate transaction management
  151. =================================================
  152. Control freaks can totally disable all transaction management by setting
  153. ``DISABLE_TRANSACTION_MANAGEMENT`` to ``True`` in the Django settings file.
  154. If you do this, Django won't provide any automatic transaction management
  155. whatsoever. Middleware will no longer implicitly commit transactions, and
  156. you'll need to roll management yourself. This even requires you to commit
  157. changes done by middleware somewhere else.
  158. Thus, this is best used in situations where you want to run your own
  159. transaction-controlling middleware or do something really strange. In almost
  160. all situations, you'll be better off using the default behavior, or the
  161. transaction middleware, and only modify selected functions as needed.
  162. .. _topics-db-transactions-savepoints:
  163. Savepoints
  164. ==========
  165. A savepoint is a marker within a transaction that enables you to roll back
  166. part of a transaction, rather than the full transaction. Savepoints are
  167. available to the PostgreSQL 8 and Oracle backends. Other backends will
  168. provide the savepoint functions, but they are empty operations - they won't
  169. actually do anything.
  170. Savepoints aren't especially useful if you are using the default
  171. ``autocommit`` behavior of Django. However, if you are using
  172. ``commit_on_success`` or ``commit_manually``, each open transaction will build
  173. up a series of database operations, awaiting a commit or rollback. If you
  174. issue a rollback, the entire transaction is rolled back. Savepoints provide
  175. the ability to perform a fine-grained rollback, rather than the full rollback
  176. that would be performed by ``transaction.rollback()``.
  177. Each of these functions takes a ``using`` argument which should be the name of
  178. a database for which the behavior applies. If no ``using`` argument is
  179. provided then the ``"default"`` database is used.
  180. Savepoints are controlled by three methods on the transaction object:
  181. .. method:: transaction.savepoint(using=None)
  182. Creates a new savepoint. This marks a point in the transaction that
  183. is known to be in a "good" state.
  184. Returns the savepoint ID (sid).
  185. .. method:: transaction.savepoint_commit(sid, using=None)
  186. Updates the savepoint to include any operations that have been performed
  187. since the savepoint was created, or since the last commit.
  188. .. method:: transaction.savepoint_rollback(sid, using=None)
  189. Rolls the transaction back to the last point at which the savepoint was
  190. committed.
  191. The following example demonstrates the use of savepoints::
  192. from django.db import transaction
  193. @transaction.commit_manually
  194. def viewfunc(request):
  195. a.save()
  196. # open transaction now contains a.save()
  197. sid = transaction.savepoint()
  198. b.save()
  199. # open transaction now contains a.save() and b.save()
  200. if want_to_keep_b:
  201. transaction.savepoint_commit(sid)
  202. # open transaction still contains a.save() and b.save()
  203. else:
  204. transaction.savepoint_rollback(sid)
  205. # open transaction now contains only a.save()
  206. transaction.commit()
  207. Transactions in MySQL
  208. =====================
  209. If you're using MySQL, your tables may or may not support transactions; it
  210. depends on your MySQL version and the table types you're using. (By
  211. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  212. peculiarities are outside the scope of this article, but the MySQL site has
  213. `information on MySQL transactions`_.
  214. If your MySQL setup does *not* support transactions, then Django will function
  215. in auto-commit mode: Statements will be executed and committed as soon as
  216. they're called. If your MySQL setup *does* support transactions, Django will
  217. handle transactions as explained in this document.
  218. .. _information on MySQL transactions: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html
  219. Handling exceptions within PostgreSQL transactions
  220. ==================================================
  221. When a call to a PostgreSQL cursor raises an exception (typically
  222. ``IntegrityError``), all subsequent SQL in the same transaction will fail with
  223. the error "current transaction is aborted, queries ignored until end of
  224. transaction block". Whilst simple use of ``save()`` is unlikely to raise an
  225. exception in PostgreSQL, there are more advanced usage patterns which
  226. might, such as saving objects with unique fields, saving using the
  227. force_insert/force_update flag, or invoking custom SQL.
  228. There are several ways to recover from this sort of error.
  229. Transaction rollback
  230. --------------------
  231. The first option is to roll back the entire transaction. For example::
  232. a.save() # Succeeds, but may be undone by transaction rollback
  233. try:
  234. b.save() # Could throw exception
  235. except IntegrityError:
  236. transaction.rollback()
  237. c.save() # Succeeds, but a.save() may have been undone
  238. Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  239. uncommitted database operations will be lost. In this example, the changes
  240. made by ``a.save()`` would be lost, even though that operation raised no error
  241. itself.
  242. Savepoint rollback
  243. ------------------
  244. If you are using PostgreSQL 8 or later, you can use :ref:`savepoints
  245. <topics-db-transactions-savepoints>` to control the extent of a rollback.
  246. Before performing a database operation that could fail, you can set or update
  247. the savepoint; that way, if the operation fails, you can roll back the single
  248. offending operation, rather than the entire transaction. For example::
  249. a.save() # Succeeds, and never undone by savepoint rollback
  250. try:
  251. sid = transaction.savepoint()
  252. b.save() # Could throw exception
  253. transaction.savepoint_commit(sid)
  254. except IntegrityError:
  255. transaction.savepoint_rollback(sid)
  256. c.save() # Succeeds, and a.save() is never undone
  257. In this example, ``a.save()`` will not be undone in the case where
  258. ``b.save()`` raises an exception.
  259. Database-level autocommit
  260. -------------------------
  261. With PostgreSQL 8.2 or later, there is an advanced option to run PostgreSQL
  262. with :doc:`database-level autocommit </ref/databases>`. If you use this option,
  263. there is no constantly open transaction, so it is always possible to continue
  264. after catching an exception. For example::
  265. a.save() # succeeds
  266. try:
  267. b.save() # Could throw exception
  268. except IntegrityError:
  269. pass
  270. c.save() # succeeds
  271. .. note::
  272. This is not the same as the :ref:`autocommit decorator
  273. <topics-db-transactions-autocommit>`. When using database level autocommit
  274. there is no database transaction at all. The ``autocommit`` decorator
  275. still uses transactions, automatically committing each transaction when
  276. a database modifying operation occurs.