Package Products :: Package ZenUtils :: Module transaction_contextmanagers |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.transaction_contextmanagers

     1  ##########################################################################
     2  #
     3  # This program is part of Zenoss Core, an open source monitoring platform.
     4  # Copyright (C) 2010, Zenoss Inc.
     5  #
     6  # This program is free software; you can redistribute it and/or modify it
     7  # under the terms of the GNU General Public License version 2 or (at your
     8  # option) any later version as published by the Free Software Foundation.
     9  #
    10  # For complete information please visit: http://www.zenoss.com/oss/
    11  #
    12  ###########################################################################
    13
    14  # context managers for transaction and state commit/rollback
    15  from contextlib import contextmanager
    16
    17  import transaction
    18
    19  # define exception type to catch cases where current transaction is explicitly
    20  # committed or aborted with in the body of the with statement (only necessary on
    21  # abort)
    22 -class InvalidTransactionError(Exception): pass
    23
    24  @contextmanager
    25 -def zodb_transaction():
    26      try:
    27          txn = transaction.get()
    28          yield txn
    29      except:
    30          if txn is not transaction.get():
    31              raise InvalidTransactionError(
    32                  "could not abort transaction, was already aborted/committed within 'with' body")
    33          try:
    34              txn.abort()
    35          # catch any internal exceptions that happen during abort
    36          except Exception:
    37              pass
    38          raise
    39      else:
    40          try:
    41              if txn is transaction.get():
    42                  txn.commit()
    43          # catch any internal exceptions that happen during commit
    44          except Exception:
    45              pass
    46
    47  @contextmanager
    48 -def nested_transaction(xaDataManager=None):
    49      try:
    50          txn = transaction.get()
    51          sp = txn.savepoint()
    52          if xaDataManager is not None:
    53              txn.join(xaDataManager)
    54          yield
    55      except:
    56          try:
    57              sp.rollback()
    58              if xaDataManager is not None:
    59                  xaDataManager.abort(txn)
    60          except:
    61              pass
    62          raise
    63      else:
    64          pass
    65