Savepoints

Savepoints provide a way to save to disk intermediate work done during a transaction allowing:

Savepoints make it possible to write atomic subroutines that don't make top-level transaction commitments.

Applications

To demonstrate how savepoints work with transactions, we'll show an example.

>>> import ZODB.tests.util
>>> db = ZODB.tests.util.DB()
>>> connection = db.open()
>>> root = connection.root()
>>> root['name'] = 'bob'

As with other data managers, we can commit changes:

>>> import transaction
>>> transaction.commit()
>>> root['name']
'bob'

and abort changes:

>>> root['name'] = 'sally'
>>> root['name']
'sally'
>>> transaction.abort()
>>> root['name']
'bob'

Now, let's look at an application that manages funds for people. It allows deposits and debits to be entered for multiple people. It accepts a sequence of entries and generates a sequence of status messages. For each entry, it applies the change and then validates the user's account. If the user's account is invalid, we roll back the change for that entry. The success or failure of an entry is indicated in the output status. First we'll initialize some accounts:

>>> root['bob-balance'] = 0.0
>>> root['bob-credit'] = 0.0
>>> root['sally-balance'] = 0.0
>>> root['sally-credit'] = 100.0
>>> transaction.commit()

Now, we'll define a validation function to validate an account:

>>> def validate_account(name):
...     if root[name+'-balance'] + root[name+'-credit'] < 0:
...         raise ValueError('Overdrawn', name)

And a function to apply entries. If the function fails in some unexpected way, it rolls back all of its changes and prints the error:

>>> def apply_entries(entries):
...     savepoint = transaction.savepoint()
...     try:
...         for name, amount in entries:
...             entry_savepoint = transaction.savepoint()
...             try:
...                 root[name+'-balance'] += amount
...                 validate_account(name)
...             except ValueError, error:
...                 entry_savepoint.rollback()
...                 print 'Error', str(error)
...             else:
...                 print 'Updated', name
...     except Exception, error:
...         savepoint.rollback()
...         print 'Unexpected exception', error

Now let's try applying some entries:

>>> apply_entries([
...     ('bob',   10.0),
...     ('sally', 10.0),
...     ('bob',   20.0),
...     ('sally', 10.0),
...     ('bob',   -100.0),
...     ('sally', -100.0),
...     ])
Updated bob
Updated sally
Updated bob
Updated sally
Error ('Overdrawn', 'bob')
Updated sally
>>> root['bob-balance']
30.0
>>> root['sally-balance']
-80.0

If we provide entries that cause an unexpected error:

>>> apply_entries([
...     ('bob',   10.0),
...     ('sally', 10.0),
...     ('bob',   '20.0'),
...     ('sally', 10.0),
...     ])
Updated bob
Updated sally
Unexpected exception unsupported operand type(s) for +=: 'float' and 'str'

Because the apply_entries used a savepoint for the entire function, it was able to rollback the partial changes without rolling back changes made in the previous call to apply_entries:

>>> root['bob-balance']
30.0
>>> root['sally-balance']
-80.0

If we now abort the outer transactions, the earlier changes will go away:

>>> transaction.abort()
>>> root['bob-balance']
0.0
>>> root['sally-balance']
0.0

Savepoint invalidation

A savepoint can be used any number of times:

>>> root['bob-balance'] = 100.0
>>> root['bob-balance']
100.0
>>> savepoint = transaction.savepoint()
>>> root['bob-balance'] = 200.0
>>> root['bob-balance']
200.0
>>> savepoint.rollback()
>>> root['bob-balance']
100.0
>>> savepoint.rollback()  # redundant, but should be harmless
>>> root['bob-balance']
100.0
>>> root['bob-balance'] = 300.0
>>> root['bob-balance']
300.0
>>> savepoint.rollback()
>>> root['bob-balance']
100.0

However, using a savepoint invalidates any savepoints that come after it:

>>> root['bob-balance'] = 200.0
>>> root['bob-balance']
200.0
>>> savepoint1 = transaction.savepoint()
>>> root['bob-balance'] = 300.0
>>> root['bob-balance']
300.0
>>> savepoint2 = transaction.savepoint()
>>> savepoint.rollback()
>>> root['bob-balance']
100.0
>>> savepoint2.rollback()
Traceback (most recent call last):
...
InvalidSavepointRollbackError
>>> savepoint1.rollback()
Traceback (most recent call last):
...
InvalidSavepointRollbackError
>>> transaction.abort()