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