views:

162

answers:

2

I have seen a number of different cftransaction examples and read different sites and still have not been able to find a definitive answer to what parts of cftransaction are necessary. What I am trying to accomplish is very simple:

  • start a transaction
  • run multiple inserts/updates
  • close the transaction

If there is an error at any time during the inserts/updates, I want to rollback the transaction. Here is what I have done in the past:

<cftransaction>
 <cftry>
  <!--- multiple insert/update queries --->
 <cfcatch type="any">
  <cftransaction action="rollback">
  <!--- log error, show user message --->
 </cfcatch>
 </cftry>
<cftransaction action="commit">
</cftransaction>

Is this correct? What is the best practice? Not all of the instances of cftransaction are following the example above. Some only have the beginning and ending tags.

I have been seeing some issue with my database server and think that improper use of transactions could be one of the issues. I'm seeing a large number of: set transaction isolation level read committed processes in the activity monitor that are taking up a large amount of CPU.

A: 

Two notes:

I think you want to place the cftry block around the cftransaction. Otherwise, it will roll back the transaction, then try to commit it.

Second, I believe that if queries do not return errors, closing the transaction implies that you wish to commit. The commit line is not wrong, just redundant. If you want the automatic checking to kick in, omit it.

Ben Doom
+1  A: 

As you're doing it, the "commit" and "rollback" lines are redundant. They're really only useful if you want some of the queries committed and others rolled back. Since you're doing all or none you really don't need them.

I generally do this:

<cftry>
  <cftransaction>
    <!--- multiple insert/update queries --->
  </cftransaction>
  <cfcatch type="database">
    <!--- log error, show user message --->
  </cfcatch>
</cftry>
Al Everett
won't this cause a problem if there is an error? You never make it to the </cftransaction>
Jason
Nope, because that's the default behavior. If any of the queries in the CFTRANSACTION block fail, they all get rolled back.
Al Everett
I agree the commit and rollback are redundant (when only a single transaction is used). However, some people prefer to use them for increased clarity. When relying on the implicit commit/rollback behavior, it is not immediately obvious what the code is doing.
Leigh
True. I have seldom done database transactions that required that level of granularity. It's an important consideration, though.
Al Everett