ptg10805159
776 ADatabase Library Chapter 20
626 } else { /* record found */
627 if (flag == DB_INSERT) {
628 rc =1;/*error, record already in db */
629 db->cnt_storerr++;
630 goto doreturn;
631 }
632 /*
633 * We are replacing an existing record. We know the new
634 * key equals the existing key, but we need to check if
635 * the data records are the same size.
636 */
637 if (datlen != db->datlen) {
638 _db_dodelete(db); /* delete the existing record */
639 /*
640 * Reread the chain ptr in the hash table
641 * (it may change with the deletion).
642 */
643 ptrval =_db_readptr(db, db->chainoff);
644 /*
645 * Append new index and data records to end of files.
646 */
647 _db_writedat(db, data, 0, SEEK_END);
648 _db_writeidx(db, key, 0, SEEK_END, ptrval);
649 /*
650 * New record goes to the front of the hash chain.
651 */
652 _db_writeptr(db, db->chainoff, db->idxoff);
653 db->cnt_stor3++;
654 } else {
[626 – 631] Now we reach the two cases in which a recordwith the same key already
exists in the database. If the caller isn’t replacing the record, we set the
return code to indicate that a recordexists, increment the count of the
number of storeerrors, and jump to the end of the function, wherewe
handle the common return logic.
[632 – 654] Case 3: an existing record is being replaced, and the length of the new data
recorddiffers from the length of the existing one.We call_db_dodeleteto
delete the existing record. Recall that this places the deleted record at the
head of the free list. Then we append the new record to the ends of the data
and index files by calling_db_writedatand_db_writeidx.(Thereare
other ways to handle this case.We could try to find a deleted recordthat has
the correct data size.) The new record is added to the front of the hash chain
by calling_db_writeptr.Thecnt_stor3counter in theDBstructure
records the number of times we’ve executed this case.