Using the UserConnection class to create a new transaction scope


Hi All!
Here’s a trick I learned from a colleague:
With the class UserConnection, you can make sure a transaction isn’t rolled back even if the transaction it is in is rolled back.
Consider the following example:
static void KlForRecordNotInserted(Args _args)
{
    CustTable custTable;
    ;
    
    ttsbegin;
    
    custTable.clear();
    custTable.initValue();
    custTable.AccountNum = "000010";
    custTable.Name = "My Test Customer";
    custTable.insert();
    
    throw error("An error that causes a rollback");
    ttscommit;
}
The record will not be inserted, because an error is thrown that causes an implicit ttsabort (so the tranaction is rolled back), right?
Well, you can counter this behavior by using the UserConnection class:
static void KlForRecordInserted(Args _args)
{
    UserConnection userConnection;
    CustTable custTable;
    ;
    
    ttsbegin;
    
    userConnection = new userConnection();
    
    custTable.clear();
    custTable.initValue();
    custTable.AccountNum = "000020";
    custTable.Name = "My Test Customer";
    custTable.setConnection(userConnection)// set userconnection
    custTable.insert();
    
    throw error("An error that causes a rollback");
    ttscommit;
}
You will see that the CustTable record will be inserted in the example above.
This can be useful if you really want a record to be inserted, for example when doing logging (like in batch processes, or when debugging).
When you don’t use a UserConnection, your logging will be rolled back together with other transaction.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.