1 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. See the AUTHORS file for names of contributors.
5 #include "db/db_iter.h"
7 #include "db/filename.h"
8 #include "db/db_impl.h"
9 #include "db/dbformat.h"
10 #include "leveldb/env.h"
11 #include "leveldb/iterator.h"
12 #include "port/port.h"
13 #include "util/logging.h"
14 #include "util/mutexlock.h"
15 #include "util/random.h"
18 #define ssize_t size_t
24 static void DumpInternalIter(Iterator* iter) {
25 for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
27 if (!ParseInternalKey(iter->key(), &k)) {
28 fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
30 fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
38 // Memtables and sstables that make the DB representation contain
39 // (userkey,seq,type) => uservalue entries. DBIter
40 // combines multiple entries for the same userkey found in the DB
41 // representation into a single entry while accounting for sequence
42 // numbers, deletion markers, overwrites, etc.
43 class DBIter: public Iterator {
45 // Which direction is the iterator currently moving?
46 // (1) When moving forward, the internal iterator is positioned at
47 // the exact entry that yields this->key(), this->value()
48 // (2) When moving backwards, the internal iterator is positioned
49 // just before all entries whose user key == this->key().
55 DBIter(DBImpl* db, const Comparator* cmp, Iterator* iter, SequenceNumber s,
58 user_comparator_(cmp),
64 bytes_counter_(RandomPeriod()) {
69 virtual bool Valid() const { return valid_; }
70 virtual Slice key() const {
72 return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_;
74 virtual Slice value() const {
76 return (direction_ == kForward) ? iter_->value() : saved_value_;
78 virtual Status status() const {
80 return iter_->status();
88 virtual void Seek(const Slice& target);
89 virtual void SeekToFirst();
90 virtual void SeekToLast();
93 void FindNextUserEntry(bool skipping, std::string* skip);
94 void FindPrevUserEntry();
95 bool ParseKey(ParsedInternalKey* key);
97 inline void SaveKey(const Slice& k, std::string* dst) {
98 dst->assign(k.data(), k.size());
101 inline void ClearSavedValue() {
102 if (saved_value_.capacity() > 1048576) {
104 swap(empty, saved_value_);
106 saved_value_.clear();
110 // Pick next gap with average value of config::kReadBytesPeriod.
111 ssize_t RandomPeriod() {
112 return rnd_.Uniform(2*config::kReadBytesPeriod);
116 const Comparator* const user_comparator_;
117 Iterator* const iter_;
118 SequenceNumber const sequence_;
121 std::string saved_key_; // == current key when direction_==kReverse
122 std::string saved_value_; // == current raw value when direction_==kReverse
123 Direction direction_;
127 ssize_t bytes_counter_;
129 // No copying allowed
130 DBIter(const DBIter&);
131 void operator=(const DBIter&);
134 inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
135 Slice k = iter_->key();
136 ssize_t n = k.size() + iter_->value().size();
138 while (bytes_counter_ < 0) {
139 bytes_counter_ += RandomPeriod();
140 db_->RecordReadSample(k);
142 if (!ParseInternalKey(k, ikey)) {
143 status_ = Status::Corruption("corrupted internal key in DBIter");
150 void DBIter::Next() {
153 if (direction_ == kReverse) { // Switch directions?
154 direction_ = kForward;
155 // iter_ is pointing just before the entries for this->key(),
156 // so advance into the range of entries for this->key() and then
157 // use the normal skipping code below.
158 if (!iter_->Valid()) {
159 iter_->SeekToFirst();
163 if (!iter_->Valid()) {
168 // saved_key_ already contains the key to skip past.
170 // Store in saved_key_ the current key so we skip it below.
171 SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
174 FindNextUserEntry(true, &saved_key_);
177 void DBIter::FindNextUserEntry(bool skipping, std::string* skip) {
178 // Loop until we hit an acceptable entry to yield
179 assert(iter_->Valid());
180 assert(direction_ == kForward);
182 ParsedInternalKey ikey;
183 if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
186 // Arrange to skip all upcoming entries for this key since
187 // they are hidden by this deletion.
188 SaveKey(ikey.user_key, skip);
193 user_comparator_->Compare(ikey.user_key, *skip) <= 0) {
204 } while (iter_->Valid());
209 void DBIter::Prev() {
212 if (direction_ == kForward) { // Switch directions?
213 // iter_ is pointing at the current entry. Scan backwards until
214 // the key changes so we can use the normal reverse scanning code.
215 assert(iter_->Valid()); // Otherwise valid_ would have been false
216 SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
219 if (!iter_->Valid()) {
225 if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
230 direction_ = kReverse;
236 void DBIter::FindPrevUserEntry() {
237 assert(direction_ == kReverse);
239 ValueType value_type = kTypeDeletion;
240 if (iter_->Valid()) {
242 ParsedInternalKey ikey;
243 if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
244 if ((value_type != kTypeDeletion) &&
245 user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
246 // We encountered a non-deleted value in entries for previous keys,
249 value_type = ikey.type;
250 if (value_type == kTypeDeletion) {
254 Slice raw_value = iter_->value();
255 if (saved_value_.capacity() > raw_value.size() + 1048576) {
257 swap(empty, saved_value_);
259 SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
260 saved_value_.assign(raw_value.data(), raw_value.size());
264 } while (iter_->Valid());
267 if (value_type == kTypeDeletion) {
272 direction_ = kForward;
278 void DBIter::Seek(const Slice& target) {
279 direction_ = kForward;
283 &saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
284 iter_->Seek(saved_key_);
285 if (iter_->Valid()) {
286 FindNextUserEntry(false, &saved_key_ /* temporary storage */);
292 void DBIter::SeekToFirst() {
293 direction_ = kForward;
295 iter_->SeekToFirst();
296 if (iter_->Valid()) {
297 FindNextUserEntry(false, &saved_key_ /* temporary storage */);
303 void DBIter::SeekToLast() {
304 direction_ = kReverse;
310 } // anonymous namespace
312 Iterator* NewDBIterator(
314 const Comparator* user_key_comparator,
315 Iterator* internal_iter,
316 SequenceNumber sequence,
318 return new DBIter(db, user_key_comparator, internal_iter, sequence, seed);
321 } // namespace leveldb