ptg10805159
774 ADatabase Library Chapter 20
564 /*
565 * Store a record in the database. Return 0 if OK, 1 if record
566 * exists and DB_INSERT specified, -1 on error.
567 */
568 int
569 db_store(DBHANDLE h, const char *key, const char *data, int flag)
570 {
571 DB *db = h;
572 int rc, keylen, datlen;
573 off_t ptrval;
574 if (flag != DB_INSERT && flag != DB_REPLACE &&
575 flag != DB_STORE) {
576 errno=EINVAL;
577 return(-1);
578 }
579 keylen=strlen(key);
580 datlen=strlen(data) + 1; /* +1 for newline at end */
581 if (datlen < DATLEN_MIN || datlen > DATLEN_MAX)
582 err_dump("db_store: invalid data length");
583 /*
584 * _db_find_and_lock calculates which hash table this new record
585 * goes into (db->chainoff), regardless of whether it already
586 * exists or not. The following calls to _db_writeptr change the
587 * hash table entry for this chain to point to the new record.
588 * The new record is added to the front of the hash chain.
589 */
590 if (_db_find_and_lock(db, key, 1) < 0) { /* record not found */
591 if (flag == DB_REPLACE) {
592 rc =-1;
593 db->cnt_storerr++;
594 errno=ENOENT; /* error, record does not exist */
595 goto doreturn;
596 }
[564 – 582] We usedb_storeto add a record to the database. We first validate the flag
value we arepassed. Then we make surethat the length of the data recordis
valid. If it isn’t, we drop coreand exit. This is OK for an example, but if we
werebuilding a production-quality library,we’d return an error status
instead, which would give the application a chance to recover.
[583 – 596] We call_db_find_and_lockto see if the recordalready exists. It is OK if
the recorddoesn’t exist and eitherDB_INSERTorDB_STOREis specified, or
if the recordalready exists and either DB_REPLACE or DB_STORE is
specified. Replacing an existing recordimplies that the keys areidentical
but that the data records probably differ.Note that the final argument to
_db_find_and_lockspecifies that the hash chain must be write locked, as
we will probably be modifying this hash chain.