db_iter.cc 12.0 KB
Newer Older
J
jorlow@chromium.org 已提交
1 2 3 4
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

5
#include <stdexcept>
J
jorlow@chromium.org 已提交
6 7 8 9
#include "db/db_iter.h"

#include "db/filename.h"
#include "db/dbformat.h"
10
#include "leveldb/env.h"
11
#include "leveldb/options.h"
12
#include "leveldb/iterator.h"
13
#include "leveldb/merge_operator.h"
J
jorlow@chromium.org 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include "port/port.h"
#include "util/logging.h"
#include "util/mutexlock.h"

namespace leveldb {

#if 0
static void DumpInternalIter(Iterator* iter) {
  for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
    ParsedInternalKey k;
    if (!ParseInternalKey(iter->key(), &k)) {
      fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
    } else {
      fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
    }
  }
}
#endif

namespace {

// Memtables and sstables that make the DB representation contain
// (userkey,seq,type) => uservalue entries.  DBIter
// combines multiple entries for the same userkey found in the DB
// representation into a single entry while accounting for sequence
// numbers, deletion markers, overwrites, etc.
class DBIter: public Iterator {
 public:
42
  // The following is grossly complicated. TODO: clean it up
J
jorlow@chromium.org 已提交
43 44 45 46 47 48 49 50 51 52
  // Which direction is the iterator currently moving?
  // (1) When moving forward, the internal iterator is positioned at
  //     the exact entry that yields this->key(), this->value()
  // (2) When moving backwards, the internal iterator is positioned
  //     just before all entries whose user key == this->key().
  enum Direction {
    kForward,
    kReverse
  };

53
  DBIter(const std::string* dbname, Env* env, const Options& options,
J
jorlow@chromium.org 已提交
54 55 56
         const Comparator* cmp, Iterator* iter, SequenceNumber s)
      : dbname_(dbname),
        env_(env),
57
        logger_(options.info_log),
J
jorlow@chromium.org 已提交
58
        user_comparator_(cmp),
59
        user_merge_operator_(options.merge_operator),
J
jorlow@chromium.org 已提交
60 61
        iter_(iter),
        sequence_(s),
J
jorlow@chromium.org 已提交
62
        direction_(kForward),
63 64
        valid_(false),
        current_entry_is_merged_(false) {
J
jorlow@chromium.org 已提交
65 66 67 68 69 70 71
  }
  virtual ~DBIter() {
    delete iter_;
  }
  virtual bool Valid() const { return valid_; }
  virtual Slice key() const {
    assert(valid_);
72
    return saved_key_;
J
jorlow@chromium.org 已提交
73 74 75
  }
  virtual Slice value() const {
    assert(valid_);
76 77
    return (direction_ == kForward && !current_entry_is_merged_) ?
      iter_->value() : saved_value_;
J
jorlow@chromium.org 已提交
78 79 80 81 82 83 84 85 86
  }
  virtual Status status() const {
    if (status_.ok()) {
      return iter_->status();
    } else {
      return status_;
    }
  }

J
jorlow@chromium.org 已提交
87 88 89 90 91
  virtual void Next();
  virtual void Prev();
  virtual void Seek(const Slice& target);
  virtual void SeekToFirst();
  virtual void SeekToLast();
J
jorlow@chromium.org 已提交
92

J
jorlow@chromium.org 已提交
93
 private:
94
  void FindNextUserEntry(bool skipping);
J
jorlow@chromium.org 已提交
95 96
  void FindPrevUserEntry();
  bool ParseKey(ParsedInternalKey* key);
97
  void MergeValuesNewToOld();
J
jorlow@chromium.org 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111

  inline void SaveKey(const Slice& k, std::string* dst) {
    dst->assign(k.data(), k.size());
  }

  inline void ClearSavedValue() {
    if (saved_value_.capacity() > 1048576) {
      std::string empty;
      swap(empty, saved_value_);
    } else {
      saved_value_.clear();
    }
  }

J
jorlow@chromium.org 已提交
112 113
  const std::string* const dbname_;
  Env* const env_;
114
  shared_ptr<Logger> logger_;
J
jorlow@chromium.org 已提交
115
  const Comparator* const user_comparator_;
116
  const MergeOperator* const user_merge_operator_;
J
jorlow@chromium.org 已提交
117 118
  Iterator* const iter_;
  SequenceNumber const sequence_;
J
jorlow@chromium.org 已提交
119

J
jorlow@chromium.org 已提交
120
  Status status_;
J
jorlow@chromium.org 已提交
121 122
  std::string saved_key_;     // == current key when direction_==kReverse
  std::string saved_value_;   // == current raw value when direction_==kReverse
123
  std::string skip_key_;
J
jorlow@chromium.org 已提交
124
  Direction direction_;
J
jorlow@chromium.org 已提交
125
  bool valid_;
126
  bool current_entry_is_merged_;
J
jorlow@chromium.org 已提交
127 128 129 130 131 132 133 134 135

  // No copying allowed
  DBIter(const DBIter&);
  void operator=(const DBIter&);
};

inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
  if (!ParseInternalKey(iter_->key(), ikey)) {
    status_ = Status::Corruption("corrupted internal key in DBIter");
136 137
    Log(logger_, "corrupted internal key in DBIter: %s",
        iter_->key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
138 139 140 141 142 143
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
144 145 146 147 148 149 150 151 152 153 154
void DBIter::Next() {
  assert(valid_);

  if (direction_ == kReverse) {  // Switch directions?
    direction_ = kForward;
    // iter_ is pointing just before the entries for this->key(),
    // so advance into the range of entries for this->key() and then
    // use the normal skipping code below.
    if (!iter_->Valid()) {
      iter_->SeekToFirst();
    } else {
J
jorlow@chromium.org 已提交
155 156
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
157 158 159 160
    if (!iter_->Valid()) {
      valid_ = false;
      saved_key_.clear();
      return;
J
jorlow@chromium.org 已提交
161 162
    }
  }
J
jorlow@chromium.org 已提交
163

164 165 166 167 168 169
  // If the current value is merged, we might already hit end of iter_
  if (!iter_->Valid()) {
    valid_ = false;
    return;
  }
  FindNextUserEntry(true /* skipping the current user key */);
J
jorlow@chromium.org 已提交
170 171
}

172 173 174 175 176 177 178 179 180 181

// PRE: saved_key_ has the current user key if skipping
// POST: saved_key_ should have the next user key if valid_,
//       if the current entry is a result of merge
//           current_entry_is_merged_ => true
//           saved_value_             => the merged value
//
// NOTE: In between, saved_key_ can point to a user key that has
//       a delete marker
void DBIter::FindNextUserEntry(bool skipping) {
J
jorlow@chromium.org 已提交
182 183 184
  // Loop until we hit an acceptable entry to yield
  assert(iter_->Valid());
  assert(direction_ == kForward);
185
  current_entry_is_merged_ = false;
J
jorlow@chromium.org 已提交
186
  do {
J
jorlow@chromium.org 已提交
187
    ParsedInternalKey ikey;
J
jorlow@chromium.org 已提交
188
    if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
189 190 191 192 193 194 195 196 197 198 199 200 201
      if (skipping &&
          user_comparator_->Compare(ikey.user_key, saved_key_) <= 0) {
        // skip this entry
      } else {
        skipping = false;
        switch (ikey.type) {
          case kTypeDeletion:
            // Arrange to skip all upcoming entries for this key since
            // they are hidden by this deletion.
            SaveKey(ikey.user_key, &saved_key_);
            skipping = true;
            break;
          case kTypeValue:
J
jorlow@chromium.org 已提交
202
            valid_ = true;
203
            SaveKey(ikey.user_key, &saved_key_);
J
jorlow@chromium.org 已提交
204
            return;
205 206 207 208 209 210 211 212 213 214 215
          case kTypeMerge:
            // By now, we are sure the current ikey is going to yield a value
            SaveKey(ikey.user_key, &saved_key_);
            current_entry_is_merged_ = true;
            valid_ = true;
            // Go to a different state machine
            MergeValuesNewToOld();
            // TODO: what if !iter_->Valid()
            return;
            break;
        }
J
jorlow@chromium.org 已提交
216
      }
J
jorlow@chromium.org 已提交
217 218
    }
    iter_->Next();
J
jorlow@chromium.org 已提交
219 220
  } while (iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
221 222
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
// Merge values of the same user key starting from the current iter_ position
// Scan from the newer entries to older entries.
// PRE: iter_->key() points to the first merge type entry
//      saved_key_ stores the user key
// POST: saved_value_ has the merged value for the user key
//       iter_ points to the next entry (or invalid)
void DBIter::MergeValuesNewToOld() {

  const Slice value = iter_->value();
  std::string operand(value.data(), value.size());

  ParsedInternalKey ikey;
  for (iter_->Next(); iter_->Valid(); iter_->Next()) {
    if (!ParseKey(&ikey)) {
      // skip corrupted key
      continue;
    }

    if (user_comparator_->Compare(ikey.user_key, saved_key_) != 0) {
      // hit the next user key, stop right here
      break;
    }

    if (kTypeDeletion == ikey.type) {
      // hit a delete with the same user key, stop right here
      // iter_ is positioned after delete
      iter_->Next();
      break;
    }

    if (kTypeValue == ikey.type) {
      // hit a put, merge the put value with operand and store it in the
      // final result saved_value_. We are done!
      const Slice value = iter_->value();
      user_merge_operator_->Merge(ikey.user_key, &value, Slice(operand),
                                  &saved_value_, logger_.get());
      // iter_ is positioned after put
      iter_->Next();
      return;
    }

    if (kTypeMerge == ikey.type) {
      // hit a merge, merge the value with operand and continue.
      // saved_value_ is used as a scratch area. The result is put
      // back in operand
      const Slice value = iter_->value();
      user_merge_operator_->Merge(ikey.user_key, &value, operand,
                                  &saved_value_, logger_.get());
      swap(saved_value_, operand);
    }
  }

  // we either exhausted all internal keys under this user key, or hit
  // a deletion marker.
  // feed null as the existing value to the merge opexrator, such that
  // client can differentiate this scenario and do things accordingly.
  user_merge_operator_->Merge(ikey.user_key, nullptr, operand,
                              &saved_value_, logger_.get());
}

J
jorlow@chromium.org 已提交
283 284
void DBIter::Prev() {
  assert(valid_);
J
jorlow@chromium.org 已提交
285

286 287 288 289 290 291 292 293
  // TODO: support backward iteration
  // Throw an exception now if merge_operator is provided
  if (user_merge_operator_) {
    Log(logger_, "Prev not supported yet if merge_operator is provided");
    throw std::logic_error("DBIter::Prev backward iteration not supported"
                           " if merge_operator is provided");
  }

J
jorlow@chromium.org 已提交
294 295 296 297 298 299 300
  if (direction_ == kForward) {  // Switch directions?
    // iter_ is pointing at the current entry.  Scan backwards until
    // the key changes so we can use the normal reverse scanning code.
    assert(iter_->Valid());  // Otherwise valid_ would have been false
    SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
    while (true) {
      iter_->Prev();
J
jorlow@chromium.org 已提交
301
      if (!iter_->Valid()) {
J
jorlow@chromium.org 已提交
302 303 304
        valid_ = false;
        saved_key_.clear();
        ClearSavedValue();
J
jorlow@chromium.org 已提交
305 306
        return;
      }
J
jorlow@chromium.org 已提交
307 308 309 310
      if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
                                    saved_key_) < 0) {
        break;
      }
J
jorlow@chromium.org 已提交
311
    }
J
jorlow@chromium.org 已提交
312
    direction_ = kReverse;
J
jorlow@chromium.org 已提交
313
  }
J
jorlow@chromium.org 已提交
314 315

  FindPrevUserEntry();
J
jorlow@chromium.org 已提交
316 317
}

J
jorlow@chromium.org 已提交
318 319
void DBIter::FindPrevUserEntry() {
  assert(direction_ == kReverse);
J
jorlow@chromium.org 已提交
320

J
jorlow@chromium.org 已提交
321 322 323 324 325 326 327 328 329 330 331 332
  ValueType value_type = kTypeDeletion;
  if (iter_->Valid()) {
    do {
      ParsedInternalKey ikey;
      if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
        if ((value_type != kTypeDeletion) &&
            user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
          // We encountered a non-deleted value in entries for previous keys,
          break;
        }
        value_type = ikey.type;
        if (value_type == kTypeDeletion) {
333
          saved_key_.clear();
J
jorlow@chromium.org 已提交
334 335 336 337 338 339 340
          ClearSavedValue();
        } else {
          Slice raw_value = iter_->value();
          if (saved_value_.capacity() > raw_value.size() + 1048576) {
            std::string empty;
            swap(empty, saved_value_);
          }
341
          SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
J
jorlow@chromium.org 已提交
342 343 344
          saved_value_.assign(raw_value.data(), raw_value.size());
        }
      }
J
jorlow@chromium.org 已提交
345
      iter_->Prev();
J
jorlow@chromium.org 已提交
346 347
    } while (iter_->Valid());
  }
J
jorlow@chromium.org 已提交
348

J
jorlow@chromium.org 已提交
349 350 351 352 353 354 355 356 357 358
  if (value_type == kTypeDeletion) {
    // End
    valid_ = false;
    saved_key_.clear();
    ClearSavedValue();
    direction_ = kForward;
  } else {
    valid_ = true;
  }
}
J
jorlow@chromium.org 已提交
359

J
jorlow@chromium.org 已提交
360 361 362 363 364 365 366 367
void DBIter::Seek(const Slice& target) {
  direction_ = kForward;
  ClearSavedValue();
  saved_key_.clear();
  AppendInternalKey(
      &saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
  iter_->Seek(saved_key_);
  if (iter_->Valid()) {
368
    FindNextUserEntry(false /*not skipping */);
J
jorlow@chromium.org 已提交
369 370 371 372
  } else {
    valid_ = false;
  }
}
J
jorlow@chromium.org 已提交
373

J
jorlow@chromium.org 已提交
374 375 376 377 378
void DBIter::SeekToFirst() {
  direction_ = kForward;
  ClearSavedValue();
  iter_->SeekToFirst();
  if (iter_->Valid()) {
379
    FindNextUserEntry(false /* not skipping */);
J
jorlow@chromium.org 已提交
380 381
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
382 383 384
  }
}

J
jorlow@chromium.org 已提交
385
void DBIter::SeekToLast() {
386 387 388 389 390 391 392 393
  // TODO: support backward iteration
  // throw an exception for now if merge_operator is provided
  if (user_merge_operator_) {
    Log(logger_, "SeekToLast not supported yet if merge_operator is provided");
    throw std::logic_error("DBIter::SeekToLast: backward iteration not"
                           " supported if merge_operator is provided");
  }

J
jorlow@chromium.org 已提交
394 395 396 397 398 399
  direction_ = kReverse;
  ClearSavedValue();
  iter_->SeekToLast();
  FindPrevUserEntry();
}

J
jorlow@chromium.org 已提交
400 401 402 403 404
}  // anonymous namespace

Iterator* NewDBIterator(
    const std::string* dbname,
    Env* env,
405 406
    const Options& options,
    const Comparator *user_key_comparator,
J
jorlow@chromium.org 已提交
407 408
    Iterator* internal_iter,
    const SequenceNumber& sequence) {
409 410
  return new DBIter(dbname, env, options, user_key_comparator,
                    internal_iter, sequence);
J
jorlow@chromium.org 已提交
411 412
}

H
Hans Wennborg 已提交
413
}  // namespace leveldb