transactions.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. ``CacheMiddleware``, :class:`~django.middleware.cache.UpdateCacheMiddleware`,
  40. and :class:`~django.middleware.cache.FetchFromCacheMiddleware` are never
  41. affected. Even when using database caching, Django's cache backend uses its own
  42. database cursor (which is mapped to its own database connection internally).
  43. .. note::
  44. The ``TransactionMiddleware`` only affects the database aliased
  45. as "default" within your :setting:`DATABASES` setting. If you are using
  46. multiple databases and want transaction control over databases other than
  47. "default", you will need to write your own transaction middleware.
  48. .. _transaction-management-functions:
  49. Controlling transaction management in views
  50. ===========================================
  51. For most people, implicit request-based transactions work wonderfully. However,
  52. if you need more fine-grained control over how transactions are managed, you can
  53. use a set of functions in ``django.db.transaction`` to control transactions on a
  54. per-function or per-code-block basis.
  55. These functions, described in detail below, can be used in two different ways:
  56. * As a decorator_ on a particular function. For example::
  57. from django.db import transaction
  58. @transaction.commit_on_success
  59. def viewfunc(request):
  60. # ...
  61. # this code executes inside a transaction
  62. # ...
  63. * As a `context manager`_ around a particular block of code::
  64. from django.db import transaction
  65. def viewfunc(request):
  66. # ...
  67. # this code executes using default transaction management
  68. # ...
  69. with transaction.commit_on_success():
  70. # ...
  71. # this code executes inside a transaction
  72. # ...
  73. Both techniques work with all supported version of Python.
  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. Whether you are writing or simply reading from the database, you must
  117. ``commit()`` or ``rollback()`` explicitly or Django will raise a
  118. :exc:`TransactionManagementError` exception. This is required when reading
  119. from the database because ``SELECT`` statements may call functions which
  120. modify tables, and thus it is impossible to know if any data has been
  121. modified.
  122. Manual transaction management looks like this::
  123. from django.db import transaction
  124. @transaction.commit_manually
  125. def viewfunc(request):
  126. ...
  127. # You can commit/rollback however and whenever you want
  128. transaction.commit()
  129. ...
  130. # But you've got to remember to do it yourself!
  131. try:
  132. ...
  133. except:
  134. transaction.rollback()
  135. else:
  136. transaction.commit()
  137. @transaction.commit_manually(using="my_other_database")
  138. def viewfunc2(request):
  139. ....
  140. .. _topics-db-transactions-requirements:
  141. Requirements for transaction handling
  142. =====================================
  143. Django requires that every transaction that is opened is closed before
  144. the completion of a request. If you are using :func:`autocommit` (the
  145. default commit mode) or :func:`commit_on_success`, this will be done
  146. for you automatically (with the exception of :ref:`executing custom SQL
  147. <executing-custom-sql>`). However, if you are manually managing
  148. transactions (using the :func:`commit_manually` decorator), you must
  149. ensure that the transaction is either committed or rolled back before
  150. a request is completed.
  151. This applies to all database operations, not just write operations. Even
  152. if your transaction only reads from the database, the transaction must
  153. be committed or rolled back before you complete a request.
  154. .. _deactivate-transaction-management:
  155. How to globally deactivate transaction management
  156. =================================================
  157. Control freaks can totally disable all transaction management by setting
  158. :setting:`TRANSACTIONS_MANAGED` to ``True`` in the Django settings file.
  159. If you do this, Django won't provide any automatic transaction management
  160. whatsoever. Middleware will no longer implicitly commit transactions, and
  161. you'll need to roll management yourself. This even requires you to commit
  162. changes done by middleware somewhere else.
  163. Thus, this is best used in situations where you want to run your own
  164. transaction-controlling middleware or do something really strange. In almost
  165. all situations, you'll be better off using the default behavior, or the
  166. transaction middleware, and only modify selected functions as needed.
  167. .. _topics-db-transactions-savepoints:
  168. Savepoints
  169. ==========
  170. A savepoint is a marker within a transaction that enables you to roll back part
  171. of a transaction, rather than the full transaction. Savepoints are available
  172. with the PostgreSQL 8, Oracle and MySQL (when using the InnoDB storage engine)
  173. backends. Other backends provide the savepoint functions, but they're empty
  174. operations -- they don't actually do anything.
  175. Savepoints aren't especially useful if you are using the default
  176. ``autocommit`` behavior of Django. However, if you are using
  177. ``commit_on_success`` or ``commit_manually``, each open transaction will build
  178. up a series of database operations, awaiting a commit or rollback. If you
  179. issue a rollback, the entire transaction is rolled back. Savepoints provide
  180. the ability to perform a fine-grained rollback, rather than the full rollback
  181. that would be performed by ``transaction.rollback()``.
  182. Each of these functions takes a ``using`` argument which should be the name of
  183. a database for which the behavior applies. If no ``using`` argument is
  184. provided then the ``"default"`` database is used.
  185. Savepoints are controlled by three methods on the transaction object:
  186. .. method:: transaction.savepoint(using=None)
  187. Creates a new savepoint. This marks a point in the transaction that
  188. is known to be in a "good" state.
  189. Returns the savepoint ID (sid).
  190. .. method:: transaction.savepoint_commit(sid, using=None)
  191. Updates the savepoint to include any operations that have been performed
  192. since the savepoint was created, or since the last commit.
  193. .. method:: transaction.savepoint_rollback(sid, using=None)
  194. Rolls the transaction back to the last point at which the savepoint was
  195. committed.
  196. The following example demonstrates the use of savepoints::
  197. from django.db import transaction
  198. @transaction.commit_manually
  199. def viewfunc(request):
  200. a.save()
  201. # open transaction now contains a.save()
  202. sid = transaction.savepoint()
  203. b.save()
  204. # open transaction now contains a.save() and b.save()
  205. if want_to_keep_b:
  206. transaction.savepoint_commit(sid)
  207. # open transaction still contains a.save() and b.save()
  208. else:
  209. transaction.savepoint_rollback(sid)
  210. # open transaction now contains only a.save()
  211. transaction.commit()
  212. Transactions in MySQL
  213. =====================
  214. If you're using MySQL, your tables may or may not support transactions; it
  215. depends on your MySQL version and the table types you're using. (By
  216. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  217. peculiarities are outside the scope of this article, but the MySQL site has
  218. `information on MySQL transactions`_.
  219. If your MySQL setup does *not* support transactions, then Django will function
  220. in auto-commit mode: Statements will be executed and committed as soon as
  221. they're called. If your MySQL setup *does* support transactions, Django will
  222. handle transactions as explained in this document.
  223. .. _information on MySQL transactions: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html
  224. Handling exceptions within PostgreSQL transactions
  225. ==================================================
  226. When a call to a PostgreSQL cursor raises an exception (typically
  227. ``IntegrityError``), all subsequent SQL in the same transaction will fail with
  228. the error "current transaction is aborted, queries ignored until end of
  229. transaction block". Whilst simple use of ``save()`` is unlikely to raise an
  230. exception in PostgreSQL, there are more advanced usage patterns which
  231. might, such as saving objects with unique fields, saving using the
  232. force_insert/force_update flag, or invoking custom SQL.
  233. There are several ways to recover from this sort of error.
  234. Transaction rollback
  235. --------------------
  236. The first option is to roll back the entire transaction. For example::
  237. a.save() # Succeeds, but may be undone by transaction rollback
  238. try:
  239. b.save() # Could throw exception
  240. except IntegrityError:
  241. transaction.rollback()
  242. c.save() # Succeeds, but a.save() may have been undone
  243. Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  244. uncommitted database operations will be lost. In this example, the changes
  245. made by ``a.save()`` would be lost, even though that operation raised no error
  246. itself.
  247. Savepoint rollback
  248. ------------------
  249. If you are using PostgreSQL 8 or later, you can use :ref:`savepoints
  250. <topics-db-transactions-savepoints>` to control the extent of a rollback.
  251. Before performing a database operation that could fail, you can set or update
  252. the savepoint; that way, if the operation fails, you can roll back the single
  253. offending operation, rather than the entire transaction. For example::
  254. a.save() # Succeeds, and never undone by savepoint rollback
  255. try:
  256. sid = transaction.savepoint()
  257. b.save() # Could throw exception
  258. transaction.savepoint_commit(sid)
  259. except IntegrityError:
  260. transaction.savepoint_rollback(sid)
  261. c.save() # Succeeds, and a.save() is never undone
  262. In this example, ``a.save()`` will not be undone in the case where
  263. ``b.save()`` raises an exception.
  264. Database-level autocommit
  265. -------------------------
  266. With PostgreSQL 8.2 or later, there is an advanced option to run PostgreSQL
  267. with :doc:`database-level autocommit </ref/databases>`. If you use this option,
  268. there is no constantly open transaction, so it is always possible to continue
  269. after catching an exception. For example::
  270. a.save() # succeeds
  271. try:
  272. b.save() # Could throw exception
  273. except IntegrityError:
  274. pass
  275. c.save() # succeeds
  276. .. note::
  277. This is not the same as the :ref:`autocommit decorator
  278. <topics-db-transactions-autocommit>`. When using database level autocommit
  279. there is no database transaction at all. The ``autocommit`` decorator
  280. still uses transactions, automatically committing each transaction when
  281. a database modifying operation occurs.