transactions.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. .. _tying-transactions-to-http-requests:
  20. Tying transactions to HTTP requests
  21. -----------------------------------
  22. A common way to handle transactions on the web is to wrap each request in a
  23. transaction. Set :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>` to
  24. ``True`` in the configuration of each database for which you want to enable
  25. this behavior.
  26. It works like this. Before calling a view function, Django starts a
  27. transaction. If the response is produced without problems, Django commits the
  28. transaction. If the view produces an exception, Django rolls back the
  29. transaction.
  30. You may perform subtransactions using savepoints in your view code, typically
  31. with the :func:`atomic` context manager. However, at the end of the view,
  32. either all or none of the changes will be committed.
  33. .. warning::
  34. While the simplicity of this transaction model is appealing, it also makes it
  35. inefficient when traffic increases. Opening a transaction for every view has
  36. some overhead. The impact on performance depends on the query patterns of your
  37. application and on how well your database handles locking.
  38. .. admonition:: Per-request transactions and streaming responses
  39. When a view returns a :class:`~django.http.StreamingHttpResponse`, reading
  40. the contents of the response will often execute code to generate the
  41. content. Since the view has already returned, such code runs outside of
  42. the transaction.
  43. Generally speaking, it isn't advisable to write to the database while
  44. generating a streaming response, since there's no sensible way to handle
  45. errors after starting to send the response.
  46. In practice, this feature wraps every view function in the :func:`atomic`
  47. decorator described below.
  48. Note that only the execution of your view is enclosed in the transactions.
  49. Middleware runs outside of the transaction, and so does the rendering of
  50. template responses.
  51. When :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>` is enabled, it's
  52. still possible to prevent views from running in a transaction.
  53. .. function:: non_atomic_requests(using=None)
  54. This decorator will negate the effect of :setting:`ATOMIC_REQUESTS
  55. <DATABASE-ATOMIC_REQUESTS>` for a given view::
  56. from django.db import transaction
  57. @transaction.non_atomic_requests
  58. def my_view(request):
  59. do_stuff()
  60. @transaction.non_atomic_requests(using="other")
  61. def my_other_view(request):
  62. do_stuff_on_the_other_database()
  63. It only works if it's applied to the view itself.
  64. Controlling transactions explicitly
  65. -----------------------------------
  66. Django provides a single API to control database transactions.
  67. .. function:: atomic(using=None, savepoint=True, durable=False)
  68. Atomicity is the defining property of database transactions. ``atomic``
  69. allows us to create a block of code within which the atomicity on the
  70. database is guaranteed. If the block of code is successfully completed, the
  71. changes are committed to the database. If there is an exception, the
  72. changes are rolled back.
  73. ``atomic`` blocks can be nested. In this case, when an inner block
  74. completes successfully, its effects can still be rolled back if an
  75. exception is raised in the outer block at a later point.
  76. It is sometimes useful to ensure an ``atomic`` block is always the
  77. outermost ``atomic`` block, ensuring that any database changes are
  78. committed when the block is exited without errors. This is known as
  79. durability and can be achieved by setting ``durable=True``. If the
  80. ``atomic`` block is nested within another it raises a ``RuntimeError``.
  81. ``atomic`` is usable both as a :py:term:`decorator`::
  82. from django.db import transaction
  83. @transaction.atomic
  84. def viewfunc(request):
  85. # This code executes inside a transaction.
  86. do_stuff()
  87. and as a :py:term:`context manager`::
  88. from django.db import transaction
  89. def viewfunc(request):
  90. # This code executes in autocommit mode (Django's default).
  91. do_stuff()
  92. with transaction.atomic():
  93. # This code executes inside a transaction.
  94. do_more_stuff()
  95. Wrapping ``atomic`` in a try/except block allows for natural handling of
  96. integrity errors::
  97. from django.db import IntegrityError, transaction
  98. @transaction.atomic
  99. def viewfunc(request):
  100. create_parent()
  101. try:
  102. with transaction.atomic():
  103. generate_relationships()
  104. except IntegrityError:
  105. handle_exception()
  106. add_children()
  107. In this example, even if ``generate_relationships()`` causes a database
  108. error by breaking an integrity constraint, you can execute queries in
  109. ``add_children()``, and the changes from ``create_parent()`` are still
  110. there and bound to the same transaction. Note that any operations attempted
  111. in ``generate_relationships()`` will already have been rolled back safely
  112. when ``handle_exception()`` is called, so the exception handler can also
  113. operate on the database if necessary.
  114. .. admonition:: Avoid catching exceptions inside ``atomic``!
  115. When exiting an ``atomic`` block, Django looks at whether it's exited
  116. normally or with an exception to determine whether to commit or roll
  117. back. If you catch and handle exceptions inside an ``atomic`` block,
  118. you may hide from Django the fact that a problem has happened. This
  119. can result in unexpected behavior.
  120. This is mostly a concern for :exc:`~django.db.DatabaseError` and its
  121. subclasses such as :exc:`~django.db.IntegrityError`. After such an
  122. error, the transaction is broken and Django will perform a rollback at
  123. the end of the ``atomic`` block. If you attempt to run database
  124. queries before the rollback happens, Django will raise a
  125. :class:`~django.db.transaction.TransactionManagementError`. You may
  126. also encounter this behavior when an ORM-related signal handler raises
  127. an exception.
  128. The correct way to catch database errors is around an ``atomic`` block
  129. as shown above. If necessary, add an extra ``atomic`` block for this
  130. purpose. This pattern has another advantage: it delimits explicitly
  131. which operations will be rolled back if an exception occurs.
  132. If you catch exceptions raised by raw SQL queries, Django's behavior
  133. is unspecified and database-dependent.
  134. .. admonition:: You may need to manually revert app state when rolling back a transaction.
  135. The values of a model's fields won't be reverted when a transaction
  136. rollback happens. This could lead to an inconsistent model state unless
  137. you manually restore the original field values.
  138. For example, given ``MyModel`` with an ``active`` field, this snippet
  139. ensures that the ``if obj.active`` check at the end uses the correct
  140. value if updating ``active`` to ``True`` fails in the transaction::
  141. from django.db import DatabaseError, transaction
  142. obj = MyModel(active=False)
  143. obj.active = True
  144. try:
  145. with transaction.atomic():
  146. obj.save()
  147. except DatabaseError:
  148. obj.active = False
  149. if obj.active:
  150. ...
  151. This also applies to any other mechanism that may hold app state, such
  152. as caching or global variables. For example, if the code proactively
  153. updates data in the cache after saving an object, it's recommended to
  154. use :ref:`transaction.on_commit() <performing-actions-after-commit>`
  155. instead, to defer cache alterations until the transaction is actually
  156. committed.
  157. In order to guarantee atomicity, ``atomic`` disables some APIs. Attempting
  158. to commit, roll back, or change the autocommit state of the database
  159. connection within an ``atomic`` block will raise an exception.
  160. ``atomic`` takes a ``using`` argument which should be the name of a
  161. database. If this argument isn't provided, Django uses the ``"default"``
  162. database.
  163. Under the hood, Django's transaction management code:
  164. - opens a transaction when entering the outermost ``atomic`` block;
  165. - creates a savepoint when entering an inner ``atomic`` block;
  166. - releases or rolls back to the savepoint when exiting an inner block;
  167. - commits or rolls back the transaction when exiting the outermost block.
  168. You can disable the creation of savepoints for inner blocks by setting the
  169. ``savepoint`` argument to ``False``. If an exception occurs, Django will
  170. perform the rollback when exiting the first parent block with a savepoint
  171. if there is one, and the outermost block otherwise. Atomicity is still
  172. guaranteed by the outer transaction. This option should only be used if
  173. the overhead of savepoints is noticeable. It has the drawback of breaking
  174. the error handling described above.
  175. You may use ``atomic`` when autocommit is turned off. It will only use
  176. savepoints, even for the outermost block.
  177. .. admonition:: Performance considerations
  178. Open transactions have a performance cost for your database server. To
  179. minimize this overhead, keep your transactions as short as possible. This
  180. is especially important if you're using :func:`atomic` in long-running
  181. processes, outside of Django's request / response cycle.
  182. Autocommit
  183. ==========
  184. .. _autocommit-details:
  185. Why Django uses autocommit
  186. --------------------------
  187. In the SQL standards, each SQL query starts a transaction, unless one is
  188. already active. Such transactions must then be explicitly committed or rolled
  189. back.
  190. This isn't always convenient for application developers. To alleviate this
  191. problem, most databases provide an autocommit mode. When autocommit is turned
  192. on and no transaction is active, each SQL query gets wrapped in its own
  193. transaction. In other words, not only does each such query start a
  194. transaction, but the transaction also gets automatically committed or rolled
  195. back, depending on whether the query succeeded.
  196. :pep:`249`, the Python Database API Specification v2.0, requires autocommit to
  197. be initially turned off. Django overrides this default and turns autocommit
  198. on.
  199. To avoid this, you can :ref:`deactivate the transaction management
  200. <deactivate-transaction-management>`, but it isn't recommended.
  201. .. _deactivate-transaction-management:
  202. Deactivating transaction management
  203. -----------------------------------
  204. You can totally disable Django's transaction management for a given database
  205. by setting :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` to ``False`` in its
  206. configuration. If you do this, Django won't enable autocommit, and won't
  207. perform any commits. You'll get the regular behavior of the underlying
  208. database library.
  209. This requires you to commit explicitly every transaction, even those started
  210. by Django or by third-party libraries. Thus, this is best used in situations
  211. where you want to run your own transaction-controlling middleware or do
  212. something really strange.
  213. .. _performing-actions-after-commit:
  214. Performing actions after commit
  215. ===============================
  216. Sometimes you need to perform an action related to the current database
  217. transaction, but only if the transaction successfully commits. Examples might
  218. include a background task, an email notification, or a cache invalidation.
  219. :func:`on_commit` allows you to register callbacks that will be executed after
  220. the open transaction is successfully committed:
  221. .. function:: on_commit(func, using=None, robust=False)
  222. Pass a function, or any callable, to :func:`on_commit`::
  223. from django.db import transaction
  224. def send_welcome_email(): ...
  225. transaction.on_commit(send_welcome_email)
  226. Callbacks will not be passed any arguments, but you can bind them with
  227. :func:`functools.partial`::
  228. from functools import partial
  229. for user in users:
  230. transaction.on_commit(partial(send_invite_email, user=user))
  231. Callbacks are called after the open transaction is successfully committed. If
  232. the transaction is instead rolled back (typically when an unhandled exception
  233. is raised in an :func:`atomic` block), the callback will be discarded, and
  234. never called.
  235. If you call ``on_commit()`` while there isn't an open transaction,
  236. the callback will be executed immediately.
  237. It's sometimes useful to register callbacks that can fail. Passing
  238. ``robust=True`` allows the next callbacks to be executed even if the current
  239. one throws an exception. All errors derived from Python's ``Exception`` class
  240. are caught and logged to the ``django.db.backends.base`` logger.
  241. You can use :meth:`.TestCase.captureOnCommitCallbacks` to test callbacks
  242. registered with :func:`on_commit`.
  243. Savepoints
  244. ----------
  245. Savepoints (i.e. nested :func:`atomic` blocks) are handled correctly. That is,
  246. an :func:`on_commit` callable registered after a savepoint (in a nested
  247. :func:`atomic` block) will be called after the outer transaction is committed,
  248. but not if a rollback to that savepoint or any previous savepoint occurred
  249. during the transaction::
  250. with transaction.atomic(): # Outer atomic, start a new transaction
  251. transaction.on_commit(foo)
  252. with transaction.atomic(): # Inner atomic block, create a savepoint
  253. transaction.on_commit(bar)
  254. # foo() and then bar() will be called when leaving the outermost block
  255. On the other hand, when a savepoint is rolled back (due to an exception being
  256. raised), the inner callable will not be called::
  257. with transaction.atomic(): # Outer atomic, start a new transaction
  258. transaction.on_commit(foo)
  259. try:
  260. with transaction.atomic(): # Inner atomic block, create a savepoint
  261. transaction.on_commit(bar)
  262. raise SomeError() # Raising an exception - abort the savepoint
  263. except SomeError:
  264. pass
  265. # foo() will be called, but not bar()
  266. Order of execution
  267. ------------------
  268. On-commit functions for a given transaction are executed in the order they were
  269. registered.
  270. Exception handling
  271. ------------------
  272. If one on-commit function registered with ``robust=False`` within a given
  273. transaction raises an uncaught exception, no later registered functions in that
  274. same transaction will run. This is the same behavior as if you'd executed the
  275. functions sequentially yourself without :func:`on_commit`.
  276. Timing of execution
  277. -------------------
  278. Your callbacks are executed *after* a successful commit, so a failure in a
  279. callback will not cause the transaction to roll back. They are executed
  280. conditionally upon the success of the transaction, but they are not *part* of
  281. the transaction. For the intended use cases (mail notifications, background
  282. tasks, etc.), this should be fine. If it's not (if your follow-up action is so
  283. critical that its failure should mean the failure of the transaction itself),
  284. then you don't want to use the :func:`on_commit` hook. Instead, you may want
  285. `two-phase commit`_ such as the :ref:`psycopg Two-Phase Commit protocol support
  286. <psycopg:two-phase-commit>` and the :pep:`optional Two-Phase Commit Extensions
  287. in the Python DB-API specification <249#optional-two-phase-commit-extensions>`.
  288. Callbacks are not run until autocommit is restored on the connection following
  289. the commit (because otherwise any queries done in a callback would open an
  290. implicit transaction, preventing the connection from going back into autocommit
  291. mode).
  292. When in autocommit mode and outside of an :func:`atomic` block, the function
  293. will run immediately, not on commit.
  294. On-commit functions only work with :ref:`autocommit mode <managing-autocommit>`
  295. and the :func:`atomic` (or :setting:`ATOMIC_REQUESTS
  296. <DATABASE-ATOMIC_REQUESTS>`) transaction API. Calling :func:`on_commit` when
  297. autocommit is disabled and you are not within an atomic block will result in an
  298. error.
  299. .. _two-phase commit: https://en.wikipedia.org/wiki/Two-phase_commit_protocol
  300. Use in tests
  301. ------------
  302. Django's :class:`~django.test.TestCase` class wraps each test in a transaction
  303. and rolls back that transaction after each test, in order to provide test
  304. isolation. This means that no transaction is ever actually committed, thus your
  305. :func:`on_commit` callbacks will never be run.
  306. You can overcome this limitation by using
  307. :meth:`.TestCase.captureOnCommitCallbacks`. This captures your
  308. :func:`on_commit` callbacks in a list, allowing you to make assertions on them,
  309. or emulate the transaction committing by calling them.
  310. Another way to overcome the limitation is to use
  311. :class:`~django.test.TransactionTestCase` instead of
  312. :class:`~django.test.TestCase`. This will mean your transactions are committed,
  313. and the callbacks will run. However
  314. :class:`~django.test.TransactionTestCase` flushes the database between tests,
  315. which is significantly slower than :class:`~django.test.TestCase`\'s isolation.
  316. Why no rollback hook?
  317. ---------------------
  318. A rollback hook is harder to implement robustly than a commit hook, since a
  319. variety of things can cause an implicit rollback.
  320. For instance, if your database connection is dropped because your process was
  321. killed without a chance to shut down gracefully, your rollback hook will never
  322. run.
  323. But there is a solution: instead of doing something during the atomic block
  324. (transaction) and then undoing it if the transaction fails, use
  325. :func:`on_commit` to delay doing it in the first place until after the
  326. transaction succeeds. It's a lot easier to undo something you never did in the
  327. first place!
  328. Low-level APIs
  329. ==============
  330. .. warning::
  331. Always prefer :func:`atomic` if possible at all. It accounts for the
  332. idiosyncrasies of each database and prevents invalid operations.
  333. The low level APIs are only useful if you're implementing your own
  334. transaction management.
  335. .. _managing-autocommit:
  336. Autocommit
  337. ----------
  338. Django provides an API in the :mod:`django.db.transaction` module to manage the
  339. autocommit state of each database connection.
  340. .. function:: get_autocommit(using=None)
  341. .. function:: set_autocommit(autocommit, using=None)
  342. These functions take a ``using`` argument which should be the name of a
  343. database. If it isn't provided, Django uses the ``"default"`` database.
  344. Autocommit is initially turned on. If you turn it off, it's your
  345. responsibility to restore it.
  346. Once you turn autocommit off, you get the default behavior of your database
  347. adapter, and Django won't help you. Although that behavior is specified in
  348. :pep:`249`, implementations of adapters aren't always consistent with one
  349. another. Review the documentation of the adapter you're using carefully.
  350. You must ensure that no transaction is active, usually by issuing a
  351. :func:`commit` or a :func:`rollback`, before turning autocommit back on.
  352. Django will refuse to turn autocommit off when an :func:`atomic` block is
  353. active, because that would break atomicity.
  354. Transactions
  355. ------------
  356. A transaction is an atomic set of database queries. Even if your program
  357. crashes, the database guarantees that either all the changes will be applied,
  358. or none of them.
  359. Django doesn't provide an API to start a transaction. The expected way to
  360. start a transaction is to disable autocommit with :func:`set_autocommit`.
  361. Once you're in a transaction, you can choose either to apply the changes
  362. you've performed until this point with :func:`commit`, or to cancel them with
  363. :func:`rollback`. These functions are defined in :mod:`django.db.transaction`.
  364. .. function:: commit(using=None)
  365. .. function:: rollback(using=None)
  366. These functions take a ``using`` argument which should be the name of a
  367. database. If it isn't provided, Django uses the ``"default"`` database.
  368. Django will refuse to commit or to rollback when an :func:`atomic` block is
  369. active, because that would break atomicity.
  370. .. _topics-db-transactions-savepoints:
  371. Savepoints
  372. ----------
  373. A savepoint is a marker within a transaction that enables you to roll back
  374. part of a transaction, rather than the full transaction. Savepoints are
  375. available with the SQLite, PostgreSQL, Oracle, and MySQL (when using the InnoDB
  376. storage engine) backends. Other backends provide the savepoint functions, but
  377. they're empty operations -- they don't actually do anything.
  378. Savepoints aren't especially useful if you are using autocommit, the default
  379. behavior of Django. However, once you open a transaction with :func:`atomic`,
  380. you build up a series of database operations awaiting a commit or rollback. If
  381. you issue a rollback, the entire transaction is rolled back. Savepoints
  382. provide the ability to perform a fine-grained rollback, rather than the full
  383. rollback that would be performed by ``transaction.rollback()``.
  384. When the :func:`atomic` decorator is nested, it creates a savepoint to allow
  385. partial commit or rollback. You're strongly encouraged to use :func:`atomic`
  386. rather than the functions described below, but they're still part of the
  387. public API, and there's no plan to deprecate them.
  388. Each of these functions takes a ``using`` argument which should be the name of
  389. a database for which the behavior applies. If no ``using`` argument is
  390. provided then the ``"default"`` database is used.
  391. Savepoints are controlled by three functions in :mod:`django.db.transaction`:
  392. .. function:: savepoint(using=None)
  393. Creates a new savepoint. This marks a point in the transaction that is
  394. known to be in a "good" state. Returns the savepoint ID (``sid``).
  395. .. function:: savepoint_commit(sid, using=None)
  396. Releases savepoint ``sid``. The changes performed since the savepoint was
  397. created become part of the transaction.
  398. .. function:: savepoint_rollback(sid, using=None)
  399. Rolls back the transaction to savepoint ``sid``.
  400. These functions do nothing if savepoints aren't supported or if the database
  401. is in autocommit mode.
  402. In addition, there's a utility function:
  403. .. function:: clean_savepoints(using=None)
  404. Resets the counter used to generate unique savepoint IDs.
  405. The following example demonstrates the use of savepoints::
  406. from django.db import transaction
  407. # open a transaction
  408. @transaction.atomic
  409. def viewfunc(request):
  410. a.save()
  411. # transaction now contains a.save()
  412. sid = transaction.savepoint()
  413. b.save()
  414. # transaction now contains a.save() and b.save()
  415. if want_to_keep_b:
  416. transaction.savepoint_commit(sid)
  417. # open transaction still contains a.save() and b.save()
  418. else:
  419. transaction.savepoint_rollback(sid)
  420. # open transaction now contains only a.save()
  421. Savepoints may be used to recover from a database error by performing a partial
  422. rollback. If you're doing this inside an :func:`atomic` block, the entire block
  423. will still be rolled back, because it doesn't know you've handled the situation
  424. at a lower level! To prevent this, you can control the rollback behavior with
  425. the following functions.
  426. .. function:: get_rollback(using=None)
  427. .. function:: set_rollback(rollback, using=None)
  428. Setting the rollback flag to ``True`` forces a rollback when exiting the
  429. innermost atomic block. This may be useful to trigger a rollback without
  430. raising an exception.
  431. Setting it to ``False`` prevents such a rollback. Before doing that, make sure
  432. you've rolled back the transaction to a known-good savepoint within the current
  433. atomic block! Otherwise you're breaking atomicity and data corruption may
  434. occur.
  435. Database-specific notes
  436. =======================
  437. .. _savepoints-in-sqlite:
  438. Savepoints in SQLite
  439. --------------------
  440. While SQLite supports savepoints, a flaw in the design of the :mod:`sqlite3`
  441. module makes them hardly usable.
  442. When autocommit is enabled, savepoints don't make sense. When it's disabled,
  443. :mod:`sqlite3` commits implicitly before savepoint statements. (In fact, it
  444. commits before any statement other than ``SELECT``, ``INSERT``, ``UPDATE``,
  445. ``DELETE`` and ``REPLACE``.) This bug has two consequences:
  446. - The low level APIs for savepoints are only usable inside a transaction i.e.
  447. inside an :func:`atomic` block.
  448. - It's impossible to use :func:`atomic` when autocommit is turned off.
  449. Transactions in MySQL
  450. ---------------------
  451. If you're using MySQL, your tables may or may not support transactions; it
  452. depends on your MySQL version and the table types you're using. (By
  453. "table types," we mean something like "InnoDB" or "MyISAM".) MySQL transaction
  454. peculiarities are outside the scope of this article, but the MySQL site has
  455. `information on MySQL transactions`_.
  456. If your MySQL setup does *not* support transactions, then Django will always
  457. function in autocommit mode: statements will be executed and committed as soon
  458. as they're called. If your MySQL setup *does* support transactions, Django
  459. will handle transactions as explained in this document.
  460. .. _information on MySQL transactions: https://dev.mysql.com/doc/refman/en/sql-transactional-statements.html
  461. Handling exceptions within PostgreSQL transactions
  462. --------------------------------------------------
  463. .. note::
  464. This section is relevant only if you're implementing your own transaction
  465. management. This problem cannot occur in Django's default mode and
  466. :func:`atomic` handles it automatically.
  467. Inside a transaction, when a call to a PostgreSQL cursor raises an exception
  468. (typically ``IntegrityError``), all subsequent SQL in the same transaction
  469. will fail with the error "current transaction is aborted, queries ignored
  470. until end of transaction block". While the basic use of ``save()`` is unlikely
  471. to raise an exception in PostgreSQL, there are more advanced usage patterns
  472. which might, such as saving objects with unique fields, saving using the
  473. ``force_insert``/``force_update`` flag, or invoking custom SQL.
  474. There are several ways to recover from this sort of error.
  475. Transaction rollback
  476. ~~~~~~~~~~~~~~~~~~~~
  477. The first option is to roll back the entire transaction. For example::
  478. a.save() # Succeeds, but may be undone by transaction rollback
  479. try:
  480. b.save() # Could throw exception
  481. except IntegrityError:
  482. transaction.rollback()
  483. c.save() # Succeeds, but a.save() may have been undone
  484. Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  485. uncommitted database operations will be lost. In this example, the changes
  486. made by ``a.save()`` would be lost, even though that operation raised no error
  487. itself.
  488. Savepoint rollback
  489. ~~~~~~~~~~~~~~~~~~
  490. You can use :ref:`savepoints <topics-db-transactions-savepoints>` to control
  491. the extent of a rollback. Before performing a database operation that could
  492. fail, you can set or update the savepoint; that way, if the operation fails,
  493. you can roll back the single offending operation, rather than the entire
  494. transaction. For example::
  495. a.save() # Succeeds, and never undone by savepoint rollback
  496. sid = transaction.savepoint()
  497. try:
  498. b.save() # Could throw exception
  499. transaction.savepoint_commit(sid)
  500. except IntegrityError:
  501. transaction.savepoint_rollback(sid)
  502. c.save() # Succeeds, and a.save() is never undone
  503. In this example, ``a.save()`` will not be undone in the case where
  504. ``b.save()`` raises an exception.