PageRenderTime 70ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

Plain Text | 378 lines | 277 code | 101 blank | 0 comment | 0 complexity | 790d06a34bebfd6c5ef444b0bd022f1a MD5 | raw file
Possible License(s): BSD-3-Clause
  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 ```` 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::
  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. This technique works with all supported version of Python (that is, with
  62. Python 2.4 and greater).
  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. The ``with`` statement is new in Python 2.5, and so this syntax can only
  74. be used with Python 2.5 and above.
  75. .. _decorator:
  76. .. _context manager:
  77. For maximum compatibility, all of the examples below show transactions using the
  78. decorator syntax, but all of the follow functions may be used as context
  79. managers, too.
  80. .. note::
  81. Although the examples below use view functions as examples, these
  82. decorators and context managers can be used anywhere in your code
  83. that you need to deal with transactions.
  84. .. _topics-db-transactions-autocommit:
  85. .. function:: autocommit
  86. Use the ``autocommit`` decorator to switch a view function to Django's
  87. default commit behavior, regardless of the global transaction setting.
  88. Example::
  89. from django.db import transaction
  90. @transaction.autocommit
  91. def viewfunc(request):
  92. ....
  93. @transaction.autocommit(using="my_other_database")
  94. def viewfunc2(request):
  95. ....
  96. Within ``viewfunc()``, transactions will be committed as soon as you call
  97. ````, ``model.delete()``, or any other function that writes to
  98. the database. ``viewfunc2()`` will have this same behavior, but for the
  99. ``"my_other_database"`` connection.
  100. .. function:: commit_on_success
  101. Use the ``commit_on_success`` decorator to use a single transaction for all
  102. the work done in a function::
  103. from django.db import transaction
  104. @transaction.commit_on_success
  105. def viewfunc(request):
  106. ....
  107. @transaction.commit_on_success(using="my_other_database")
  108. def viewfunc2(request):
  109. ....
  110. If the function returns successfully, then Django will commit all work done
  111. within the function at that point. If the function raises an exception,
  112. though, Django will roll back the transaction.
  113. .. function:: commit_manually
  114. Use the ``commit_manually`` decorator if you need full control over
  115. transactions. It tells Django you'll be managing the transaction on your
  116. own.
  117. If your view changes data and doesn't ``commit()`` or ``rollback()``,
  118. Django will raise a ``TransactionManagementError`` exception.
  119. Manual transaction management looks like this::
  120. from django.db import transaction
  121. @transaction.commit_manually
  122. def viewfunc(request):
  123. ...
  124. # You can commit/rollback however and whenever you want
  125. transaction.commit()
  126. ...
  127. # But you've got to remember to do it yourself!
  128. try:
  129. ...
  130. except:
  131. transaction.rollback()
  132. else:
  133. transaction.commit()
  134. @transaction.commit_manually(using="my_other_database")
  135. def viewfunc2(request):
  136. ....
  137. .. _topics-db-transactions-requirements:
  138. Requirements for transaction handling
  139. =====================================
  140. .. versionadded:: 1.3
  141. Django requires that every transaction that is opened is closed before
  142. the completion of a request. If you are using :func:`autocommit` (the
  143. default commit mode) or :func:`commit_on_success`, this will be done
  144. for you automatically. However, if you are manually managing
  145. transactions (using the :func:`commit_manually` decorator), you must
  146. ensure that the transaction is either committed or rolled back before
  147. a request is completed.
  148. This applies to all database operations, not just write operations. Even
  149. if your transaction only reads from the database, the transaction must
  150. be committed or rolled back before you complete a request.
  151. How to globally deactivate transaction management
  152. =================================================
  153. Control freaks can totally disable all transaction management by setting
  154. ``DISABLE_TRANSACTION_MANAGEMENT`` to ``True`` in the Django settings file.
  155. If you do this, Django won't provide any automatic transaction management
  156. whatsoever. Middleware will no longer implicitly commit transactions, and
  157. you'll need to roll management yourself. This even requires you to commit
  158. changes done by middleware somewhere else.
  159. Thus, this is best used in situations where you want to run your own
  160. transaction-controlling middleware or do something really strange. In almost
  161. all situations, you'll be better off using the default behavior, or the
  162. transaction middleware, and only modify selected functions as needed.
  163. .. _topics-db-transactions-savepoints:
  164. Savepoints
  165. ==========
  166. A savepoint is a marker within a transaction that enables you to roll back
  167. part of a transaction, rather than the full transaction. Savepoints are
  168. available to the PostgreSQL 8 and Oracle backends. Other backends will
  169. provide the savepoint functions, but they are empty operations - they won't
  170. actually do anything.
  171. Savepoints aren't especially useful if you are using the default
  172. ``autocommit`` behavior of Django. However, if you are using
  173. ``commit_on_success`` or ``commit_manually``, each open transaction will build
  174. up a series of database operations, awaiting a commit or rollback. If you
  175. issue a rollback, the entire transaction is rolled back. Savepoints provide
  176. the ability to perform a fine-grained rollback, rather than the full rollback
  177. that would be performed by ``transaction.rollback()``.
  178. Each of these functions takes a ``using`` argument which should be the name of
  179. a database for which the behavior applies. If no ``using`` argument is
  180. provided then the ``"default"`` database is used.
  181. Savepoints are controlled by three methods on the transaction object:
  182. .. method:: transaction.savepoint(using=None)
  183. Creates a new savepoint. This marks a point in the transaction that
  184. is known to be in a "good" state.
  185. Returns the savepoint ID (sid).
  186. .. method:: transaction.savepoint_commit(sid, using=None)
  187. Updates the savepoint to include any operations that have been performed
  188. since the savepoint was created, or since the last commit.
  189. .. method:: transaction.savepoint_rollback(sid, using=None)
  190. Rolls the transaction back to the last point at which the savepoint was
  191. committed.
  192. The following example demonstrates the use of savepoints::
  193. from django.db import transaction
  194. @transaction.commit_manually
  195. def viewfunc(request):
  197. # open transaction now contains
  198. sid = transaction.savepoint()
  200. # open transaction now contains and
  201. if want_to_keep_b:
  202. transaction.savepoint_commit(sid)
  203. # open transaction still contains and
  204. else:
  205. transaction.savepoint_rollback(sid)
  206. # open transaction now contains only
  207. transaction.commit()
  208. Transactions in MySQL
  209. =====================
  210. If you're using MySQL, your tables may or may not support transactions; it
  211. depends on your MySQL version and the table types you're using. (By
  212. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  213. peculiarities are outside the scope of this article, but the MySQL site has
  214. `information on MySQL transactions`_.
  215. If your MySQL setup does *not* support transactions, then Django will function
  216. in auto-commit mode: Statements will be executed and committed as soon as
  217. they're called. If your MySQL setup *does* support transactions, Django will
  218. handle transactions as explained in this document.
  219. .. _information on MySQL transactions:
  220. Handling exceptions within PostgreSQL transactions
  221. ==================================================
  222. When a call to a PostgreSQL cursor raises an exception (typically
  223. ``IntegrityError``), all subsequent SQL in the same transaction will fail with
  224. the error "current transaction is aborted, queries ignored until end of
  225. transaction block". Whilst simple use of ``save()`` is unlikely to raise an
  226. exception in PostgreSQL, there are more advanced usage patterns which
  227. might, such as saving objects with unique fields, saving using the
  228. force_insert/force_update flag, or invoking custom SQL.
  229. There are several ways to recover from this sort of error.
  230. Transaction rollback
  231. --------------------
  232. The first option is to roll back the entire transaction. For example::
  233. # Succeeds, but may be undone by transaction rollback
  234. try:
  235. # Could throw exception
  236. except IntegrityError:
  237. transaction.rollback()
  238. # Succeeds, but may have been undone
  239. Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  240. uncommitted database operations will be lost. In this example, the changes
  241. made by ```` would be lost, even though that operation raised no error
  242. itself.
  243. Savepoint rollback
  244. ------------------
  245. If you are using PostgreSQL 8 or later, you can use :ref:`savepoints
  246. <topics-db-transactions-savepoints>` to control the extent of a rollback.
  247. Before performing a database operation that could fail, you can set or update
  248. the savepoint; that way, if the operation fails, you can roll back the single
  249. offending operation, rather than the entire transaction. For example::
  250. # Succeeds, and never undone by savepoint rollback
  251. try:
  252. sid = transaction.savepoint()
  253. # Could throw exception
  254. transaction.savepoint_commit(sid)
  255. except IntegrityError:
  256. transaction.savepoint_rollback(sid)
  257. # Succeeds, and is never undone
  258. In this example, ```` will not be undone in the case where
  259. ```` raises an exception.
  260. Database-level autocommit
  261. -------------------------
  262. With PostgreSQL 8.2 or later, there is an advanced option to run PostgreSQL
  263. with :doc:`database-level autocommit </ref/databases>`. If you use this option,
  264. there is no constantly open transaction, so it is always possible to continue
  265. after catching an exception. For example::
  266. # succeeds
  267. try:
  268. # Could throw exception
  269. except IntegrityError:
  270. pass
  271. # succeeds
  272. .. note::
  273. This is not the same as the :ref:`autocommit decorator
  274. <topics-db-transactions-autocommit>`. When using database level autocommit
  275. there is no database transaction at all. The ``autocommit`` decorator
  276. still uses transactions, automatically committing each transaction when
  277. a database modifying operation occurs.