db_iter.cc 29.1 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 3 4 5
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
J
jorlow@chromium.org 已提交
6 7 8 9 10
// 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.

#include "db/db_iter.h"
11
#include <stdexcept>
12
#include <deque>
S
Stanislau Hlebik 已提交
13
#include <string>
S
Stanislau Hlebik 已提交
14
#include <limits>
J
jorlow@chromium.org 已提交
15 16

#include "db/dbformat.h"
17
#include "db/filename.h"
S
sdong 已提交
18
#include "port/port.h"
19 20 21
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
#include "rocksdb/merge_operator.h"
22
#include "rocksdb/options.h"
S
sdong 已提交
23
#include "table/internal_iterator.h"
24
#include "util/arena.h"
J
jorlow@chromium.org 已提交
25 26
#include "util/logging.h"
#include "util/mutexlock.h"
27
#include "util/perf_context_imp.h"
28
#include "util/string_util.h"
J
jorlow@chromium.org 已提交
29

30
namespace rocksdb {
J
jorlow@chromium.org 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

#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

// 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:
52
  // The following is grossly complicated. TODO: clean it up
J
jorlow@chromium.org 已提交
53 54 55 56 57 58 59 60 61 62
  // 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
  };

S
sdong 已提交
63 64
  DBIter(Env* env, const ImmutableCFOptions& ioptions, const Comparator* cmp,
         InternalIterator* iter, SequenceNumber s, bool arena_mode,
65
         uint64_t max_sequential_skip_in_iterations, uint64_t version_number,
66 67
         const Slice* iterate_upper_bound = nullptr,
         bool prefix_same_as_start = false)
68 69
      : arena_mode_(arena_mode),
        env_(env),
70
        logger_(ioptions.info_log),
J
jorlow@chromium.org 已提交
71
        user_comparator_(cmp),
72
        user_merge_operator_(ioptions.merge_operator),
J
jorlow@chromium.org 已提交
73 74
        iter_(iter),
        sequence_(s),
J
jorlow@chromium.org 已提交
75
        direction_(kForward),
76
        valid_(false),
77
        current_entry_is_merged_(false),
78
        statistics_(ioptions.statistics),
79
        version_number_(version_number),
80
        iterate_upper_bound_(iterate_upper_bound),
81 82
        prefix_same_as_start_(prefix_same_as_start),
        iter_pinned_(false) {
L
Lei Jin 已提交
83
    RecordTick(statistics_, NO_ITERATORS);
84 85
    prefix_extractor_ = ioptions.prefix_extractor;
    max_skip_ = max_sequential_skip_in_iterations;
J
jorlow@chromium.org 已提交
86 87
  }
  virtual ~DBIter() {
88
    RecordTick(statistics_, NO_ITERATORS, -1);
89 90 91
    if (!arena_mode_) {
      delete iter_;
    } else {
S
sdong 已提交
92
      iter_->~InternalIterator();
93 94
    }
  }
S
sdong 已提交
95
  virtual void SetIter(InternalIterator* iter) {
96 97
    assert(iter_ == nullptr);
    iter_ = iter;
98 99 100
    if (iter_ && iter_pinned_) {
      iter_->PinData();
    }
J
jorlow@chromium.org 已提交
101
  }
I
Igor Sugak 已提交
102 103
  virtual bool Valid() const override { return valid_; }
  virtual Slice key() const override {
J
jorlow@chromium.org 已提交
104
    assert(valid_);
105
    return saved_key_.GetKey();
J
jorlow@chromium.org 已提交
106
  }
I
Igor Sugak 已提交
107
  virtual Slice value() const override {
J
jorlow@chromium.org 已提交
108
    assert(valid_);
109 110
    return (direction_ == kForward && !current_entry_is_merged_) ?
      iter_->value() : saved_value_;
J
jorlow@chromium.org 已提交
111
  }
I
Igor Sugak 已提交
112
  virtual Status status() const override {
J
jorlow@chromium.org 已提交
113 114 115 116 117 118
    if (status_.ok()) {
      return iter_->status();
    } else {
      return status_;
    }
  }
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  virtual Status PinData() {
    Status s;
    if (iter_) {
      s = iter_->PinData();
    }
    if (s.ok()) {
      // Even if iter_ is nullptr, we set iter_pinned_ to true so that when
      // iter_ is updated using SetIter, we Pin it.
      iter_pinned_ = true;
    }
    return s;
  }
  virtual Status ReleasePinnedData() {
    Status s;
    if (iter_) {
      s = iter_->ReleasePinnedData();
    }
    if (s.ok()) {
      iter_pinned_ = false;
    }
    return s;
  }
141 142 143 144 145 146

  virtual Status GetProperty(std::string prop_name,
                             std::string* prop) override {
    if (prop == nullptr) {
      return Status::InvalidArgument("prop is nullptr");
    }
147 148 149 150 151 152 153
    if (prop_name == "rocksdb.iterator.version-number") {
      // First try to pass the value returned from inner iterator.
      if (!iter_->GetProperty(prop_name, prop).ok()) {
        *prop = ToString(version_number_);
      }
      return Status::OK();
    } else if (prop_name == "rocksdb.iterator.is-key-pinned") {
154 155 156 157 158 159 160 161
      if (valid_) {
        *prop = (iter_pinned_ && saved_key_.IsKeyPinned()) ? "1" : "0";
      } else {
        *prop = "Iterator is not valid.";
      }
      return Status::OK();
    }
    return Status::InvalidArgument("Undentified property.");
162
  }
J
jorlow@chromium.org 已提交
163

I
Igor Sugak 已提交
164 165 166 167 168
  virtual void Next() override;
  virtual void Prev() override;
  virtual void Seek(const Slice& target) override;
  virtual void SeekToFirst() override;
  virtual void SeekToLast() override;
J
jorlow@chromium.org 已提交
169

J
jorlow@chromium.org 已提交
170
 private:
171
  void ReverseToBackward();
S
Stanislau Hlebik 已提交
172 173 174 175 176 177
  void PrevInternal();
  void FindParseableKey(ParsedInternalKey* ikey, Direction direction);
  bool FindValueForCurrentKey();
  bool FindValueForCurrentKeyUsingSeek();
  void FindPrevUserKey();
  void FindNextUserKey();
178 179
  inline void FindNextUserEntry(bool skipping);
  void FindNextUserEntryInternal(bool skipping);
J
jorlow@chromium.org 已提交
180
  bool ParseKey(ParsedInternalKey* key);
181
  void MergeValuesNewToOld();
J
jorlow@chromium.org 已提交
182 183 184 185 186 187 188 189 190 191

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

192
  const SliceTransform* prefix_extractor_;
193
  bool arena_mode_;
J
jorlow@chromium.org 已提交
194
  Env* const env_;
I
Igor Canadi 已提交
195
  Logger* logger_;
J
jorlow@chromium.org 已提交
196
  const Comparator* const user_comparator_;
197
  const MergeOperator* const user_merge_operator_;
S
sdong 已提交
198
  InternalIterator* iter_;
J
jorlow@chromium.org 已提交
199
  SequenceNumber const sequence_;
J
jorlow@chromium.org 已提交
200

J
jorlow@chromium.org 已提交
201
  Status status_;
S
Stanislau Hlebik 已提交
202 203
  IterKey saved_key_;
  std::string saved_value_;
J
jorlow@chromium.org 已提交
204
  Direction direction_;
J
jorlow@chromium.org 已提交
205
  bool valid_;
206
  bool current_entry_is_merged_;
207
  Statistics* statistics_;
208
  uint64_t max_skip_;
209
  uint64_t version_number_;
210
  const Slice* iterate_upper_bound_;
211
  IterKey prefix_start_;
212
  bool prefix_same_as_start_;
213
  bool iter_pinned_;
214 215
  // List of operands for merge operator.
  std::deque<std::string> merge_operands_;
J
jorlow@chromium.org 已提交
216 217 218 219 220 221 222 223 224

  // 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");
225 226
    Log(InfoLogLevel::ERROR_LEVEL,
        logger_, "corrupted internal key in DBIter: %s",
227
        iter_->key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
228 229 230 231 232 233
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
234 235 236
void DBIter::Next() {
  assert(valid_);

S
Stanislau Hlebik 已提交
237 238
  if (direction_ == kReverse) {
    FindNextUserKey();
J
jorlow@chromium.org 已提交
239 240 241
    direction_ = kForward;
    if (!iter_->Valid()) {
      iter_->SeekToFirst();
J
jorlow@chromium.org 已提交
242
    }
243 244 245 246 247 248 249
  } else if (iter_->Valid() && !current_entry_is_merged_) {
    // If the current value is not a merge, the iter position is the
    // current key, which is already returned. We can safely issue a
    // Next() without checking the current key.
    // If the current key is a merge, very likely iter already points
    // to the next internal position.
    iter_->Next();
250
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
J
jorlow@chromium.org 已提交
251
  }
J
jorlow@chromium.org 已提交
252

253 254
  // Now we point to the next internal position, for both of merge and
  // not merge cases.
255 256 257 258 259
  if (!iter_->Valid()) {
    valid_ = false;
    return;
  }
  FindNextUserEntry(true /* skipping the current user key */);
M
Manuel Ung 已提交
260 261 262 263 264 265 266
  if (statistics_ != nullptr) {
    RecordTick(statistics_, NUMBER_DB_NEXT);
    if (valid_) {
      RecordTick(statistics_, NUMBER_DB_NEXT_FOUND);
      RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
    }
  }
267 268
  if (valid_ && prefix_extractor_ && prefix_same_as_start_ &&
      prefix_extractor_->Transform(saved_key_.GetKey())
269
              .compare(prefix_start_.GetKey()) != 0) {
270 271
    valid_ = false;
  }
J
jorlow@chromium.org 已提交
272 273
}

274 275 276 277 278 279 280 281
// 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
282
inline void DBIter::FindNextUserEntry(bool skipping) {
283
  PERF_TIMER_GUARD(find_next_user_entry_time);
284 285 286 287 288
  FindNextUserEntryInternal(skipping);
}

// Actual implementation of DBIter::FindNextUserEntry()
void DBIter::FindNextUserEntryInternal(bool skipping) {
J
jorlow@chromium.org 已提交
289 290 291
  // Loop until we hit an acceptable entry to yield
  assert(iter_->Valid());
  assert(direction_ == kForward);
292
  current_entry_is_merged_ = false;
293
  uint64_t num_skipped = 0;
J
jorlow@chromium.org 已提交
294
  do {
J
jorlow@chromium.org 已提交
295
    ParsedInternalKey ikey;
296 297 298

    if (ParseKey(&ikey)) {
      if (iterate_upper_bound_ != nullptr &&
299
          user_comparator_->Compare(ikey.user_key, *iterate_upper_bound_) >= 0) {
300 301 302 303 304 305 306 307 308 309 310
        break;
      }

      if (ikey.sequence <= sequence_) {
        if (skipping &&
           user_comparator_->Compare(ikey.user_key, saved_key_.GetKey()) <= 0) {
          num_skipped++;  // skip this entry
          PERF_COUNTER_ADD(internal_key_skipped_count, 1);
        } else {
          switch (ikey.type) {
            case kTypeDeletion:
A
Andres Noetzli 已提交
311
            case kTypeSingleDeletion:
312 313
              // Arrange to skip all upcoming entries for this key since
              // they are hidden by this deletion.
314 315
              saved_key_.SetKey(ikey.user_key,
                                !iter_->IsKeyPinned() /* copy */);
316 317 318 319 320 321
              skipping = true;
              num_skipped = 0;
              PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
              break;
            case kTypeValue:
              valid_ = true;
322 323
              saved_key_.SetKey(ikey.user_key,
                                !iter_->IsKeyPinned() /* copy */);
324 325 326
              return;
            case kTypeMerge:
              // By now, we are sure the current ikey is going to yield a value
327 328
              saved_key_.SetKey(ikey.user_key,
                                !iter_->IsKeyPinned() /* copy */);
329 330 331 332 333 334 335 336
              current_entry_is_merged_ = true;
              valid_ = true;
              MergeValuesNewToOld();  // Go to a different state machine
              return;
            default:
              assert(false);
              break;
          }
337
        }
J
jorlow@chromium.org 已提交
338
      }
J
jorlow@chromium.org 已提交
339
    }
340 341
    // If we have sequentially iterated via numerous keys and still not
    // found the next user-key, then it is better to seek so that we can
C
clark.kang 已提交
342
    // avoid too many key comparisons. We seek to the last occurrence of
343 344
    // our current key by looking for sequence number 0 and type deletion
    // (the smallest type).
345 346 347
    if (skipping && num_skipped > max_skip_) {
      num_skipped = 0;
      std::string last_key;
348
      AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetKey(), 0,
349
                                                     kTypeDeletion));
350 351 352 353 354
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
355 356
  } while (iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
357 358
}

359 360 361 362 363 364 365
// 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() {
D
Deon Nicholas 已提交
366
  if (!user_merge_operator_) {
367 368
    Log(InfoLogLevel::ERROR_LEVEL,
        logger_, "Options::merge_operator is null.");
369 370 371
    status_ = Status::InvalidArgument("user_merge_operator_ must be set.");
    valid_ = false;
    return;
D
Deon Nicholas 已提交
372
  }
373

374 375 376
  // Start the merge process by pushing the first operand
  std::deque<std::string> operands;
  operands.push_front(iter_->value().ToString());
377 378 379 380 381 382 383 384

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

385
    if (!user_comparator_->Equal(ikey.user_key, saved_key_.GetKey())) {
386 387
      // hit the next user key, stop right here
      break;
A
Andres Noetzli 已提交
388
    } else if (kTypeDeletion == ikey.type || kTypeSingleDeletion == ikey.type) {
389 390 391 392
      // hit a delete with the same user key, stop right here
      // iter_ is positioned after delete
      iter_->Next();
      break;
A
Andres Noetzli 已提交
393
    } else if (kTypeValue == ikey.type) {
394 395 396
      // hit a put, merge the put value with operands and store the
      // final result in saved_value_. We are done!
      // ignore corruption if there is any.
I
Igor Canadi 已提交
397
      const Slice val = iter_->value();
398 399 400 401 402 403 404 405
      {
        StopWatchNano timer(env_, statistics_ != nullptr);
        PERF_TIMER_GUARD(merge_operator_time_nanos);
        user_merge_operator_->FullMerge(ikey.user_key, &val, operands,
                                        &saved_value_, logger_);
        RecordTick(statistics_, MERGE_OPERATION_TOTAL_TIME,
                   timer.ElapsedNanos());
      }
406 407 408
      // iter_ is positioned after put
      iter_->Next();
      return;
A
Andres Noetzli 已提交
409
    } else if (kTypeMerge == ikey.type) {
410 411
      // hit a merge, add the value as an operand and run associative merge.
      // when complete, add result to operands and continue.
I
Igor Canadi 已提交
412 413
      const Slice& val = iter_->value();
      operands.push_front(val.ToString());
A
Andres Noetzli 已提交
414 415
    } else {
      assert(false);
416 417 418
    }
  }

419 420 421 422 423 424 425 426 427 428 429
  {
    StopWatchNano timer(env_, statistics_ != nullptr);
    PERF_TIMER_GUARD(merge_operator_time_nanos);
    // we either exhausted all internal keys under this user key, or hit
    // a deletion marker.
    // feed null as the existing value to the merge operator, such that
    // client can differentiate this scenario and do things accordingly.
    user_merge_operator_->FullMerge(saved_key_.GetKey(), nullptr, operands,
                                    &saved_value_, logger_);
    RecordTick(statistics_, MERGE_OPERATION_TOTAL_TIME, timer.ElapsedNanos());
  }
430 431
}

J
jorlow@chromium.org 已提交
432 433
void DBIter::Prev() {
  assert(valid_);
S
Stanislau Hlebik 已提交
434
  if (direction_ == kForward) {
435
    ReverseToBackward();
S
Stanislau Hlebik 已提交
436 437
  }
  PrevInternal();
M
Manuel Ung 已提交
438 439 440 441 442 443 444
  if (statistics_ != nullptr) {
    RecordTick(statistics_, NUMBER_DB_PREV);
    if (valid_) {
      RecordTick(statistics_, NUMBER_DB_PREV_FOUND);
      RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
    }
  }
445 446
  if (valid_ && prefix_extractor_ && prefix_same_as_start_ &&
      prefix_extractor_->Transform(saved_key_.GetKey())
447
              .compare(prefix_start_.GetKey()) != 0) {
448 449
    valid_ = false;
  }
S
Stanislau Hlebik 已提交
450
}
J
jorlow@chromium.org 已提交
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
void DBIter::ReverseToBackward() {
  if (current_entry_is_merged_) {
    // Not placed in the same key. Need to call Prev() until finding the
    // previous key.
    if (!iter_->Valid()) {
      iter_->SeekToLast();
    }
    ParsedInternalKey ikey;
    FindParseableKey(&ikey, kReverse);
    while (iter_->Valid() &&
           user_comparator_->Compare(ikey.user_key, saved_key_.GetKey()) > 0) {
      iter_->Prev();
      FindParseableKey(&ikey, kReverse);
    }
  }
#ifndef NDEBUG
  if (iter_->Valid()) {
    ParsedInternalKey ikey;
    assert(ParseKey(&ikey));
    assert(user_comparator_->Compare(ikey.user_key, saved_key_.GetKey()) <= 0);
  }
#endif

  FindPrevUserKey();
  direction_ = kReverse;
}

S
Stanislau Hlebik 已提交
479 480 481 482
void DBIter::PrevInternal() {
  if (!iter_->Valid()) {
    valid_ = false;
    return;
483 484
  }

S
Stanislau Hlebik 已提交
485 486 487
  ParsedInternalKey ikey;

  while (iter_->Valid()) {
488 489
    saved_key_.SetKey(ExtractUserKey(iter_->key()),
                      !iter_->IsKeyPinned() /* copy */);
S
Stanislau Hlebik 已提交
490 491
    if (FindValueForCurrentKey()) {
      valid_ = true;
J
jorlow@chromium.org 已提交
492 493 494
      if (!iter_->Valid()) {
        return;
      }
S
Stanislau Hlebik 已提交
495
      FindParseableKey(&ikey, kReverse);
496
      if (user_comparator_->Equal(ikey.user_key, saved_key_.GetKey())) {
S
Stanislau Hlebik 已提交
497
        FindPrevUserKey();
J
jorlow@chromium.org 已提交
498
      }
S
Stanislau Hlebik 已提交
499
      return;
J
jorlow@chromium.org 已提交
500
    }
S
Stanislau Hlebik 已提交
501 502 503 504
    if (!iter_->Valid()) {
      break;
    }
    FindParseableKey(&ikey, kReverse);
505
    if (user_comparator_->Equal(ikey.user_key, saved_key_.GetKey())) {
S
Stanislau Hlebik 已提交
506 507 508 509 510 511
      FindPrevUserKey();
    }
  }
  // We haven't found any key - iterator is not valid
  assert(!iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
512 513
}

S
Stanislau Hlebik 已提交
514
// This function checks, if the entry with biggest sequence_number <= sequence_
A
Andres Noetzli 已提交
515 516
// is non kTypeDeletion or kTypeSingleDeletion. If it's not, we save value in
// saved_value_
S
Stanislau Hlebik 已提交
517 518
bool DBIter::FindValueForCurrentKey() {
  assert(iter_->Valid());
519
  merge_operands_.clear();
A
Andres Noetzli 已提交
520 521
  // last entry before merge (could be kTypeDeletion, kTypeSingleDeletion or
  // kTypeValue)
S
Stanislau Hlebik 已提交
522 523
  ValueType last_not_merge_type = kTypeDeletion;
  ValueType last_key_entry_type = kTypeDeletion;
J
jorlow@chromium.org 已提交
524

S
Stanislau Hlebik 已提交
525 526 527 528 529
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kReverse);

  size_t num_skipped = 0;
  while (iter_->Valid() && ikey.sequence <= sequence_ &&
530
         user_comparator_->Equal(ikey.user_key, saved_key_.GetKey())) {
S
Stanislau Hlebik 已提交
531 532 533 534 535 536 537 538
    // We iterate too much: let's use Seek() to avoid too much key comparisons
    if (num_skipped >= max_skip_) {
      return FindValueForCurrentKeyUsingSeek();
    }

    last_key_entry_type = ikey.type;
    switch (last_key_entry_type) {
      case kTypeValue:
539
        merge_operands_.clear();
S
Stanislau Hlebik 已提交
540 541 542 543
        saved_value_ = iter_->value().ToString();
        last_not_merge_type = kTypeValue;
        break;
      case kTypeDeletion:
A
Andres Noetzli 已提交
544
      case kTypeSingleDeletion:
545
        merge_operands_.clear();
A
Andres Noetzli 已提交
546
        last_not_merge_type = last_key_entry_type;
547
        PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
S
Stanislau Hlebik 已提交
548 549 550
        break;
      case kTypeMerge:
        assert(user_merge_operator_ != nullptr);
551
        merge_operands_.push_back(iter_->value().ToString());
S
Stanislau Hlebik 已提交
552 553 554 555 556
        break;
      default:
        assert(false);
    }

557
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
558
    assert(user_comparator_->Equal(ikey.user_key, saved_key_.GetKey()));
S
Stanislau Hlebik 已提交
559 560 561 562 563 564 565
    iter_->Prev();
    ++num_skipped;
    FindParseableKey(&ikey, kReverse);
  }

  switch (last_key_entry_type) {
    case kTypeDeletion:
A
Andres Noetzli 已提交
566
    case kTypeSingleDeletion:
S
Stanislau Hlebik 已提交
567 568 569 570
      valid_ = false;
      return false;
    case kTypeMerge:
      if (last_not_merge_type == kTypeDeletion) {
571 572
        StopWatchNano timer(env_, statistics_ != nullptr);
        PERF_TIMER_GUARD(merge_operator_time_nanos);
573 574 575
        user_merge_operator_->FullMerge(saved_key_.GetKey(), nullptr,
                                        merge_operands_, &saved_value_,
                                        logger_);
576 577
        RecordTick(statistics_, MERGE_OPERATION_TOTAL_TIME,
                   timer.ElapsedNanos());
578
      } else {
S
Stanislau Hlebik 已提交
579 580 581
        assert(last_not_merge_type == kTypeValue);
        std::string last_put_value = saved_value_;
        Slice temp_slice(last_put_value);
582 583 584 585
        {
          StopWatchNano timer(env_, statistics_ != nullptr);
          PERF_TIMER_GUARD(merge_operator_time_nanos);
          user_merge_operator_->FullMerge(saved_key_.GetKey(), &temp_slice,
586 587
                                          merge_operands_, &saved_value_,
                                          logger_);
588 589 590
          RecordTick(statistics_, MERGE_OPERATION_TOTAL_TIME,
                     timer.ElapsedNanos());
        }
591
      }
S
Stanislau Hlebik 已提交
592 593 594 595 596 597 598
      break;
    case kTypeValue:
      // do nothing - we've already has value in saved_value_
      break;
    default:
      assert(false);
      break;
J
jorlow@chromium.org 已提交
599
  }
S
Stanislau Hlebik 已提交
600 601 602
  valid_ = true;
  return true;
}
J
jorlow@chromium.org 已提交
603

S
Stanislau Hlebik 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616
// This function is used in FindValueForCurrentKey.
// We use Seek() function instead of Prev() to find necessary value
bool DBIter::FindValueForCurrentKeyUsingSeek() {
  std::string last_key;
  AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetKey(), sequence_,
                                                 kValueTypeForSeek));
  iter_->Seek(last_key);
  RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);

  // assume there is at least one parseable key for this user key
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kForward);

A
Andres Noetzli 已提交
617 618
  if (ikey.type == kTypeValue || ikey.type == kTypeDeletion ||
      ikey.type == kTypeSingleDeletion) {
S
Stanislau Hlebik 已提交
619 620 621 622 623
    if (ikey.type == kTypeValue) {
      saved_value_ = iter_->value().ToString();
      valid_ = true;
      return true;
    }
J
jorlow@chromium.org 已提交
624
    valid_ = false;
S
Stanislau Hlebik 已提交
625 626 627 628 629 630 631
    return false;
  }

  // kTypeMerge. We need to collect all kTypeMerge values and save them
  // in operands
  std::deque<std::string> operands;
  while (iter_->Valid() &&
632
         user_comparator_->Equal(ikey.user_key, saved_key_.GetKey()) &&
S
Stanislau Hlebik 已提交
633 634 635 636 637 638 639
         ikey.type == kTypeMerge) {
    operands.push_front(iter_->value().ToString());
    iter_->Next();
    FindParseableKey(&ikey, kForward);
  }

  if (!iter_->Valid() ||
640
      !user_comparator_->Equal(ikey.user_key, saved_key_.GetKey()) ||
A
Andres Noetzli 已提交
641
      ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion) {
642 643 644 645 646 647 648
    {
      StopWatchNano timer(env_, statistics_ != nullptr);
      PERF_TIMER_GUARD(merge_operator_time_nanos);
      user_merge_operator_->FullMerge(saved_key_.GetKey(), nullptr, operands,
                                      &saved_value_, logger_);
      RecordTick(statistics_, MERGE_OPERATION_TOTAL_TIME, timer.ElapsedNanos());
    }
S
Stanislau Hlebik 已提交
649 650
    // Make iter_ valid and point to saved_key_
    if (!iter_->Valid() ||
651
        !user_comparator_->Equal(ikey.user_key, saved_key_.GetKey())) {
S
Stanislau Hlebik 已提交
652 653 654
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    }
J
jorlow@chromium.org 已提交
655
    valid_ = true;
S
Stanislau Hlebik 已提交
656 657 658
    return true;
  }

I
Igor Canadi 已提交
659
  const Slice& val = iter_->value();
660 661 662 663 664 665 666
  {
    StopWatchNano timer(env_, statistics_ != nullptr);
    PERF_TIMER_GUARD(merge_operator_time_nanos);
    user_merge_operator_->FullMerge(saved_key_.GetKey(), &val, operands,
                                    &saved_value_, logger_);
    RecordTick(statistics_, MERGE_OPERATION_TOTAL_TIME, timer.ElapsedNanos());
  }
S
Stanislau Hlebik 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  valid_ = true;
  return true;
}

// Used in Next to change directions
// Go to next user key
// Don't use Seek(),
// because next user key will be very close
void DBIter::FindNextUserKey() {
  if (!iter_->Valid()) {
    return;
  }
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kForward);
  while (iter_->Valid() &&
682
         !user_comparator_->Equal(ikey.user_key, saved_key_.GetKey())) {
S
Stanislau Hlebik 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695
    iter_->Next();
    FindParseableKey(&ikey, kForward);
  }
}

// Go to previous user_key
void DBIter::FindPrevUserKey() {
  if (!iter_->Valid()) {
    return;
  }
  size_t num_skipped = 0;
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kReverse);
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
  int cmp;
  while (iter_->Valid() && ((cmp = user_comparator_->Compare(
                                 ikey.user_key, saved_key_.GetKey())) == 0 ||
                            (cmp > 0 && ikey.sequence > sequence_))) {
    if (cmp == 0) {
      if (num_skipped >= max_skip_) {
        num_skipped = 0;
        IterKey last_key;
        last_key.SetInternalKey(ParsedInternalKey(
            saved_key_.GetKey(), kMaxSequenceNumber, kValueTypeForSeek));
        iter_->Seek(last_key.GetKey());
        RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
      } else {
        ++num_skipped;
      }
S
Stanislau Hlebik 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724
    }
    iter_->Prev();
    FindParseableKey(&ikey, kReverse);
  }
}

// Skip all unparseable keys
void DBIter::FindParseableKey(ParsedInternalKey* ikey, Direction direction) {
  while (iter_->Valid() && !ParseKey(ikey)) {
    if (direction == kReverse) {
      iter_->Prev();
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
725 726
  }
}
J
jorlow@chromium.org 已提交
727

J
jorlow@chromium.org 已提交
728
void DBIter::Seek(const Slice& target) {
L
Lei Jin 已提交
729
  StopWatch sw(env_, statistics_, DB_SEEK);
730 731 732
  saved_key_.Clear();
  // now savved_key is used to store internal key.
  saved_key_.SetInternalKey(target, sequence_);
733 734 735 736 737 738

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->Seek(saved_key_.GetKey());
  }

M
Manuel Ung 已提交
739
  RecordTick(statistics_, NUMBER_DB_SEEK);
J
jorlow@chromium.org 已提交
740
  if (iter_->Valid()) {
741 742
    direction_ = kForward;
    ClearSavedValue();
743
    FindNextUserEntry(false /* not skipping */);
M
Manuel Ung 已提交
744 745 746 747 748 749
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
      }
    }
J
jorlow@chromium.org 已提交
750 751 752
  } else {
    valid_ = false;
  }
753
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
754
    prefix_start_.SetKey(prefix_extractor_->Transform(target));
755
  }
J
jorlow@chromium.org 已提交
756
}
J
jorlow@chromium.org 已提交
757

J
jorlow@chromium.org 已提交
758
void DBIter::SeekToFirst() {
S
Stanislau Hlebik 已提交
759
  // Don't use iter_::Seek() if we set a prefix extractor
760
  // because prefix seek will be used.
761
  if (prefix_extractor_ != nullptr) {
S
Stanislau Hlebik 已提交
762 763
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
J
jorlow@chromium.org 已提交
764 765
  direction_ = kForward;
  ClearSavedValue();
766 767 768 769 770 771

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->SeekToFirst();
  }

M
Manuel Ung 已提交
772
  RecordTick(statistics_, NUMBER_DB_SEEK);
J
jorlow@chromium.org 已提交
773
  if (iter_->Valid()) {
774
    FindNextUserEntry(false /* not skipping */);
M
Manuel Ung 已提交
775 776 777 778 779 780
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
      }
    }
J
jorlow@chromium.org 已提交
781 782
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
783
  }
784
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
785
    prefix_start_.SetKey(prefix_extractor_->Transform(saved_key_.GetKey()));
786
  }
J
jorlow@chromium.org 已提交
787 788
}

J
jorlow@chromium.org 已提交
789
void DBIter::SeekToLast() {
S
Stanislau Hlebik 已提交
790
  // Don't use iter_::Seek() if we set a prefix extractor
791
  // because prefix seek will be used.
792
  if (prefix_extractor_ != nullptr) {
S
Stanislau Hlebik 已提交
793 794
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
J
jorlow@chromium.org 已提交
795 796
  direction_ = kReverse;
  ClearSavedValue();
797 798 799 800 801

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->SeekToLast();
  }
802 803 804 805
  // When the iterate_upper_bound is set to a value,
  // it will seek to the last key before the
  // ReadOptions.iterate_upper_bound
  if (iter_->Valid() && iterate_upper_bound_ != nullptr) {
806
    saved_key_.SetKey(*iterate_upper_bound_, false /* copy */);
807 808 809 810 811 812
    std::string last_key;
    AppendInternalKey(&last_key,
                      ParsedInternalKey(saved_key_.GetKey(), kMaxSequenceNumber,
                                        kValueTypeForSeek));

    iter_->Seek(last_key);
S
Stanislau Hlebik 已提交
813

814 815 816 817 818 819 820 821 822 823
    if (!iter_->Valid()) {
      iter_->SeekToLast();
    } else {
      iter_->Prev();
      if (!iter_->Valid()) {
        valid_ = false;
        return;
      }
    }
  }
S
Stanislau Hlebik 已提交
824
  PrevInternal();
M
Manuel Ung 已提交
825 826 827 828 829 830 831
  if (statistics_ != nullptr) {
    RecordTick(statistics_, NUMBER_DB_SEEK);
    if (valid_) {
      RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
      RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
    }
  }
832
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
833
    prefix_start_.SetKey(prefix_extractor_->Transform(saved_key_.GetKey()));
834
  }
J
jorlow@chromium.org 已提交
835 836
}

837
Iterator* NewDBIterator(Env* env, const ImmutableCFOptions& ioptions,
838
                        const Comparator* user_key_comparator,
S
sdong 已提交
839
                        InternalIterator* internal_iter,
840
                        const SequenceNumber& sequence,
841
                        uint64_t max_sequential_skip_in_iterations,
842
                        uint64_t version_number,
843
                        const Slice* iterate_upper_bound,
844 845 846
                        bool prefix_same_as_start, bool pin_data) {
  DBIter* db_iter =
      new DBIter(env, ioptions, user_key_comparator, internal_iter, sequence,
847 848
                 false, max_sequential_skip_in_iterations, version_number,
                 iterate_upper_bound, prefix_same_as_start);
849 850 851 852
  if (pin_data) {
    db_iter->PinData();
  }
  return db_iter;
853 854
}

I
Igor Canadi 已提交
855
ArenaWrappedDBIter::~ArenaWrappedDBIter() { db_iter_->~DBIter(); }
856 857 858

void ArenaWrappedDBIter::SetDBIter(DBIter* iter) { db_iter_ = iter; }

S
sdong 已提交
859
void ArenaWrappedDBIter::SetIterUnderDBIter(InternalIterator* iter) {
860 861 862 863 864 865 866 867 868 869 870 871 872 873
  static_cast<DBIter*>(db_iter_)->SetIter(iter);
}

inline bool ArenaWrappedDBIter::Valid() const { return db_iter_->Valid(); }
inline void ArenaWrappedDBIter::SeekToFirst() { db_iter_->SeekToFirst(); }
inline void ArenaWrappedDBIter::SeekToLast() { db_iter_->SeekToLast(); }
inline void ArenaWrappedDBIter::Seek(const Slice& target) {
  db_iter_->Seek(target);
}
inline void ArenaWrappedDBIter::Next() { db_iter_->Next(); }
inline void ArenaWrappedDBIter::Prev() { db_iter_->Prev(); }
inline Slice ArenaWrappedDBIter::key() const { return db_iter_->key(); }
inline Slice ArenaWrappedDBIter::value() const { return db_iter_->value(); }
inline Status ArenaWrappedDBIter::status() const { return db_iter_->status(); }
874
inline Status ArenaWrappedDBIter::PinData() { return db_iter_->PinData(); }
875 876 877 878
inline Status ArenaWrappedDBIter::GetProperty(std::string prop_name,
                                              std::string* prop) {
  return db_iter_->GetProperty(prop_name, prop);
}
879 880 881
inline Status ArenaWrappedDBIter::ReleasePinnedData() {
  return db_iter_->ReleasePinnedData();
}
882 883 884 885
void ArenaWrappedDBIter::RegisterCleanup(CleanupFunction function, void* arg1,
                                         void* arg2) {
  db_iter_->RegisterCleanup(function, arg1, arg2);
}
J
jorlow@chromium.org 已提交
886

887
ArenaWrappedDBIter* NewArenaWrappedDbIterator(
888
    Env* env, const ImmutableCFOptions& ioptions,
889
    const Comparator* user_key_comparator, const SequenceNumber& sequence,
890
    uint64_t max_sequential_skip_in_iterations, uint64_t version_number,
891 892
    const Slice* iterate_upper_bound, bool prefix_same_as_start,
    bool pin_data) {
893 894 895
  ArenaWrappedDBIter* iter = new ArenaWrappedDBIter();
  Arena* arena = iter->GetArena();
  auto mem = arena->AllocateAligned(sizeof(DBIter));
896 897
  DBIter* db_iter =
      new (mem) DBIter(env, ioptions, user_key_comparator, nullptr, sequence,
898
                       true, max_sequential_skip_in_iterations, version_number,
899
                       iterate_upper_bound, prefix_same_as_start);
900

901
  iter->SetDBIter(db_iter);
902 903 904
  if (pin_data) {
    iter->PinData();
  }
905

906
  return iter;
J
jorlow@chromium.org 已提交
907 908
}

909
}  // namespace rocksdb