diff --git a/doc/ref/transaction.rst b/doc/ref/transaction.rst index 6ce67eeb71..7657de5ba5 100644 --- a/doc/ref/transaction.rst +++ b/doc/ref/transaction.rst @@ -51,6 +51,13 @@ commited. transaction will be committed when exiting the `with` statement without exception. The other cases will be rollbacked. +.. method:: Transaction.stop([commit]) + + Stop the transaction. If commit is True, the transaction will be committed + otherwise it will be rollbacked. + The `context manager`_ returned by :meth:`Transaction.start` should be used + instead of calling this method. + .. method:: Transaction.set_context(context, \**kwargs) Update the transaction context and return a `context manager`_. The context diff --git a/trytond/transaction.py b/trytond/transaction.py index 090c9aabc0..349b0b2d13 100644 --- a/trytond/transaction.py +++ b/trytond/transaction.py @@ -87,11 +87,11 @@ class Transaction(object): else: database = Database(database_name).connect() Flavor.set(Database.flavor) + self.connection = database.get_connection(readonly=readonly, + autocommit=autocommit) self.user = user self.database = database self.readonly = readonly - self.connection = database.get_connection(readonly=readonly, - autocommit=autocommit) self.close = close self.context = context or {} self.create_records = {} @@ -103,19 +103,26 @@ class Transaction(object): self._nocache = _nocache if not _nocache: from trytond.cache import Cache - Cache.clean(database.name) + try: + Cache.clean(database.name) + except BaseException: + self.stop(False) + raise return self def __enter__(self): return self def __exit__(self, type, value, traceback): + self.stop(type is None) + + def stop(self, commit=False): transactions = self._local.transactions try: if transactions.count(self) == 1: try: try: - if type is None and not self.readonly: + if commit and not self.readonly: self.commit() else: self.rollback()