root/gaphor/tags/gaphor-0.11.1/gaphor/transaction.py

Revision 1204, 1.7 kB (checked in by arj..@yirdis.nl, 2 years ago)

Added module gaphor.transaction

Line 
1 """
2 Transation support for Gaphor
3 """
4
5 from zope import interface, component
6 from gaphor.interfaces import ITransaction
7 from gaphor.event import TransactionBegin, TransactionCommit, TransactionRollback
8
9 def transactional(func):
10     def _transactional(*args, **kwargs):
11         tx = Transaction()
12         try:
13             func(*args, **kwargs)
14         except:
15             tx.rollback()
16             raise
17         else:
18             tx.commit()
19     return _transactional
20
21 class TransactionError(Exception):
22     """
23     Errors related to the transaction module.
24     """
25
26
27 class Transaction(object):
28     interface.implements(ITransaction)
29
30     _stack= []
31
32     def __init__(self):
33         self._need_rollback = False
34         if not self._stack:
35             component.handle(TransactionBegin())
36         self._stack.append(self)
37
38     def commit(self):
39         self._close()
40 #        if self._need_rollback:
41 #            log.warning('Tried to commit a transaction already marked for rollback.')
42         if not self._stack:
43             if self._need_rollback:
44                 component.handle(TransactionRollback())
45             else:
46                 component.handle(TransactionCommit())
47
48     def rollback(self):
49         self._close()
50         # Mark every tx on the stack for rollback
51         for tx in self._stack:
52             tx._need_rollback = True
53         if not self._stack:
54             component.handle(TransactionRollback())
55
56     def _close(self):
57         try:
58             last = self._stack.pop()
59         except IndexError:
60             raise TransactionError, 'No Transaction on stack.'
61         if last is not self:
62             self._stack.append(last)
63             raise TransactionError, 'Transaction on stack is not the transaction being closed.'
Note: See TracBrowser for help on using the browser.