transactions.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. Django's default transaction behavior
  7. =====================================
  8. Django's default behavior is to run in autocommit mode. Each query is
  9. immediately committed to the database. :ref:`See below for details
  10. <autocommit-details>`.
  11. ..
  12. Django uses transactions or savepoints automatically to guarantee the
  13. integrity of ORM operations that require multiple queries, especially
  14. :ref:`delete() <topics-db-queries-delete>` and :ref:`update()
  15. <topics-db-queries-update>` queries.
  16. .. versionchanged:: 1.6
  17. Previous version of Django featured :ref:`a more complicated default
  18. behavior <transactions-changes-from-1.5>`.
  19. Tying transactions to HTTP requests
  20. ===================================
  21. The recommended way to handle transactions in Web requests is to tie them to
  22. the request and response phases via Django's ``TransactionMiddleware``.
  23. It works like this. When a request starts, Django starts a transaction. If the
  24. response is produced without problems, Django commits any pending transactions.
  25. If the view function produces an exception, Django rolls back any pending
  26. transactions.
  27. To activate this feature, just add the ``TransactionMiddleware`` middleware to
  28. your :setting:`MIDDLEWARE_CLASSES` setting::
  29. MIDDLEWARE_CLASSES = (
  30. 'django.middleware.cache.UpdateCacheMiddleware',
  31. 'django.contrib.sessions.middleware.SessionMiddleware',
  32. 'django.middleware.common.CommonMiddleware',
  33. 'django.middleware.transaction.TransactionMiddleware',
  34. 'django.middleware.cache.FetchFromCacheMiddleware',
  35. )
  36. The order is quite important. The transaction middleware applies not only to
  37. view functions, but also for all middleware modules that come after it. So if
  38. you use the session middleware after the transaction middleware, session
  39. creation will be part of the transaction.
  40. The various cache middlewares are an exception: ``CacheMiddleware``,
  41. :class:`~django.middleware.cache.UpdateCacheMiddleware`, and
  42. :class:`~django.middleware.cache.FetchFromCacheMiddleware` are never affected.
  43. Even when using database caching, Django's cache backend uses its own database
  44. connection internally.
  45. .. note::
  46. The ``TransactionMiddleware`` only affects the database aliased
  47. as "default" within your :setting:`DATABASES` setting. If you are using
  48. multiple databases and want transaction control over databases other than
  49. "default", you will need to write your own transaction middleware.
  50. .. _transaction-management-functions:
  51. Controlling transaction management in views
  52. ===========================================
  53. For most people, implicit request-based transactions work wonderfully. However,
  54. if you need more fine-grained control over how transactions are managed, you can
  55. use a set of functions in ``django.db.transaction`` to control transactions on a
  56. per-function or per-code-block basis.
  57. These functions, described in detail below, can be used in two different ways:
  58. * As a decorator_ on a particular function. For example::
  59. from django.db import transaction
  60. @transaction.commit_on_success
  61. def viewfunc(request):
  62. # ...
  63. # this code executes inside a transaction
  64. # ...
  65. * As a `context manager`_ around a particular block of code::
  66. from django.db import transaction
  67. def viewfunc(request):
  68. # ...
  69. # this code executes using default transaction management
  70. # ...
  71. with transaction.commit_on_success():
  72. # ...
  73. # this code executes inside a transaction
  74. # ...
  75. Both techniques work with all supported version of Python.
  76. .. _decorator: http://docs.python.org/glossary.html#term-decorator
  77. .. _context manager: http://docs.python.org/glossary.html#term-context-manager
  78. For maximum compatibility, all of the examples below show transactions using the
  79. decorator syntax, but all of the follow functions may be used as context
  80. managers, too.
  81. .. note::
  82. Although the examples below use view functions as examples, these
  83. decorators and context managers can be used anywhere in your code
  84. that you need to deal with transactions.
  85. .. _topics-db-transactions-autocommit:
  86. .. function:: autocommit
  87. Use the ``autocommit`` decorator to switch a view function to Django's
  88. default commit behavior.
  89. Example::
  90. from django.db import transaction
  91. @transaction.autocommit
  92. def viewfunc(request):
  93. ....
  94. @transaction.autocommit(using="my_other_database")
  95. def viewfunc2(request):
  96. ....
  97. Within ``viewfunc()``, transactions will be committed as soon as you call
  98. ``model.save()``, ``model.delete()``, or any other function that writes to
  99. the database. ``viewfunc2()`` will have this same behavior, but for the
  100. ``"my_other_database"`` connection.
  101. .. function:: commit_on_success
  102. Use the ``commit_on_success`` decorator to use a single transaction for all
  103. the work done in a function::
  104. from django.db import transaction
  105. @transaction.commit_on_success
  106. def viewfunc(request):
  107. ....
  108. @transaction.commit_on_success(using="my_other_database")
  109. def viewfunc2(request):
  110. ....
  111. If the function returns successfully, then Django will commit all work done
  112. within the function at that point. If the function raises an exception,
  113. though, Django will roll back the transaction.
  114. .. function:: commit_manually
  115. Use the ``commit_manually`` decorator if you need full control over
  116. transactions. It tells Django you'll be managing the transaction on your
  117. own.
  118. Whether you are writing or simply reading from the database, you must
  119. ``commit()`` or ``rollback()`` explicitly or Django will raise a
  120. :exc:`TransactionManagementError` exception. This is required when reading
  121. from the database because ``SELECT`` statements may call functions which
  122. modify tables, and thus it is impossible to know if any data has been
  123. modified.
  124. Manual transaction management looks like this::
  125. from django.db import transaction
  126. @transaction.commit_manually
  127. def viewfunc(request):
  128. ...
  129. # You can commit/rollback however and whenever you want
  130. transaction.commit()
  131. ...
  132. # But you've got to remember to do it yourself!
  133. try:
  134. ...
  135. except:
  136. transaction.rollback()
  137. else:
  138. transaction.commit()
  139. @transaction.commit_manually(using="my_other_database")
  140. def viewfunc2(request):
  141. ....
  142. .. _topics-db-transactions-requirements:
  143. Requirements for transaction handling
  144. =====================================
  145. Django requires that every transaction that is opened is closed before the
  146. completion of a request.
  147. If you are using :func:`autocommit` (the default commit mode) or
  148. :func:`commit_on_success`, this will be done for you automatically. However,
  149. if you are manually managing transactions (using the :func:`commit_manually`
  150. decorator), you must ensure that the transaction is either committed or rolled
  151. back before a request is completed.
  152. This applies to all database operations, not just write operations. Even
  153. if your transaction only reads from the database, the transaction must
  154. be committed or rolled back before you complete a request.
  155. .. _managing-autocommit:
  156. Managing autocommit
  157. ===================
  158. .. versionadded:: 1.6
  159. Django provides a straightforward API to manage the autocommit state of each
  160. database connection, if you need to.
  161. .. function:: get_autocommit(using=None)
  162. .. function:: set_autocommit(using=None, autocommit=True)
  163. These functions take a ``using`` argument which should be the name of a
  164. database. If it isn't provided, Django uses the ``"default"`` database.
  165. .. _deactivate-transaction-management:
  166. How to globally deactivate transaction management
  167. =================================================
  168. Control freaks can totally disable all transaction management by setting
  169. :setting:`TRANSACTIONS_MANAGED` to ``True`` in the Django settings file. If
  170. you do this, Django won't enable autocommit. You'll get the regular behavior
  171. of the underlying database library.
  172. This requires you to commit explicitly every transaction, even those started
  173. by Django or by third-party libraries. Thus, this is best used in situations
  174. where you want to run your own transaction-controlling middleware or do
  175. something really strange.
  176. In almost all situations, you'll be better off using the default behavior, or
  177. the transaction middleware, and only modify selected functions as needed.
  178. .. _topics-db-transactions-savepoints:
  179. Savepoints
  180. ==========
  181. A savepoint is a marker within a transaction that enables you to roll back
  182. part of a transaction, rather than the full transaction. Savepoints are
  183. available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using
  184. the InnoDB storage engine) backends. Other backends provide the savepoint
  185. functions, but they're empty operations -- they don't actually do anything.
  186. Savepoints aren't especially useful if you are using the default
  187. ``autocommit`` behavior of Django. However, if you are using
  188. ``commit_on_success`` or ``commit_manually``, each open transaction will build
  189. up a series of database operations, awaiting a commit or rollback. If you
  190. issue a rollback, the entire transaction is rolled back. Savepoints provide
  191. the ability to perform a fine-grained rollback, rather than the full rollback
  192. that would be performed by ``transaction.rollback()``.
  193. Each of these functions takes a ``using`` argument which should be the name of
  194. a database for which the behavior applies. If no ``using`` argument is
  195. provided then the ``"default"`` database is used.
  196. Savepoints are controlled by three methods on the transaction object:
  197. .. method:: transaction.savepoint(using=None)
  198. Creates a new savepoint. This marks a point in the transaction that
  199. is known to be in a "good" state.
  200. Returns the savepoint ID (sid).
  201. .. method:: transaction.savepoint_commit(sid, using=None)
  202. Updates the savepoint to include any operations that have been performed
  203. since the savepoint was created, or since the last commit.
  204. .. method:: transaction.savepoint_rollback(sid, using=None)
  205. Rolls the transaction back to the last point at which the savepoint was
  206. committed.
  207. The following example demonstrates the use of savepoints::
  208. from django.db import transaction
  209. @transaction.commit_manually
  210. def viewfunc(request):
  211. a.save()
  212. # open transaction now contains a.save()
  213. sid = transaction.savepoint()
  214. b.save()
  215. # open transaction now contains a.save() and b.save()
  216. if want_to_keep_b:
  217. transaction.savepoint_commit(sid)
  218. # open transaction still contains a.save() and b.save()
  219. else:
  220. transaction.savepoint_rollback(sid)
  221. # open transaction now contains only a.save()
  222. transaction.commit()
  223. Database-specific notes
  224. =======================
  225. Savepoints in SQLite
  226. --------------------
  227. While SQLite ≥ 3.6.8 supports savepoints, a flaw in the design of the
  228. :mod:`sqlite3` makes them hardly usable.
  229. When autocommit is enabled, savepoints don't make sense. When it's disabled,
  230. :mod:`sqlite3` commits implicitly before savepoint-related statement. (It
  231. commits before any statement other than ``SELECT``, ``INSERT``, ``UPDATE``,
  232. ``DELETE`` and ``REPLACE``.)
  233. As a consequence, savepoints are only usable if you start a transaction
  234. manually while in autocommit mode, and Django doesn't provide an API to
  235. achieve that.
  236. Transactions in MySQL
  237. ---------------------
  238. If you're using MySQL, your tables may or may not support transactions; it
  239. depends on your MySQL version and the table types you're using. (By
  240. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  241. peculiarities are outside the scope of this article, but the MySQL site has
  242. `information on MySQL transactions`_.
  243. If your MySQL setup does *not* support transactions, then Django will function
  244. in autocommit mode: Statements will be executed and committed as soon as
  245. they're called. If your MySQL setup *does* support transactions, Django will
  246. handle transactions as explained in this document.
  247. .. _information on MySQL transactions: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html
  248. Handling exceptions within PostgreSQL transactions
  249. --------------------------------------------------
  250. When a call to a PostgreSQL cursor raises an exception (typically
  251. ``IntegrityError``), all subsequent SQL in the same transaction will fail with
  252. the error "current transaction is aborted, queries ignored until end of
  253. transaction block". Whilst simple use of ``save()`` is unlikely to raise an
  254. exception in PostgreSQL, there are more advanced usage patterns which
  255. might, such as saving objects with unique fields, saving using the
  256. force_insert/force_update flag, or invoking custom SQL.
  257. There are several ways to recover from this sort of error.
  258. Transaction rollback
  259. ~~~~~~~~~~~~~~~~~~~~
  260. The first option is to roll back the entire transaction. For example::
  261. a.save() # Succeeds, but may be undone by transaction rollback
  262. try:
  263. b.save() # Could throw exception
  264. except IntegrityError:
  265. transaction.rollback()
  266. c.save() # Succeeds, but a.save() may have been undone
  267. Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  268. uncommitted database operations will be lost. In this example, the changes
  269. made by ``a.save()`` would be lost, even though that operation raised no error
  270. itself.
  271. Savepoint rollback
  272. ~~~~~~~~~~~~~~~~~~
  273. You can use :ref:`savepoints <topics-db-transactions-savepoints>` to control
  274. the extent of a rollback. Before performing a database operation that could
  275. fail, you can set or update the savepoint; that way, if the operation fails,
  276. you can roll back the single offending operation, rather than the entire
  277. transaction. For example::
  278. a.save() # Succeeds, and never undone by savepoint rollback
  279. try:
  280. sid = transaction.savepoint()
  281. b.save() # Could throw exception
  282. transaction.savepoint_commit(sid)
  283. except IntegrityError:
  284. transaction.savepoint_rollback(sid)
  285. c.save() # Succeeds, and a.save() is never undone
  286. In this example, ``a.save()`` will not be undone in the case where
  287. ``b.save()`` raises an exception.
  288. Under the hood
  289. ==============
  290. .. _autocommit-details:
  291. Details on autocommit
  292. ---------------------
  293. In the SQL standards, each SQL query starts a transaction, unless one is
  294. already in progress. Such transactions must then be committed or rolled back.
  295. This isn't always convenient for application developers. To alleviate this
  296. problem, most databases provide an autocommit mode. When autocommit is turned
  297. on, each SQL query is wrapped in its own transaction. In other words, the
  298. transaction is not only automatically started, but also automatically
  299. committed.
  300. :pep:`249`, the Python Database API Specification v2.0, requires autocommit to
  301. be initially turned off. Django overrides this default and turns autocommit
  302. on.
  303. To avoid this, you can :ref:`deactivate the transaction management
  304. <deactivate-transaction-management>`, but it isn't recommended.
  305. .. versionchanged:: 1.6
  306. Before Django 1.6, autocommit was turned off, and it was emulated by
  307. forcing a commit after write operations in the ORM.
  308. .. warning::
  309. If you're using the database API directly — for instance, you're running
  310. SQL queries with ``cursor.execute()`` — be aware that autocommit is on,
  311. and consider wrapping your operations in a transaction to ensure
  312. consistency.
  313. .. _transaction-states:
  314. Transaction management states
  315. -----------------------------
  316. At any time, each database connection is in one of these two states:
  317. - **auto mode**: autocommit is enabled;
  318. - **managed mode**: autocommit is disabled.
  319. Django starts in auto mode. ``TransactionMiddleware``,
  320. :func:`commit_on_success` and :func:`commit_manually` activate managed mode;
  321. :func:`autocommit` activates auto mode.
  322. Internally, Django keeps a stack of states. Activations and deactivations must
  323. be balanced.
  324. For example, at the beginning of each HTTP request, ``TransactionMiddleware``
  325. switches to managed mode; at the end of the request, it commits or rollbacks,
  326. and switches back to auto mode.
  327. .. admonition:: Nesting decorators / context managers
  328. :func:`commit_on_success` has two effects: it changes the transaction
  329. state, and defines an atomic transaction block.
  330. Nesting with :func:`autocommit` and :func:`commit_manually` will give the
  331. expected results in terms of transaction state, but not in terms of
  332. transaction semantics. Most often, the inner block will commit, breaking
  333. the atomicity of the outer block.
  334. Django currently doesn't provide any APIs to create transactions in auto mode.
  335. .. _transactions-changes-from-1.5:
  336. Changes from Django 1.5 and earlier
  337. ===================================
  338. Since version 1.6, Django uses database-level autocommit in auto mode.
  339. Previously, it implemented application-level autocommit by triggering a commit
  340. after each ORM write.
  341. As a consequence, each database query (for instance, an
  342. ORM read) started a transaction that lasted until the next ORM write. Such
  343. "automatic transactions" no longer exist in Django 1.6.
  344. There are four known scenarios where this is backwards-incompatible.
  345. Note that managed mode isn't affected at all. This section assumes auto mode.
  346. See the :ref:`description of modes <transaction-states>` above.
  347. Sequences of custom SQL queries
  348. -------------------------------
  349. If you're executing several :ref:`custom SQL queries <executing-custom-sql>`
  350. in a row, each one now runs in its own transaction, instead of sharing the
  351. same "automatic transaction". If you need to enforce atomicity, you must wrap
  352. the sequence of queries in :func:`commit_on_success`.
  353. To check for this problem, look for calls to ``cursor.execute()``. They're
  354. usually followed by a call to ``transaction.commit_unless_managed``, which
  355. isn't necessary any more and should be removed.
  356. Select for update
  357. -----------------
  358. If you were relying on "automatic transactions" to provide locking between
  359. :meth:`~django.db.models.query.QuerySet.select_for_update` and a subsequent
  360. write operation — an extremely fragile design, but nonetheless possible — you
  361. must wrap the relevant code in :func:`commit_on_success`.
  362. Using a high isolation level
  363. ----------------------------
  364. If you were using the "repeatable read" isolation level or higher, and if you
  365. relied on "automatic transactions" to guarantee consistency between successive
  366. reads, the new behavior is backwards-incompatible. To maintain consistency,
  367. you must wrap such sequences in :func:`commit_on_success`.
  368. MySQL defaults to "repeatable read" and SQLite to "serializable"; they may be
  369. affected by this problem.
  370. At the "read committed" isolation level or lower, "automatic transactions"
  371. have no effect on the semantics of any sequence of ORM operations.
  372. PostgreSQL and Oracle default to "read committed" and aren't affected, unless
  373. you changed the isolation level.
  374. Using unsupported database features
  375. -----------------------------------
  376. With triggers, views, or functions, it's possible to make ORM reads result in
  377. database modifications. Django 1.5 and earlier doesn't deal with this case and
  378. it's theoretically possible to observe a different behavior after upgrading to
  379. Django 1.6 or later. In doubt, use :func:`commit_on_success` to enforce
  380. integrity.