[Zope-DB] rollback / commit inside DTML : How To ??

Matthew T. Kromer matt@zope.com
Mon, 07 Oct 2002 13:41:06 -0400


Federico Di Gregorio wrote:

>Il lun, 2002-10-07 alle 18:43, Harald Koschinski ha scritto:
>  
>
>>Hi,
>>
>>does anybody know, howto commit / rollback a DB-transaction inside a DTML-Script by hand.
>>
>>Something like
>><dtml-commit>  :-))
>>
>>I know the python functions (get_transaction().commit() ...) but how can I call
>>    
>>
>
>*don't* *call* *them*. (zope does it for you and you will only mess with
>the transaction system..)
>
>  
>

Agreed -- dont try to abort or commit the transaction *during* the 
transaction.  You'll get in a world of hurt if you try.

Instead, what you might want to consider doing is registering a callback 
object with the transaction manager.

Take a look at the Shared.DC.ZRDB.TM's TM class.  It implements a 
transaction manager (which has a naming 'misfeature' or two IMHO).   
 What you might want to do is something like:

class MyMonitor(TM):

    def __init__(self, datum):
        """ initialize with some data, useful for remembering """
        self._register()
   
    def tpc_vote(self, context):
        """ Called *before* commit """
        self._finalize = 1    # Have to borrow this from the underlying 
TM code

    def _finish(self):
        """ Called when we're to commit """
        # commit ourselves to DB or whatever
        pass

    def _abort(self):
        """ Called when we're to abort """
        # abort ourself to DB or whatever
        pass

You can instantiate a monitor then to hang around through the course of 
the transaction and do something if the transaction is commited/aborted, 
or use the vote hook to get an opportunity to call an abort (by raising 
an exception) if some condition isnt to your liking.

However, trying to call a commit early is a mistake.  Consider the 
following scenario:

BEGIN TRANSACTION
DEBIT your_account some_amount
COMMIT
CREDIT your_other_account some_amount
**** ERROR: your_other_account does not exist!

Uh, if the credit blows up, your money poofed.  You dont want that.  One 
element of a transaction doesn't have any knowledge of what else may 
happen subseqently in the transaction, so you *really* dont want to try 
to commit early.

-- 
Matt Kromer
Zope Corporation  http://www.zope.com/