Traverse all KV

This example demonstrates that if you traverse all KVs in KVDB, users can add their own processing actions when traversing KVs.

Code description

In the following sample code, first initialize the iterator of KVDB, and then use the iterator API to traverse all KVs of KVDB one by one.

The traversed KV object contains some attributes of KV, including: key name, value saved addr, value length, etc. The user can read it out through fdb_blob_read in cooperation with fdb_kv_to_blob, and do some business processing of his own.

  1. void kvdb_tarversal_sample(fdb_kvdb_t kvdb)
  2. {
  3. struct fdb_kv_iterator iterator;
  4. fdb_kv_t cur_kv;
  5. struct fdb_blob blob;
  6. size_t data_size;
  7. uint8_t *data_buf;
  8. fdb_kv_iterator_init(kvdb, &iterator);
  9. while (fdb_kv_iterate(kvdb, &iterator)) {
  10. cur_kv = &(iterator.curr_kv);
  11. data_size = (size_t) cur_kv->value_len;
  12. data_buf = (uint8_t *) malloc(data_size);
  13. if (data_buf == NULL) {
  14. FDB_INFO("Error: malloc failed.\n");
  15. break;
  16. }
  17. fdb_blob_read((fdb_db_t) kvdb, fdb_kv_to_blob(cur_kv, fdb_blob_make(&blob, data_buf, data_size)));
  18. /*
  19. * balabala do what ever you like with blob...
  20. */
  21. free(data_buf);
  22. }
  23. }