Tutorial

Point Lookups

The function for looking up Database items is called ups_db_find. This function receives five parameters, of which one (flags) is unused and always set to 0. The third parameter (key) receives a pointer to an initialized ups_key_t structure. If the key is found, the record of this key is returned in parameter four (record).

The second parameter of ups_db_find is a Transaction handle; if you do not use Transactions, then set this parameter to NULL. Transactions are covered in a later chapter.

ups_status_t
ups_db_find (ups_db_t *db, ups_txn_t *txn, ups_key_t *key,
            ups_record_t *record, uint32_t flags);

API reference for ups_db_find

The following example looks up the key "color":

ups_status_t st;
ups_key_t key = ups_make_key((void *)"color", strlen("color") + 1);
ups_record_t record = {0};

if ((st = ups_db_find (db, NULL, &key, &record, 0)) != UPS_SUCCESS) {
  printf ("error %d (%s)\n", st, ups_strerror (st));
  exit (–1);
}

If you followed the tutorial, ups_db_find returns error UPS_KEY_NOT_FOUND, because we deleted the key “color” in the previous chapter. If you did NOT delete the key, record.data will now point to the string “green” and record.size will be 6 (it includes the terminating zero byte).

Please bear in mind that record.data is a temporary pointer which is allocated by the upscaledb library. Other calls to API functions can overwrite this pointer. If you want to avoid this behaviour you can allocate the pointer on your own and set the flag UPS_RECORD_USER_ALLOC. In this case it is your responsibility to make sure that the allocated memory is actually large enough for the data. Alternatively you can use Transactions, and the record.data pointer is stored in the Transaction object. Especially when using multiple threads it makes sense to have each Thread manipulate its own Transaction object.

char buffer[64];
ups_record_t record = ups_make_record(&buffer[0], sizeof(buffer));
record.flags = UPS_RECORD_USER_ALLOC;

if ((st = ups_db_find (db, NULL, &key, &record, 0)) != UPS_SUCCESS) {
  printf ("error %d (%s)\n", st, ups_strerror (st));
  exit (–1);
}