transactions.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. =====================
  2. Database transactions
  3. =====================
  4. .. module:: django.db.transaction
  5. Django gives you a few ways to control how database transactions are managed.
  6. Managing database transactions
  7. ==============================
  8. Django's default transaction behavior
  9. -------------------------------------
  10. Django's default behavior is to run in autocommit mode. Each query is
  11. immediately committed to the database. :ref:`See below for details
  12. <autocommit-details>`.
  13. ..
  14. Django uses transactions or savepoints automatically to guarantee the
  15. integrity of ORM operations that require multiple queries, especially
  16. :ref:`delete() <topics-db-queries-delete>` and :ref:`update()
  17. <topics-db-queries-update>` queries.
  18. .. versionchanged:: 1.6
  19. Previous version of Django featured :ref:`a more complicated default
  20. behavior <transactions-upgrading-from-1.5>`.
  21. .. _tying-transactions-to-http-requests:
  22. Tying transactions to HTTP requests
  23. -----------------------------------
  24. A common way to handle transactions on the web is to wrap each request in a
  25. transaction. Set :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>` to
  26. ``True`` in the configuration of each database for which you want to enable
  27. this behavior.
  28. It works like this. When a request starts, Django starts a transaction. If the
  29. response is produced without problems, Django commits the transaction. If the
  30. view function produces an exception, Django rolls back the transaction.
  31. Middleware always runs outside of this transaction.
  32. You may perfom partial commits and rollbacks in your view code, typically with
  33. the :func:`atomic` context manager. However, at the end of the view, either
  34. all the changes will be committed, or none of them.
  35. To disable this behavior for a specific view, you must set the
  36. ``transactions_per_request`` attribute of the view function itself to
  37. ``False``, like this::
  38. def my_view(request):
  39. do_stuff()
  40. my_view.transactions_per_request = False
  41. .. warning::
  42. While the simplicity of this transaction model is appealing, it also makes it
  43. inefficient when traffic increases. Opening a transaction for every view has
  44. some overhead. The impact on performance depends on the query patterns of your
  45. application and on how well your database handles locking.
  46. .. admonition:: Per-request transactions and streaming responses
  47. When a view returns a :class:`~django.http.StreamingHttpResponse`, reading
  48. the contents of the response will often execute code to generate the
  49. content. Since the view has already returned, such code runs outside of
  50. the transaction.
  51. Generally speaking, it isn't advisable to write to the database while
  52. generating a streaming response, since there's no sensible way to handle
  53. errors after starting to send the response.
  54. In practice, this feature simply wraps every view function in the :func:`atomic`
  55. decorator described below.
  56. Note that only the execution of your view in enclosed in the transactions.
  57. Middleware run outside of the transaction, and so does the rendering of
  58. template responses.
  59. .. versionchanged:: 1.6
  60. Django used to provide this feature via ``TransactionMiddleware``, which is
  61. now deprecated.
  62. Controlling transactions explicitly
  63. -----------------------------------
  64. .. versionadded:: 1.6
  65. Django provides a single API to control database transactions.
  66. .. function:: atomic(using=None)
  67. This function creates an atomic block for writes to the database.
  68. (Atomicity is the defining property of database transactions.)
  69. When the block completes successfully, the changes are committed to the
  70. database. When it raises an exception, the changes are rolled back.
  71. ``atomic`` can be nested. In this case, when an inner block completes
  72. successfully, its effects can still be rolled back if an exception is
  73. raised in the outer block at a later point.
  74. ``atomic`` takes a ``using`` argument which should be the name of a
  75. database. If this argument isn't provided, Django uses the ``"default"``
  76. database.
  77. ``atomic`` is usable both as a `decorator`_::
  78. from django.db import transaction
  79. @transaction.atomic
  80. def viewfunc(request):
  81. # This code executes inside a transaction.
  82. do_stuff()
  83. and as a `context manager`_::
  84. from django.db import transaction
  85. def viewfunc(request):
  86. # This code executes in autocommit mode (Django's default).
  87. do_stuff()
  88. with transaction.atomic():
  89. # This code executes inside a transaction.
  90. do_more_stuff()
  91. .. _decorator: http://docs.python.org/glossary.html#term-decorator
  92. .. _context manager: http://docs.python.org/glossary.html#term-context-manager
  93. Wrapping ``atomic`` in a try/except block allows for natural handling of
  94. integrity errors::
  95. from django.db import IntegrityError, transaction
  96. @transaction.atomic
  97. def viewfunc(request):
  98. do_stuff()
  99. try:
  100. with transaction.atomic():
  101. do_stuff_that_could_fail()
  102. except IntegrityError:
  103. handle_exception()
  104. do_more_stuff()
  105. In this example, even if ``do_stuff_that_could_fail()`` causes a database
  106. error by breaking an integrity constraint, you can execute queries in
  107. ``do_more_stuff()``, and the changes from ``do_stuff()`` are still there.
  108. In order to guarantee atomicity, ``atomic`` disables some APIs. Attempting
  109. to commit, roll back, or change the autocommit state of the database
  110. connection within an ``atomic`` block will raise an exception.
  111. ``atomic`` can only be used in autocommit mode. It will raise an exception
  112. if autocommit is turned off.
  113. Under the hood, Django's transaction management code:
  114. - opens a transaction when entering the outermost ``atomic`` block;
  115. - creates a savepoint when entering an inner ``atomic`` block;
  116. - releases or rolls back to the savepoint when exiting an inner block;
  117. - commits or rolls back the transaction when exiting the outermost block.
  118. .. _topics-db-transactions-savepoints:
  119. Savepoints
  120. ==========
  121. A savepoint is a marker within a transaction that enables you to roll back
  122. part of a transaction, rather than the full transaction. Savepoints are
  123. available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using
  124. the InnoDB storage engine) backends. Other backends provide the savepoint
  125. functions, but they're empty operations -- they don't actually do anything.
  126. Savepoints aren't especially useful if you are using autocommit, the default
  127. behavior of Django. However, once you open a transaction with :func:`atomic`,
  128. you build up a series of database operations awaiting a commit or rollback. If
  129. you issue a rollback, the entire transaction is rolled back. Savepoints
  130. provide the ability to perform a fine-grained rollback, rather than the full
  131. rollback that would be performed by ``transaction.rollback()``.
  132. .. versionchanged:: 1.6
  133. When the :func:`atomic` decorator is nested, it creates a savepoint to allow
  134. partial commit or rollback. You're strongly encouraged to use :func:`atomic`
  135. rather than the functions described below, but they're still part of the
  136. public API, and there's no plan to deprecate them.
  137. Each of these functions takes a ``using`` argument which should be the name of
  138. a database for which the behavior applies. If no ``using`` argument is
  139. provided then the ``"default"`` database is used.
  140. Savepoints are controlled by three functions in :mod:`django.db.transaction`:
  141. .. function:: savepoint(using=None)
  142. Creates a new savepoint. This marks a point in the transaction that
  143. is known to be in a "good" state.
  144. Returns the savepoint ID (``sid``).
  145. .. function:: savepoint_commit(sid, using=None)
  146. Releases savepoint ``sid``. The changes performed since the savepoint was
  147. created become part of the transaction.
  148. .. function:: savepoint_rollback(sid, using=None)
  149. Rolls back the transaction to savepoint ``sid``.
  150. These functions do nothing if savepoints aren't supported or if the database
  151. is in autocommit mode.
  152. In addition, there's a utility function:
  153. .. function:: clean_savepoints(using=None)
  154. Resets the counter used to generate unique savepoint IDs.
  155. The following example demonstrates the use of savepoints::
  156. from django.db import transaction
  157. # open a transaction
  158. @transaction.atomic
  159. def viewfunc(request):
  160. a.save()
  161. # transaction now contains a.save()
  162. sid = transaction.savepoint()
  163. b.save()
  164. # transaction now contains a.save() and b.save()
  165. if want_to_keep_b:
  166. transaction.savepoint_commit(sid)
  167. # open transaction still contains a.save() and b.save()
  168. else:
  169. transaction.savepoint_rollback(sid)
  170. # open transaction now contains only a.save()
  171. Autocommit
  172. ==========
  173. .. _autocommit-details:
  174. Why Django uses autocommit
  175. --------------------------
  176. In the SQL standards, each SQL query starts a transaction, unless one is
  177. already in progress. Such transactions must then be committed or rolled back.
  178. This isn't always convenient for application developers. To alleviate this
  179. problem, most databases provide an autocommit mode. When autocommit is turned
  180. on, each SQL query is wrapped in its own transaction. In other words, the
  181. transaction is not only automatically started, but also automatically
  182. committed.
  183. :pep:`249`, the Python Database API Specification v2.0, requires autocommit to
  184. be initially turned off. Django overrides this default and turns autocommit
  185. on.
  186. To avoid this, you can :ref:`deactivate the transaction management
  187. <deactivate-transaction-management>`, but it isn't recommended.
  188. .. versionchanged:: 1.6
  189. Before Django 1.6, autocommit was turned off, and it was emulated by
  190. forcing a commit after write operations in the ORM.
  191. .. warning::
  192. If you're using the database API directly — for instance, you're running
  193. SQL queries with ``cursor.execute()`` — be aware that autocommit is on,
  194. and consider wrapping your operations in a transaction, with
  195. :func:`atomic`, to ensure consistency.
  196. .. _managing-autocommit:
  197. Managing autocommit
  198. -------------------
  199. .. versionadded:: 1.6
  200. Django provides a straightforward API to manage the autocommit state of each
  201. database connection, if you need to.
  202. .. function:: get_autocommit(using=None)
  203. .. function:: set_autocommit(using=None, autocommit=True)
  204. These functions take a ``using`` argument which should be the name of a
  205. database. If it isn't provided, Django uses the ``"default"`` database.
  206. Autocommit is initially turned on. If you turn it off, it's your
  207. responsibility to restore it.
  208. :func:`atomic` requires autocommit to be turned on; it will raise an exception
  209. if autocommit is off. Django will also refuse to turn autocommit off when an
  210. :func:`atomic` block is active, because that would break atomicity.
  211. .. _deactivate-transaction-management:
  212. Deactivating transaction management
  213. -----------------------------------
  214. You can totally disable Django's transaction management for a given database
  215. by setting :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` to ``False`` in its
  216. configuration. If you do this, Django won't enable autocommit, and won't
  217. perform any commits. You'll get the regular behavior of the underlying
  218. database library.
  219. This requires you to commit explicitly every transaction, even those started
  220. by Django or by third-party libraries. Thus, this is best used in situations
  221. where you want to run your own transaction-controlling middleware or do
  222. something really strange.
  223. .. versionchanged:: 1.6
  224. This used to be controlled by the ``TRANSACTIONS_MANAGED`` setting.
  225. Database-specific notes
  226. =======================
  227. Savepoints in SQLite
  228. --------------------
  229. While SQLite ≥ 3.6.8 supports savepoints, a flaw in the design of the
  230. :mod:`sqlite3` makes them hardly usable.
  231. When autocommit is enabled, savepoints don't make sense. When it's disabled,
  232. :mod:`sqlite3` commits implicitly before savepoint-related statement. (It
  233. commits before any statement other than ``SELECT``, ``INSERT``, ``UPDATE``,
  234. ``DELETE`` and ``REPLACE``.)
  235. As a consequence, savepoints are only usable inside a transaction ie. inside
  236. an :func:`atomic` block.
  237. Transactions in MySQL
  238. ---------------------
  239. If you're using MySQL, your tables may or may not support transactions; it
  240. depends on your MySQL version and the table types you're using. (By
  241. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  242. peculiarities are outside the scope of this article, but the MySQL site has
  243. `information on MySQL transactions`_.
  244. If your MySQL setup does *not* support transactions, then Django will function
  245. in autocommit mode: Statements will be executed and committed as soon as
  246. they're called. If your MySQL setup *does* support transactions, Django will
  247. handle transactions as explained in this document.
  248. .. _information on MySQL transactions: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html
  249. Handling exceptions within PostgreSQL transactions
  250. --------------------------------------------------
  251. When a call to a PostgreSQL cursor raises an exception (typically
  252. ``IntegrityError``), all subsequent SQL in the same transaction will fail with
  253. the error "current transaction is aborted, queries ignored until end of
  254. transaction block". Whilst simple use of ``save()`` is unlikely to raise an
  255. exception in PostgreSQL, there are more advanced usage patterns which
  256. might, such as saving objects with unique fields, saving using the
  257. force_insert/force_update flag, or invoking custom SQL.
  258. There are several ways to recover from this sort of error.
  259. Transaction rollback
  260. ~~~~~~~~~~~~~~~~~~~~
  261. The first option is to roll back the entire transaction. For example::
  262. a.save() # Succeeds, but may be undone by transaction rollback
  263. try:
  264. b.save() # Could throw exception
  265. except IntegrityError:
  266. transaction.rollback()
  267. c.save() # Succeeds, but a.save() may have been undone
  268. Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  269. uncommitted database operations will be lost. In this example, the changes
  270. made by ``a.save()`` would be lost, even though that operation raised no error
  271. itself.
  272. Savepoint rollback
  273. ~~~~~~~~~~~~~~~~~~
  274. You can use :ref:`savepoints <topics-db-transactions-savepoints>` to control
  275. the extent of a rollback. Before performing a database operation that could
  276. fail, you can set or update the savepoint; that way, if the operation fails,
  277. you can roll back the single offending operation, rather than the entire
  278. transaction. For example::
  279. a.save() # Succeeds, and never undone by savepoint rollback
  280. try:
  281. sid = transaction.savepoint()
  282. b.save() # Could throw exception
  283. transaction.savepoint_commit(sid)
  284. except IntegrityError:
  285. transaction.savepoint_rollback(sid)
  286. c.save() # Succeeds, and a.save() is never undone
  287. In this example, ``a.save()`` will not be undone in the case where
  288. ``b.save()`` raises an exception.
  289. .. _transactions-upgrading-from-1.5:
  290. Changes from Django 1.5 and earlier
  291. ===================================
  292. The features described below were deprecated in Django 1.6 and will be removed
  293. in Django 1.8. They're documented in order to ease the migration to the new
  294. transaction management APIs.
  295. Legacy APIs
  296. -----------
  297. The following functions, defined in ``django.db.transaction``, provided a way
  298. to control transactions on a per-function or per-code-block basis. They could
  299. be used as decorators or as context managers, and they accepted a ``using``
  300. argument, exactly like :func:`atomic`.
  301. .. function:: autocommit
  302. Enable Django's default autocommit behavior.
  303. Transactions will be committed as soon as you call ``model.save()``,
  304. ``model.delete()``, or any other function that writes to the database.
  305. .. function:: commit_on_success
  306. Use a single transaction for all the work done in a function.
  307. If the function returns successfully, then Django will commit all work done
  308. within the function at that point. If the function raises an exception,
  309. though, Django will roll back the transaction.
  310. .. function:: commit_manually
  311. Tells Django you'll be managing the transaction on your own.
  312. Whether you are writing or simply reading from the database, you must
  313. ``commit()`` or ``rollback()`` explicitly or Django will raise a
  314. :exc:`TransactionManagementError` exception. This is required when reading
  315. from the database because ``SELECT`` statements may call functions which
  316. modify tables, and thus it is impossible to know if any data has been
  317. modified.
  318. .. _transaction-states:
  319. Transaction states
  320. ------------------
  321. The three functions described above relied on a concept called "transaction
  322. states". This mechanisme was deprecated in Django 1.6, but it's still
  323. available until Django 1.8..
  324. At any time, each database connection is in one of these two states:
  325. - **auto mode**: autocommit is enabled;
  326. - **managed mode**: autocommit is disabled.
  327. Django starts in auto mode. ``TransactionMiddleware``,
  328. :func:`commit_on_success` and :func:`commit_manually` activate managed mode;
  329. :func:`autocommit` activates auto mode.
  330. Internally, Django keeps a stack of states. Activations and deactivations must
  331. be balanced.
  332. For example, ``commit_on_success`` switches to managed mode when entering the
  333. block of code it controls; when exiting the block, it commits or rollbacks,
  334. and switches back to auto mode.
  335. So :func:`commit_on_success` really has two effects: it changes the
  336. transaction state and it defines an transaction block. Nesting will give the
  337. expected results in terms of transaction state, but not in terms of
  338. transaction semantics. Most often, the inner block will commit, breaking the
  339. atomicity of the outer block.
  340. :func:`autocommit` and :func:`commit_manually` have similar limitations.
  341. API changes
  342. -----------
  343. Transaction middleware
  344. ~~~~~~~~~~~~~~~~~~~~~~
  345. In Django 1.6, ``TransactionMiddleware`` is deprecated and replaced
  346. :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>`. While the general
  347. behavior is the same, there are a few differences.
  348. With the transaction middleware, it was still possible to switch to autocommit
  349. or to commit explicitly in a view. Since :func:`atomic` guarantees atomicity,
  350. this isn't allowed any longer.
  351. To avoid wrapping a particular view in a transaction, instead of::
  352. @transaction.autocommit
  353. def my_view(request):
  354. do_stuff()
  355. you must now use this pattern::
  356. def my_view(request):
  357. do_stuff()
  358. my_view.transactions_per_request = False
  359. The transaction middleware applied not only to view functions, but also to
  360. middleware modules that come after it. For instance, if you used the session
  361. middleware after the transaction middleware, session creation was part of the
  362. transaction. :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>` only
  363. applies to the view itself.
  364. Managing transactions
  365. ~~~~~~~~~~~~~~~~~~~~~
  366. Starting with Django 1.6, :func:`atomic` is the only supported API for
  367. defining a transaction. Unlike the deprecated APIs, it's nestable and always
  368. guarantees atomicity.
  369. In most cases, it will be a drop-in replacement for :func:`commit_on_success`.
  370. During the deprecation period, it's possible to use :func:`atomic` within
  371. :func:`autocommit`, :func:`commit_on_success` or :func:`commit_manually`.
  372. However, the reverse is forbidden, because nesting the old decorators /
  373. context managers breaks atomicity.
  374. If you enter :func:`atomic` while you're in managed mode, it will trigger a
  375. commit to start from a clean slate.
  376. Managing autocommit
  377. ~~~~~~~~~~~~~~~~~~~
  378. Django 1.6 introduces an explicit :ref:`API for mananging autocommit
  379. <managing-autocommit>`.
  380. To disable autocommit temporarily, instead of::
  381. with transaction.commit_manually():
  382. # do stuff
  383. you should now use::
  384. transaction.set_autocommit(autocommit=False)
  385. try:
  386. # do stuff
  387. finally:
  388. transaction.set_autocommit(autocommit=True)
  389. To enable autocommit temporarily, instead of::
  390. with transaction.autocommit():
  391. # do stuff
  392. you should now use::
  393. transaction.set_autocommit(autocommit=True)
  394. try:
  395. # do stuff
  396. finally:
  397. transaction.set_autocommit(autocommit=False)
  398. Disabling transaction management
  399. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  400. Instead of setting ``TRANSACTIONS_MANAGED = True``, set the ``AUTOCOMMIT`` key
  401. to ``False`` in the configuration of each database, as explained in :ref
  402. :`deactivate-transaction-management`.
  403. Backwards incompatibilities
  404. ---------------------------
  405. Since version 1.6, Django uses database-level autocommit in auto mode.
  406. Previously, it implemented application-level autocommit by triggering a commit
  407. after each ORM write.
  408. As a consequence, each database query (for instance, an ORM read) started a
  409. transaction that lasted until the next ORM write. Such "automatic
  410. transactions" no longer exist in Django 1.6.
  411. There are four known scenarios where this is backwards-incompatible.
  412. Note that managed mode isn't affected at all. This section assumes auto mode.
  413. See the :ref:`description of modes <transaction-states>` above.
  414. Sequences of custom SQL queries
  415. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  416. If you're executing several :ref:`custom SQL queries <executing-custom-sql>`
  417. in a row, each one now runs in its own transaction, instead of sharing the
  418. same "automatic transaction". If you need to enforce atomicity, you must wrap
  419. the sequence of queries in :func:`commit_on_success`.
  420. To check for this problem, look for calls to ``cursor.execute()``. They're
  421. usually followed by a call to ``transaction.commit_unless_managed``, which
  422. isn't necessary any more and should be removed.
  423. Select for update
  424. ~~~~~~~~~~~~~~~~~
  425. If you were relying on "automatic transactions" to provide locking between
  426. :meth:`~django.db.models.query.QuerySet.select_for_update` and a subsequent
  427. write operation — an extremely fragile design, but nonetheless possible — you
  428. must wrap the relevant code in :func:`atomic`.
  429. Using a high isolation level
  430. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  431. If you were using the "repeatable read" isolation level or higher, and if you
  432. relied on "automatic transactions" to guarantee consistency between successive
  433. reads, the new behavior might be backwards-incompatible. To enforce
  434. consistency, you must wrap such sequences in :func:`atomic`.
  435. MySQL defaults to "repeatable read" and SQLite to "serializable"; they may be
  436. affected by this problem.
  437. At the "read committed" isolation level or lower, "automatic transactions"
  438. have no effect on the semantics of any sequence of ORM operations.
  439. PostgreSQL and Oracle default to "read committed" and aren't affected, unless
  440. you changed the isolation level.
  441. Using unsupported database features
  442. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  443. With triggers, views, or functions, it's possible to make ORM reads result in
  444. database modifications. Django 1.5 and earlier doesn't deal with this case and
  445. it's theoretically possible to observe a different behavior after upgrading to
  446. Django 1.6 or later. In doubt, use :func:`atomic` to enforce integrity.