leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions()); for (it->SeekToFirst(); it->Valid(); it->Next()) { cout << it->key().ToString() << ": " << it->value().ToString() << endl; } assert(it->status().ok()); // Check for any errors found during the scan delete it;
voidVersion::AddIterators(const ReadOptions& options, std::vector<Iterator*>* iters){ // level0的全部sst都会创建迭代器,因为数据重叠 for (size_t i = 0; i < files_[0].size(); i++) { iters->push_back(vset_->table_cache_->NewIterator( options, files_[0][i]->number, files_[0][i]->file_size)); }
// For levels > 0, we can use a concatenating iterator that sequentially // walks through the non-overlapping files in the level, opening them // lazily. for (int level = 1; level < config::kNumLevels; level++) { if (!files_[level].empty()) { // level1~n的双层迭代器,本文前言中有提到 iters->push_back(NewConcatenatingIterator(options, level)); } } }
template <typename Key, classComparator> inlinevoid SkipList<Key, Comparator>::Iterator::Prev() { // Instead of using explicit "prev" links, we just search for the // last node that falls before key. assert(Valid()); node_ = list_->FindLessThan(node_->key); if (node_ == list_->head_) { node_ = nullptr; } } template <typename Key, classComparator> typename SkipList<Key, Comparator>::Node* SkipList<Key, Comparator>::FindLessThan(const Key& key) const { Node* x = head_; int level = GetMaxHeight() - 1; while (true) { assert(x == head_ || compare_(x->key, key) < 0); Node* next = x->Next(level); if (next == nullptr || compare_(next->key, key) >= 0) { if (level == 0) { return x; } else { // Switch to next list level--; } } else { x = next; } } }
Snapshot
leveldb提供了两个接口,用于获取和释放Snapshot
1 2 3 4 5 6 7 8 9
// Return a handle to the current DB state. Iterators created with // this handle will all observe a stable snapshot of the current DB // state. The caller must call ReleaseSnapshot(result) when the // snapshot is no longer needed. virtualconst Snapshot* GetSnapshot()= 0;
// Release a previously acquired snapshot. The caller must not // use "snapshot" after this call. virtualvoidReleaseSnapshot(const Snapshot* snapshot)= 0;