loading... Salesforce Cat

Sunday, October 19, 2014

Salesforce Transaction Control

A transaction is a unit of work that you want to treat as "a whole". It has to either happen in full, or not at all.When it comes to maintain consistency and integrity of data ,Transaction Control is of paramount importance. Transaction control ensures the data changes done in failed operations do not modify the state of your database while changes done by successfully completed operations are reflected in the database.

Salesforce Transaction control is means of enforcing the above concept to your apex code which executes on Salesforce servers.In Salesforce you can do this with two simple methods.
  1. Savepoint sp = Database.setSavepoint(); - marks the beginning of your transaction and also the point  to database should revert in case the operation fails.
  2. Database.rollback(sp); - undo any changes you have done to the database after the passed save point. This methods takes a save point as a parameter and roll back all the database changes done after the passed save point.
example of  using above methods in code
 // variable initialization   
  // your custom validation logic   
  Savepoint sp = Database.setSavepoint(); // should be before any dml statements that you intend to be undone if the operation fails   
  try   
  {   
  // your dml statements and other logic   
  }   
  catch(Exception e )   
  {   
   //oops something bad happen before opertion completed   
  Database.rollback(sp); //undo any dml change done after setting the save point.   
  }   

you can find more about Salesforce Transaction Control Here

One important point to note is Id values of Sobject records save after save point are not cleared on rollback.Attempting to insert the sObject using the variable created before the rollback fails because the sObject variable has an ID. Updating or upserting the sObject using the same variable also fails because the sObject is not in the database and, thus, cannot be updated.So it is important you reinitialize your sobjects after rollback else it will generate DML exceptions on subsequent operations such as

  • Record ID: cannot specify Id in an insert call 
  • Record does not exist



No comments:

Post a Comment