Say I want to prove to myself that when I delete a detail record, the master record is locked. How would I do that?
-
In another transaction - DML on the master or acquire lock with FOR UPDATE – identigral Oct 02 '22 at 20:01
1 Answers
I demonstrate a similar concept in this answer, but the basic idea is to write a Visualforce page that calls two simultaneous apex:actionFunction methods. For example, you could have the first method delete the detail record, then spin for 10 seconds, while the second method spins for, say, 1 second, then attempt to update the parent record. This might get you started:
public class TestRecordLock {
Account theAccount;
Contact theContact;
public void initializeData() {
theAccount = new Account(Name='Demo');
insert theAccount;
theContact = new Contact(LastName='Demo', AccountId=theAccount.Id);
insert theContact;
}
void sleep(Integer ms) {
Long startTime = DateTime.now().getTime();
while(DateTime.now().getTime()-startTime<ms);
}
public void deleteContact() {
delete theContact;
sleep(10000); // 10 seconds
}
public void updateAccount() {
sleep(1000); // Small delay, just to be safe.
update theAccount;
}
}
<apex:page controller="TestRecordLock" action="{!initializeData}">
<apex:form>
<apex:actionFunction name="deleteTheContact" action="{!deleteContact}" reRender="" />
<apex:actionFunction name="updateTheAccount" action="{!updateAccount}" reRender="" />
</apex:form>
<script>
window.addEventListener('load', () => {
deleteTheContact();
updateTheAccount();
});
</script>
</apex:page>
Because DML forces a lock to be acquired, if you have the Developer Console open, you should see two log files. The first will end in failure:
14:06:26:503 EXCEPTION_THROWN [20]|System.DmlException: Update failed. First exception on row 0 with id 0011T00002hG1FNQA0; first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or 1 records: 0011T00002hG1FNQA0: []
While the second will succeed.
Whenever you need to test something like this, you almost certainly need to set up a real test, and Visualforce is one of the best ways to do that; Lightning Components can aggregate methods together, which might be misleading.
- 489,769
- 21
- 458
- 806