Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #9206 -- Added documentation on savepoints, and how to use them…

… to recover from errors in PostgreSQL. Thanks to Richard Davies for the draft text.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@10791 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 975ec181ead71fe80fcffe3fefbf2f7f9b8a6e0e 1 parent 56f3ed7
Russell Keith-Magee authored May 16, 2009

Showing 1 changed file with 130 additions and 19 deletions. Show diff stats Hide diff stats

  1. 149  docs/topics/db/transactions.txt
149  docs/topics/db/transactions.txt
@@ -150,6 +150,67 @@ transaction-controlling middleware or do something really strange. In almost
150 150
 all situations, you'll be better off using the default behavior, or the
151 151
 transaction middleware, and only modify selected functions as needed.
152 152
 
  153
+.. _topics-db-transactions-savepoints:
  154
+
  155
+Savepoints
  156
+==========
  157
+
  158
+A savepoint is a marker within a transaction that enables you to roll back
  159
+part of a transaction, rather than the full transaction. Savepoints are
  160
+available to the PostgreSQL 8 and Oracle backends. Other backends will
  161
+provide the savepoint functions, but they are empty operations - they won't
  162
+actually do anything.
  163
+
  164
+Savepoints aren't especially useful if you are using the default
  165
+``autocommit`` behaviour of Django. However, if you are using
  166
+``commit_on_success`` or ``commit_manually``, each open transaction will build
  167
+up a series of database operations, awaiting a commit or rollback. If you
  168
+issue a rollback, the entire transaction is rolled back. Savepoints provide
  169
+the ability to perform a fine-grained rollback, rather than the full rollback
  170
+that would be performed by ``transaction.rollback()``.
  171
+
  172
+Savepoints are controlled by three methods on the transaction object:
  173
+
  174
+.. method:: transaction.savepoint()
  175
+
  176
+    Creates a new savepoint. This marks a point in the transaction that
  177
+    is known to be in a "good" state.
  178
+
  179
+    Returns the savepoint ID (sid).
  180
+
  181
+.. method:: transaction.savepoint_commit(sid)
  182
+
  183
+    Updates the savepoint to include any operations that have been performed
  184
+    since the savepoint was created, or since the last commit.
  185
+
  186
+.. method:: transaction.savepoint_rollback(sid)
  187
+
  188
+    Rolls the transaction back to the last point at which the savepoint was
  189
+    committed.
  190
+
  191
+The following example demonstrates the use of savepoints::
  192
+
  193
+    from django.db import transaction
  194
+
  195
+    @transaction.commit_manually
  196
+    def viewfunc(request):
  197
+
  198
+      a.save()
  199
+      # open transaction now contains a.save()
  200
+      sid = transaction.savepoint()
  201
+
  202
+      b.save()
  203
+      # open transaction now contains a.save() and b.save()
  204
+
  205
+      if want_to_keep_b:
  206
+          transaction.savepoint_commit(sid)
  207
+          # open transaction still contains a.save() and b.save()
  208
+      else:
  209
+          transaction.savepoint_rollback(sid)
  210
+          # open transaction now contains only a.save()
  211
+
  212
+      transaction.commit()
  213
+
153 214
 Transactions in MySQL
154 215
 =====================
155 216
 
@@ -166,28 +227,78 @@ handle transactions as explained in this document.
166 227
 
167 228
 .. _information on MySQL transactions: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html
168 229
 
169  
-Transactions and savepoints in PostgreSQL 8
170  
-===========================================
  230
+Handling exceptions within PostgreSQL transactions
  231
+==================================================
171 232
 
172  
-When a call to a PostgreSQL 8 cursor raises an exception, all subsequent SQL
173  
-in the same transaction fails with the error "current transaction is aborted,
174  
-queries ignored until end of transaction block". Whilst simple use of save()
175  
-is unlikely to raise an exception in PostgreSQL, there are many more advanced
176  
-usage patterns which might: for example, saving objects with unique fields,
177  
-saving using the force_insert/force_update flag, or invoking custom SQL.
  233
+When a call to a PostgreSQL cursor raises an exception (typically
  234
+``IntegrityError``), all subsequent SQL in the same transaction will fail with
  235
+the error "current transaction is aborted, queries ignored until end of
  236
+transaction block". Whilst simple use of ``save()`` is unlikely to raise an
  237
+exception in PostgreSQL, there are more advanced usage patterns which
  238
+might, such as saving objects with unique fields, saving using the
  239
+force_insert/force_update flag, or invoking custom SQL.
178 240
 
179  
-In any of these cases, you can wrap the command which may throw
180  
-IntegrityError inside savepoints, which will then allow subsequent commands
181  
-to proceed. Example::
  241
+There are several ways to recover from this sort of error.
182 242
 
  243
+Transaction rollback
  244
+--------------------
  245
+
  246
+The first option is to roll back the entire transaction. For example::
  247
+
  248
+    a.save() # Succeeds, but may be undone by transaction rollback
183 249
     try:
184  
-      sid = transaction.savepoint()
185  
-      x.save()
186  
-      transaction.savepoint_commit(sid)
  250
+        b.save() # Could throw exception
187 251
     except IntegrityError:
188  
-      transaction.savepoint_rollback(sid)
189  
-      raise
  252
+        transaction.rollback()
  253
+    c.save() # Succeeds, but a.save() may have been undone
  254
+
  255
+Calling ``transaction.rollback()`` rolls back the entire transaction. Any
  256
+uncommitted database operations will be lost. In this example, the changes
  257
+made by ``a.save()`` would be lost, even though that operation raised no error
  258
+itself.
  259
+
  260
+Savepoint rollback
  261
+------------------
  262
+
  263
+If you are using PostgreSQL 8 or later, you can use :ref:`savepoints
  264
+<topics-db-transactions-savepoints>` to control the extent of a rollback.
  265
+Before performing a database operation that could fail, you can set or update
  266
+the savepoint; that way, if the operation fails, you can roll back the single
  267
+offending operation, rather than the entire transaction. For example::
  268
+
  269
+    a.save() # Succeeds, and never undone by savepoint rollback
  270
+    try:
  271
+        sid = transaction.savepoint()
  272
+        b.save() # Could throw exception
  273
+        transaction.savepoint_commit(sid)
  274
+    except IntegrityError:
  275
+        transaction.savepoint_rollback(sid)
  276
+    c.save() # Succeeds, and a.save() is never undone
  277
+
  278
+In this example, ``a.save()`` will not be undone in the case where
  279
+``b.save()`` raises an exception.
  280
+
  281
+Database-level autocommit
  282
+-------------------------
  283
+
  284
+.. versionadded:: 1.1
  285
+
  286
+With PostgreSQL 8.2 or later, there is an advanced option to run PostgreSQL
  287
+with :ref:`database-level autocommit <ref-databases>`. If you use this option,
  288
+there is no constantly open transaction, so it is always possible to continue
  289
+after catching an exception. For example::
  290
+
  291
+    a.save() # succeeds
  292
+    try:
  293
+        b.save() # Could throw exception
  294
+    except IntegrityError:
  295
+        pass
  296
+    c.save() # succeeds
  297
+
  298
+.. note::
190 299
 
191  
-Savepoints are not implemented in PostgreSQL 7. If you experience an
192  
-IntegrityError when using PostgreSQL 7, you will need to rollback to the
193  
-start of the transaction.
  300
+    This is not the same as the :ref:`autocommit decorator
  301
+    <topics-db-transactions-autocommit>`. When using database level autocommit
  302
+    there is no database transaction at all. The ``autocommit`` decorator
  303
+    still uses transactions, automatically committing each transaction when
  304
+    a database modifying operation occurs.

0 notes on commit 975ec18

Please sign in to comment.
Something went wrong with that request. Please try again.