Record Locking

Database systems may allow programs to lock records. While a record is locked only the program that has the lock may update it. If another program tries to read the record, it may hang until the record is unlocked, or perhaps the calll to read the record returns an error code.

Record locking has the advantage that once a record is locked the program can be sure it will not get a contention error when it updates it. Users of a program are not going to be happy if they spend a long time entering data only for the transaction to be rejected because of a contention problem.

On the other hand record locking has several disadvantages:

Record Locking in DP4.

In DP4 a record is locked when it is fetched with the LOCK flag. If a program succeeds in locking a record no other DP4 program can update or delete it until it is unlocked. A locked record becomes unlocked when it is explicitly unlocked by the program that locked it (by fetching it again with the UNLOCK flag), or when the program performs a db_update() operation, and specifies either the CHECKPONT flag or one of the UNLOCK flags (UNLOCK_ALWAYS or UNLOCK_IF_OK). A fetch with UNLOCK becomes effective immediately, so you will normally only use this when you are sure you will not want to update the record.

A DP4 program is not prevented from reading a record that is locked by another program. However, a C program can tell that a record is locked by testing the locked variable as in the sample code below:

while (rec_fetch_main(EQUAL + LOCK, &order_header.l))
{
  if (locked)
  { 
    /* Display Error Message */
    printf("Sorry another user this order locked\n");
    ... 
  }
  else
    printf("Hurray! You locked the order\n"); 
}

The locked variable is set whether or not a program is trying to lock the record itself.

If a program tries to update a record that is locked by another program it will get a LOCK_FAILURE error when it tries to commit the transaction.

There are limitations to record locking in DP4:

We strongly recommend that you use record locking only sparingly if at all. In many cases careful design of a system can eliminate many possible causes of contention.