transactions.txt 28 KB

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