Thursday, November 13, 2014

Have you met the Ghost Records of Salesforce?

This post is very old but it is long overdue. Have you seen the Ghost records in Salesforce? Whenever there is an auto-number field on an Object, it suddenly seems to have gaps in between? For e.g., if you have a auto-number set at 00001 and the next record it creates is 00004. These gaps are sometimes attributed to people who create records and delete.

Auto-number fields
Lets talk a bit about auto-number. Apart from the part that they are cool, they are also very stubborn. An auto-number field resets only once in its lifetime and never turns back. When an auto-number is incremented it does not go back, even if the record is deleted.

So when you delete a record that has auto-number field on it, it will not decrement it by 1 but instead create the gap.

Ghost records
The real crux of the issue lies when developers write unit classes. Developers always create dummy records for testing. The test execution runs in a separate context than the main Salesforce. These records are not seen in the system or recycle bin but their data remains. Thus auto-number is incremented.

Solution
Like always there is a solution (Since Spring 14 that is. Spring 14 is the ghost buster in this case).

Go to Setup-> Apex Test Execution-> Option



Since Spring 14, a new option Independent Auto-number Sequence is available. For some reason it is turned off by default and can be turned on to prevent this. Once it is on, test methods won't affect the auto-number sequence.

Ideally, there are very few cases when this problem can happen in Production. The only time a unit test is run in the Production is during Deployment from Sandbox. Avoid running Unit test in Production. A proper deployment plan can also prevent redeployment of same classes and this prevent running.

Seen any ghost records lately? Mention in the comments below.