transactions.txt 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. .. _topics-db-transactions:
  2. ==============================
  3. Managing database transactions
  4. ==============================
  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 ``MIDDLEWARE_CLASSES`` setting::
  27. MIDDLEWARE_CLASSES = (
  28. 'django.contrib.sessions.middleware.SessionMiddleware',
  29. 'django.middleware.common.CommonMiddleware',
  30. 'django.middleware.cache.CacheMiddleware',
  31. 'django.middleware.transaction.TransactionMiddleware',
  32. )
  33. The order is quite important. The transaction middleware applies not only to
  34. view functions, but also for all middleware modules that come after it. So if
  35. you use the session middleware after the transaction middleware, session
  36. creation will be part of the transaction.
  37. An exception is ``CacheMiddleware``, which is never affected. The cache
  38. middleware uses its own database cursor (which is mapped to its own database
  39. connection internally).
  40. Controlling transaction management in views
  41. ===========================================
  42. For most people, implicit request-based transactions work wonderfully. However,
  43. if you need more fine-grained control over how transactions are managed, you
  44. can use Python decorators to change the way transactions are handled by a
  45. particular view function.
  46. .. note::
  47. Although the examples below use view functions as examples, these
  48. decorators can be applied to non-view functions as well.
  49. .. _topics-db-transactions-autocommit:
  50. ``django.db.transaction.autocommit``
  51. ------------------------------------
  52. Use the ``autocommit`` decorator to switch a view function to Django's default
  53. commit behavior, regardless of the global transaction setting.
  54. Example::
  55. from django.db import transaction
  56. @transaction.autocommit
  57. def viewfunc(request):
  58. ....
  59. Within ``viewfunc()``, transactions will be committed as soon as you call
  60. ``model.save()``, ``model.delete()``, or any other function that writes to the
  61. database.
  62. ``django.db.transaction.commit_on_success``
  63. -------------------------------------------
  64. Use the ``commit_on_success`` decorator to use a single transaction for
  65. all the work done in a function::
  66. from django.db import transaction
  67. @transaction.commit_on_success
  68. def viewfunc(request):
  69. ....
  70. If the function returns successfully, then Django will commit all work done
  71. within the function at that point. If the function raises an exception, though,
  72. Django will roll back the transaction.
  73. ``django.db.transaction.commit_manually``
  74. -----------------------------------------
  75. Use the ``commit_manually`` decorator if you need full control over
  76. transactions. It tells Django you'll be managing the transaction on your own.
  77. If your view changes data and doesn't ``commit()`` or ``rollback()``, Django
  78. will raise a ``TransactionManagementError`` exception.
  79. Manual transaction management looks like this::
  80. from django.db import transaction
  81. @transaction.commit_manually
  82. def viewfunc(request):
  83. ...
  84. # You can commit/rollback however and whenever you want
  85. transaction.commit()
  86. ...
  87. # But you've got to remember to do it yourself!
  88. try:
  89. ...
  90. except:
  91. transaction.rollback()
  92. else:
  93. transaction.commit()
  94. .. admonition:: An important note to users of earlier Django releases:
  95. The database ``connection.commit()`` and ``connection.rollback()`` methods
  96. (called ``db.commit()`` and ``db.rollback()`` in 0.91 and earlier) no
  97. longer exist. They've been replaced by ``transaction.commit()`` and
  98. ``transaction.rollback()``.
  99. How to globally deactivate transaction management
  100. =================================================
  101. Control freaks can totally disable all transaction management by setting
  102. ``DISABLE_TRANSACTION_MANAGEMENT`` to ``True`` in the Django settings file.
  103. If you do this, Django won't provide any automatic transaction management
  104. whatsoever. Middleware will no longer implicitly commit transactions, and
  105. you'll need to roll management yourself. This even requires you to commit
  106. changes done by middleware somewhere else.
  107. Thus, this is best used in situations where you want to run your own
  108. transaction-controlling middleware or do something really strange. In almost
  109. all situations, you'll be better off using the default behavior, or the
  110. transaction middleware, and only modify selected functions as needed.
  111. Transactions in MySQL
  112. =====================
  113. If you're using MySQL, your tables may or may not support transactions; it
  114. depends on your MySQL version and the table types you're using. (By
  115. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  116. peculiarities are outside the scope of this article, but the MySQL site has
  117. `information on MySQL transactions`_.
  118. If your MySQL setup does *not* support transactions, then Django will function
  119. in auto-commit mode: Statements will be executed and committed as soon as
  120. they're called. If your MySQL setup *does* support transactions, Django will
  121. handle transactions as explained in this document.
  122. .. _information on MySQL transactions: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html
  123. Transactions and savepoints in PostgreSQL 8
  124. ===========================================
  125. When a call to a PostgreSQL 8 cursor raises an exception, all subsequent SQL
  126. in the same transaction fails with the error "current transaction is aborted,
  127. queries ignored until end of transaction block". Whilst simple use of save()
  128. is unlikely to raise an exception in PostgreSQL, there are many more advanced
  129. usage patterns which might: for example, saving objects with unique fields,
  130. saving using the force_insert/force_update flag, or invoking custom SQL.
  131. In any of these cases, you can wrap the command which may throw
  132. IntegrityError inside savepoints, which will then allow subsequent commands
  133. to proceed. Example::
  134. try:
  135. sid = transaction.savepoint()
  136. x.save()
  137. transaction.savepoint_commit(sid)
  138. except IntegrityError:
  139. transaction.savepoint_rollback(sid)
  140. raise
  141. Savepoints are not implemented in PostgreSQL 7. If you experience an
  142. IntegrityError when using PostgreSQL 7, you will need to rollback to the
  143. start of the transaction.