transactions.txt 26 KB

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