db_iter.cc 46.3 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5
//
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"
S
Stanislau Hlebik 已提交
11
#include <string>
S
Stanislau Hlebik 已提交
12
#include <limits>
J
jorlow@chromium.org 已提交
13 14

#include "db/dbformat.h"
15
#include "db/merge_context.h"
16
#include "db/merge_helper.h"
17
#include "db/pinned_iterators_manager.h"
18
#include "monitoring/perf_context_imp.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"
25
#include "util/filename.h"
J
jorlow@chromium.org 已提交
26 27
#include "util/logging.h"
#include "util/mutexlock.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

#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.
S
Siying Dong 已提交
50
class DBIter final: public Iterator {
J
jorlow@chromium.org 已提交
51
 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
  };

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  // LocalStatistics contain Statistics counters that will be aggregated per
  // each iterator instance and then will be sent to the global statistics when
  // the iterator is destroyed.
  //
  // The purpose of this approach is to avoid perf regression happening
  // when multiple threads bump the atomic counters from a DBIter::Next().
  struct LocalStatistics {
    explicit LocalStatistics() { ResetCounters(); }

    void ResetCounters() {
      next_count_ = 0;
      next_found_count_ = 0;
      prev_count_ = 0;
      prev_found_count_ = 0;
      bytes_read_ = 0;
    }

    void BumpGlobalStatistics(Statistics* global_statistics) {
      RecordTick(global_statistics, NUMBER_DB_NEXT, next_count_);
      RecordTick(global_statistics, NUMBER_DB_NEXT_FOUND, next_found_count_);
      RecordTick(global_statistics, NUMBER_DB_PREV, prev_count_);
      RecordTick(global_statistics, NUMBER_DB_PREV_FOUND, prev_found_count_);
      RecordTick(global_statistics, ITER_BYTES_READ, bytes_read_);
86
      PERF_COUNTER_ADD(iter_read_bytes, bytes_read_);
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      ResetCounters();
    }

    // Map to Tickers::NUMBER_DB_NEXT
    uint64_t next_count_;
    // Map to Tickers::NUMBER_DB_NEXT_FOUND
    uint64_t next_found_count_;
    // Map to Tickers::NUMBER_DB_PREV
    uint64_t prev_count_;
    // Map to Tickers::NUMBER_DB_PREV_FOUND
    uint64_t prev_found_count_;
    // Map to Tickers::ITER_BYTES_READ
    uint64_t bytes_read_;
  };

S
Siying Dong 已提交
102
  DBIter(Env* _env, const ReadOptions& read_options,
103
         const ImmutableCFOptions& cf_options, const Comparator* cmp,
S
sdong 已提交
104
         InternalIterator* iter, SequenceNumber s, bool arena_mode,
Y
Yi Wu 已提交
105 106
         uint64_t max_sequential_skip_in_iterations,
         ReadCallback* read_callback, bool allow_blob)
107
      : arena_mode_(arena_mode),
S
Siying Dong 已提交
108
        env_(_env),
109
        logger_(cf_options.info_log),
J
jorlow@chromium.org 已提交
110
        user_comparator_(cmp),
111
        merge_operator_(cf_options.merge_operator),
J
jorlow@chromium.org 已提交
112 113
        iter_(iter),
        sequence_(s),
J
jorlow@chromium.org 已提交
114
        direction_(kForward),
115
        valid_(false),
116
        current_entry_is_merged_(false),
117
        statistics_(cf_options.statistics),
118
        iterate_lower_bound_(read_options.iterate_lower_bound),
119 120 121 122 123
        iterate_upper_bound_(read_options.iterate_upper_bound),
        prefix_same_as_start_(read_options.prefix_same_as_start),
        pin_thru_lifetime_(read_options.pin_data),
        total_order_seek_(read_options.total_order_seek),
        range_del_agg_(cf_options.internal_comparator, s,
Y
Yi Wu 已提交
124
                       true /* collapse_deletions */),
Y
Yi Wu 已提交
125
        read_callback_(read_callback),
Y
Yi Wu 已提交
126
        allow_blob_(allow_blob) {
L
Lei Jin 已提交
127
    RecordTick(statistics_, NO_ITERATORS);
128
    prefix_extractor_ = cf_options.prefix_extractor;
129
    max_skip_ = max_sequential_skip_in_iterations;
130
    max_skippable_internal_keys_ = read_options.max_skippable_internal_keys;
131 132 133 134 135 136
    if (pin_thru_lifetime_) {
      pinned_iters_mgr_.StartPinning();
    }
    if (iter_) {
      iter_->SetPinnedItersMgr(&pinned_iters_mgr_);
    }
J
jorlow@chromium.org 已提交
137 138
  }
  virtual ~DBIter() {
139
    // Release pinned data if any
140 141 142
    if (pinned_iters_mgr_.PinningEnabled()) {
      pinned_iters_mgr_.ReleasePinnedData();
    }
143 144 145
    // Compiler warning issue filed:
    // https://github.com/facebook/rocksdb/issues/3013
    RecordTick(statistics_, NO_ITERATORS, uint64_t(-1));
146
    local_stats_.BumpGlobalStatistics(statistics_);
147 148 149
    if (!arena_mode_) {
      delete iter_;
    } else {
S
sdong 已提交
150
      iter_->~InternalIterator();
151 152
    }
  }
S
sdong 已提交
153
  virtual void SetIter(InternalIterator* iter) {
154 155
    assert(iter_ == nullptr);
    iter_ = iter;
156
    iter_->SetPinnedItersMgr(&pinned_iters_mgr_);
J
jorlow@chromium.org 已提交
157
  }
A
Andrew Kryczka 已提交
158 159 160 161
  virtual RangeDelAggregator* GetRangeDelAggregator() {
    return &range_del_agg_;
  }

I
Igor Sugak 已提交
162 163
  virtual bool Valid() const override { return valid_; }
  virtual Slice key() const override {
J
jorlow@chromium.org 已提交
164
    assert(valid_);
165
    return saved_key_.GetUserKey();
J
jorlow@chromium.org 已提交
166
  }
I
Igor Sugak 已提交
167
  virtual Slice value() const override {
J
jorlow@chromium.org 已提交
168
    assert(valid_);
169
    if (current_entry_is_merged_) {
170 171 172
      // If pinned_value_ is set then the result of merge operator is one of
      // the merge operands and we should return it.
      return pinned_value_.data() ? pinned_value_ : saved_value_;
173 174 175 176 177
    } else if (direction_ == kReverse) {
      return pinned_value_;
    } else {
      return iter_->value();
    }
J
jorlow@chromium.org 已提交
178
  }
I
Igor Sugak 已提交
179
  virtual Status status() const override {
J
jorlow@chromium.org 已提交
180 181 182 183 184 185
    if (status_.ok()) {
      return iter_->status();
    } else {
      return status_;
    }
  }
Y
Yi Wu 已提交
186 187 188 189
  bool IsBlob() const {
    assert(valid_ && (allow_blob_ || !is_blob_));
    return is_blob_;
  }
190 191 192 193 194 195

  virtual Status GetProperty(std::string prop_name,
                             std::string* prop) override {
    if (prop == nullptr) {
      return Status::InvalidArgument("prop is nullptr");
    }
196
    if (prop_name == "rocksdb.iterator.super-version-number") {
197
      // First try to pass the value returned from inner iterator.
S
Siying Dong 已提交
198
      return iter_->GetProperty(prop_name, prop);
199
    } else if (prop_name == "rocksdb.iterator.is-key-pinned") {
200
      if (valid_) {
201
        *prop = (pin_thru_lifetime_ && saved_key_.IsKeyPinned()) ? "1" : "0";
202 203 204 205 206 207
      } else {
        *prop = "Iterator is not valid.";
      }
      return Status::OK();
    }
    return Status::InvalidArgument("Undentified property.");
208
  }
J
jorlow@chromium.org 已提交
209

I
Igor Sugak 已提交
210 211 212
  virtual void Next() override;
  virtual void Prev() override;
  virtual void Seek(const Slice& target) override;
A
Aaron Gao 已提交
213
  virtual void SeekForPrev(const Slice& target) override;
I
Igor Sugak 已提交
214 215
  virtual void SeekToFirst() override;
  virtual void SeekToLast() override;
S
Siying Dong 已提交
216 217 218
  Env* env() { return env_; }
  void set_sequence(uint64_t s) { sequence_ = s; }
  void set_valid(bool v) { valid_ = v; }
J
jorlow@chromium.org 已提交
219

J
jorlow@chromium.org 已提交
220
 private:
221
  void ReverseToForward();
222
  void ReverseToBackward();
S
Stanislau Hlebik 已提交
223 224 225 226 227 228
  void PrevInternal();
  void FindParseableKey(ParsedInternalKey* ikey, Direction direction);
  bool FindValueForCurrentKey();
  bool FindValueForCurrentKeyUsingSeek();
  void FindPrevUserKey();
  void FindNextUserKey();
229 230
  inline void FindNextUserEntry(bool skipping, bool prefix_check);
  void FindNextUserEntryInternal(bool skipping, bool prefix_check);
J
jorlow@chromium.org 已提交
231
  bool ParseKey(ParsedInternalKey* key);
232
  void MergeValuesNewToOld();
233
  bool TooManyInternalKeysSkipped(bool increment = true);
Y
Yi Wu 已提交
234
  bool IsVisible(SequenceNumber sequence);
J
jorlow@chromium.org 已提交
235

236 237 238 239 240 241 242 243 244 245
  // Temporarily pin the blocks that we encounter until ReleaseTempPinnedData()
  // is called
  void TempPinData() {
    if (!pin_thru_lifetime_) {
      pinned_iters_mgr_.StartPinning();
    }
  }

  // Release blocks pinned by TempPinData()
  void ReleaseTempPinnedData() {
246 247
    if (!pin_thru_lifetime_ && pinned_iters_mgr_.PinningEnabled()) {
      pinned_iters_mgr_.ReleasePinnedData();
248 249 250
    }
  }

J
jorlow@chromium.org 已提交
251 252 253 254 255 256 257 258 259
  inline void ClearSavedValue() {
    if (saved_value_.capacity() > 1048576) {
      std::string empty;
      swap(empty, saved_value_);
    } else {
      saved_value_.clear();
    }
  }

260 261 262 263
  inline void ResetInternalKeysSkippedCounter() {
    num_internal_keys_skipped_ = 0;
  }

264
  const SliceTransform* prefix_extractor_;
265
  bool arena_mode_;
J
jorlow@chromium.org 已提交
266
  Env* const env_;
I
Igor Canadi 已提交
267
  Logger* logger_;
J
jorlow@chromium.org 已提交
268
  const Comparator* const user_comparator_;
269
  const MergeOperator* const merge_operator_;
S
sdong 已提交
270
  InternalIterator* iter_;
S
Siying Dong 已提交
271
  SequenceNumber sequence_;
J
jorlow@chromium.org 已提交
272

J
jorlow@chromium.org 已提交
273
  Status status_;
S
Stanislau Hlebik 已提交
274
  IterKey saved_key_;
275 276 277 278
  // Reusable internal key data structure. This is only used inside one function
  // and should not be used across functions. Reusing this object can reduce
  // overhead of calling construction of the function if creating it each time.
  ParsedInternalKey ikey_;
S
Stanislau Hlebik 已提交
279
  std::string saved_value_;
280
  Slice pinned_value_;
J
jorlow@chromium.org 已提交
281
  Direction direction_;
J
jorlow@chromium.org 已提交
282
  bool valid_;
283
  bool current_entry_is_merged_;
284
  // for prefix seek mode to support prev()
285
  Statistics* statistics_;
286
  uint64_t max_skip_;
287 288
  uint64_t max_skippable_internal_keys_;
  uint64_t num_internal_keys_skipped_;
289
  const Slice* iterate_lower_bound_;
290
  const Slice* iterate_upper_bound_;
291 292 293
  IterKey prefix_start_buf_;
  Slice prefix_start_key_;
  const bool prefix_same_as_start_;
294 295 296
  // Means that we will pin all data blocks we read as long the Iterator
  // is not deleted, will be true if ReadOptions::pin_data is true
  const bool pin_thru_lifetime_;
297
  const bool total_order_seek_;
298
  // List of operands for merge operator.
299
  MergeContext merge_context_;
A
Andrew Kryczka 已提交
300
  RangeDelAggregator range_del_agg_;
301
  LocalStatistics local_stats_;
302
  PinnedIteratorsManager pinned_iters_mgr_;
Y
Yi Wu 已提交
303
  ReadCallback* read_callback_;
Y
Yi Wu 已提交
304 305
  bool allow_blob_;
  bool is_blob_;
J
jorlow@chromium.org 已提交
306 307 308 309 310 311 312 313 314

  // 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");
315 316
    ROCKS_LOG_ERROR(logger_, "corrupted internal key in DBIter: %s",
                    iter_->key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
317 318 319 320 321 322
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
323 324 325
void DBIter::Next() {
  assert(valid_);

326 327
  // Release temporarily pinned blocks from last operation
  ReleaseTempPinnedData();
328
  ResetInternalKeysSkippedCounter();
S
Stanislau Hlebik 已提交
329
  if (direction_ == kReverse) {
330
    ReverseToForward();
331 332 333 334 335 336 337
  } 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();
338
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
J
jorlow@chromium.org 已提交
339
  }
J
jorlow@chromium.org 已提交
340

341 342 343
  if (statistics_ != nullptr) {
    local_stats_.next_count_++;
  }
344 345
  // Now we point to the next internal position, for both of merge and
  // not merge cases.
346 347 348 349
  if (!iter_->Valid()) {
    valid_ = false;
    return;
  }
350
  FindNextUserEntry(true /* skipping the current user key */, prefix_same_as_start_);
351 352 353 354
  if (statistics_ != nullptr && valid_) {
    local_stats_.next_found_count_++;
    local_stats_.bytes_read_ += (key().size() + value().size());
  }
J
jorlow@chromium.org 已提交
355 356
}

357 358 359 360 361 362 363
// 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
364
//       a delete marker or a sequence number higher than sequence_
365
//       saved_key_ MUST have a proper user_key before calling this function
366 367 368 369 370 371
//
// The prefix_check parameter controls whether we check the iterated
// keys against the prefix of the seeked key. Set to false when
// performing a seek without a key (e.g. SeekToFirst). Set to
// prefix_same_as_start_ for other iterations.
inline void DBIter::FindNextUserEntry(bool skipping, bool prefix_check) {
372
  PERF_TIMER_GUARD(find_next_user_entry_time);
373
  FindNextUserEntryInternal(skipping, prefix_check);
374 375 376
}

// Actual implementation of DBIter::FindNextUserEntry()
377
void DBIter::FindNextUserEntryInternal(bool skipping, bool prefix_check) {
J
jorlow@chromium.org 已提交
378 379 380
  // Loop until we hit an acceptable entry to yield
  assert(iter_->Valid());
  assert(direction_ == kForward);
381
  current_entry_is_merged_ = false;
382 383 384 385 386 387 388 389 390 391 392

  // How many times in a row we have skipped an entry with user key less than
  // or equal to saved_key_. We could skip these entries either because
  // sequence numbers were too high or because skipping = true.
  // What saved_key_ contains throughout this method:
  //  - if skipping        : saved_key_ contains the key that we need to skip,
  //                         and we haven't seen any keys greater than that,
  //  - if num_skipped > 0 : saved_key_ contains the key that we have skipped
  //                         num_skipped times, and we haven't seen any keys
  //                         greater than that,
  //  - none of the above  : saved_key_ can contain anything, it doesn't matter.
393
  uint64_t num_skipped = 0;
394

Y
Yi Wu 已提交
395 396
  is_blob_ = false;

J
jorlow@chromium.org 已提交
397
  do {
398
    if (!ParseKey(&ikey_)) {
399 400 401 402
      // Skip corrupted keys.
      iter_->Next();
      continue;
    }
403

404
    if (iterate_upper_bound_ != nullptr &&
405
        user_comparator_->Compare(ikey_.user_key, *iterate_upper_bound_) >= 0) {
406 407
      break;
    }
408

409
    if (prefix_extractor_ && prefix_check &&
410 411
        prefix_extractor_->Transform(ikey_.user_key)
                .compare(prefix_start_key_) != 0) {
412 413 414
      break;
    }

415 416 417 418
    if (TooManyInternalKeysSkipped()) {
      return;
    }

Y
Yi Wu 已提交
419
    if (IsVisible(ikey_.sequence)) {
420 421
      if (skipping && user_comparator_->Compare(ikey_.user_key,
                                                saved_key_.GetUserKey()) <= 0) {
422 423 424 425
        num_skipped++;  // skip this entry
        PERF_COUNTER_ADD(internal_key_skipped_count, 1);
      } else {
        num_skipped = 0;
426
        switch (ikey_.type) {
427 428 429 430
          case kTypeDeletion:
          case kTypeSingleDeletion:
            // Arrange to skip all upcoming entries for this key since
            // they are hidden by this deletion.
431
            saved_key_.SetUserKey(
432 433
                ikey_.user_key,
                !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
434 435 436 437
            skipping = true;
            PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
            break;
          case kTypeValue:
Y
Yi Wu 已提交
438
          case kTypeBlobIndex:
439
            saved_key_.SetUserKey(
440 441
                ikey_.user_key,
                !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
442
            if (range_del_agg_.ShouldDelete(
443 444
                    ikey_, RangeDelAggregator::RangePositioningMode::
                               kForwardTraversal)) {
445 446 447 448 449
              // Arrange to skip all upcoming entries for this key since
              // they are hidden by this deletion.
              skipping = true;
              num_skipped = 0;
              PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
Y
Yi Wu 已提交
450 451 452 453 454 455 456 457 458 459 460 461
            } else if (ikey_.type == kTypeBlobIndex) {
              if (!allow_blob_) {
                ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
                status_ = Status::NotSupported(
                    "Encounter unexpected blob index. Please open DB with "
                    "rocksdb::blob_db::BlobDB instead.");
                valid_ = false;
              } else {
                is_blob_ = true;
                valid_ = true;
              }
              return;
462 463 464 465 466 467
            } else {
              valid_ = true;
              return;
            }
            break;
          case kTypeMerge:
468
            saved_key_.SetUserKey(
469 470
                ikey_.user_key,
                !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
471
            if (range_del_agg_.ShouldDelete(
472 473
                    ikey_, RangeDelAggregator::RangePositioningMode::
                               kForwardTraversal)) {
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
              // Arrange to skip all upcoming entries for this key since
              // they are hidden by this deletion.
              skipping = true;
              num_skipped = 0;
              PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
            } else {
              // By now, we are sure the current ikey is going to yield a
              // value
              current_entry_is_merged_ = true;
              valid_ = true;
              MergeValuesNewToOld();  // Go to a different state machine
              return;
            }
            break;
          default:
            assert(false);
            break;
491
        }
J
jorlow@chromium.org 已提交
492
      }
493 494 495 496 497 498
    } else {
      // This key was inserted after our snapshot was taken.
      PERF_COUNTER_ADD(internal_recent_skipped_count, 1);

      // Here saved_key_ may contain some old key, or the default empty key, or
      // key assigned by some random other method. We don't care.
499
      if (user_comparator_->Compare(ikey_.user_key, saved_key_.GetUserKey()) <=
500
          0) {
501 502
        num_skipped++;
      } else {
503
        saved_key_.SetUserKey(
504
            ikey_.user_key,
505
            !iter_->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
506 507 508
        skipping = false;
        num_skipped = 0;
      }
J
jorlow@chromium.org 已提交
509
    }
510 511 512 513

    // If we have sequentially iterated via numerous equal keys, then it's
    // better to seek so that we can avoid too many key comparisons.
    if (num_skipped > max_skip_) {
514 515
      num_skipped = 0;
      std::string last_key;
516 517 518 519
      if (skipping) {
        // We're looking for the next user-key but all we see are the same
        // user-key with decreasing sequence numbers. Fast forward to
        // sequence number 0 and type deletion (the smallest type).
520 521
        AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetUserKey(),
                                                       0, kTypeDeletion));
522 523 524 525 526 527 528 529 530
        // Don't set skipping = false because we may still see more user-keys
        // equal to saved_key_.
      } else {
        // We saw multiple entries with this user key and sequence numbers
        // higher than sequence_. Fast forward to sequence_.
        // Note that this only covers a case when a higher key was overwritten
        // many times since our snapshot was taken, not the case when a lot of
        // different keys were inserted after our snapshot was taken.
        AppendInternalKey(&last_key,
531
                          ParsedInternalKey(saved_key_.GetUserKey(), sequence_,
532 533
                                            kValueTypeForSeek));
      }
534 535 536 537 538
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
539 540
  } while (iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
541 542
}

543 544 545 546 547 548 549
// 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() {
550
  if (!merge_operator_) {
551
    ROCKS_LOG_ERROR(logger_, "Options::merge_operator is null.");
552
    status_ = Status::InvalidArgument("merge_operator_ must be set.");
553 554
    valid_ = false;
    return;
D
Deon Nicholas 已提交
555
  }
556

557 558
  // Temporarily pin the blocks that hold merge operands
  TempPinData();
559
  merge_context_.Clear();
560
  // Start the merge process by pushing the first operand
561 562
  merge_context_.PushOperand(iter_->value(),
                             iter_->IsValuePinned() /* operand_pinned */);
563 564

  ParsedInternalKey ikey;
565
  Status s;
566 567 568 569 570 571
  for (iter_->Next(); iter_->Valid(); iter_->Next()) {
    if (!ParseKey(&ikey)) {
      // skip corrupted key
      continue;
    }

572
    if (!user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
573 574
      // hit the next user key, stop right here
      break;
A
Andrew Kryczka 已提交
575
    } else if (kTypeDeletion == ikey.type || kTypeSingleDeletion == ikey.type ||
576 577 578
               range_del_agg_.ShouldDelete(
                   ikey, RangeDelAggregator::RangePositioningMode::
                             kForwardTraversal)) {
579 580 581 582
      // hit a delete with the same user key, stop right here
      // iter_ is positioned after delete
      iter_->Next();
      break;
A
Andres Noetzli 已提交
583
    } else if (kTypeValue == ikey.type) {
584 585 586
      // 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 已提交
587
      const Slice val = iter_->value();
588 589
      s = MergeHelper::TimedFullMerge(
          merge_operator_, ikey.user_key, &val, merge_context_.GetOperands(),
590
          &saved_value_, logger_, statistics_, env_, &pinned_value_, true);
591 592 593
      if (!s.ok()) {
        status_ = s;
      }
594 595 596
      // iter_ is positioned after put
      iter_->Next();
      return;
A
Andres Noetzli 已提交
597
    } else if (kTypeMerge == ikey.type) {
598 599
      // hit a merge, add the value as an operand and run associative merge.
      // when complete, add result to operands and continue.
600 601
      merge_context_.PushOperand(iter_->value(),
                                 iter_->IsValuePinned() /* operand_pinned */);
602
      PERF_COUNTER_ADD(internal_merge_count, 1);
Y
Yi Wu 已提交
603 604 605 606 607 608 609 610 611 612 613 614
    } else if (kTypeBlobIndex == ikey.type) {
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
      } else {
        status_ =
            Status::NotSupported("Blob DB does not support merge operator.");
      }
      valid_ = false;
      return;
A
Andres Noetzli 已提交
615 616
    } else {
      assert(false);
617 618 619
    }
  }

620 621 622 623
  // 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.
624 625 626
  s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
                                  nullptr, merge_context_.GetOperands(),
                                  &saved_value_, logger_, statistics_, env_,
627
                                  &pinned_value_, true);
628 629 630
  if (!s.ok()) {
    status_ = s;
  }
631 632
}

J
jorlow@chromium.org 已提交
633 634
void DBIter::Prev() {
  assert(valid_);
635
  ReleaseTempPinnedData();
636
  ResetInternalKeysSkippedCounter();
S
Stanislau Hlebik 已提交
637
  if (direction_ == kForward) {
638
    ReverseToBackward();
S
Stanislau Hlebik 已提交
639 640
  }
  PrevInternal();
M
Manuel Ung 已提交
641
  if (statistics_ != nullptr) {
642
    local_stats_.prev_count_++;
M
Manuel Ung 已提交
643
    if (valid_) {
644 645
      local_stats_.prev_found_count_++;
      local_stats_.bytes_read_ += (key().size() + value().size());
M
Manuel Ung 已提交
646 647
    }
  }
S
Stanislau Hlebik 已提交
648
}
J
jorlow@chromium.org 已提交
649

650 651 652 653
void DBIter::ReverseToForward() {
  if (prefix_extractor_ != nullptr && !total_order_seek_) {
    IterKey last_key;
    last_key.SetInternalKey(ParsedInternalKey(
654 655
        saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
    iter_->Seek(last_key.GetInternalKey());
656 657 658 659 660
  }
  FindNextUserKey();
  direction_ = kForward;
  if (!iter_->Valid()) {
    iter_->SeekToFirst();
661
    range_del_agg_.InvalidateTombstoneMapPositions();
662 663 664
  }
}

665
void DBIter::ReverseToBackward() {
666 667
  if (prefix_extractor_ != nullptr && !total_order_seek_) {
    IterKey last_key;
668 669 670
    last_key.SetInternalKey(ParsedInternalKey(saved_key_.GetUserKey(), 0,
                                              kValueTypeForSeekForPrev));
    iter_->SeekForPrev(last_key.GetInternalKey());
671
  }
672 673 674 675 676
  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();
677
      range_del_agg_.InvalidateTombstoneMapPositions();
678 679 680 681
    }
    ParsedInternalKey ikey;
    FindParseableKey(&ikey, kReverse);
    while (iter_->Valid() &&
682 683
           user_comparator_->Compare(ikey.user_key, saved_key_.GetUserKey()) >
               0) {
S
Siying Dong 已提交
684
      assert(ikey.sequence != kMaxSequenceNumber);
Y
Yi Wu 已提交
685
      if (!IsVisible(ikey.sequence)) {
686 687 688 689
        PERF_COUNTER_ADD(internal_recent_skipped_count, 1);
      } else {
        PERF_COUNTER_ADD(internal_key_skipped_count, 1);
      }
690 691 692 693 694 695 696 697
      iter_->Prev();
      FindParseableKey(&ikey, kReverse);
    }
  }
#ifndef NDEBUG
  if (iter_->Valid()) {
    ParsedInternalKey ikey;
    assert(ParseKey(&ikey));
698 699
    assert(user_comparator_->Compare(ikey.user_key, saved_key_.GetUserKey()) <=
           0);
700 701 702 703 704 705 706
  }
#endif

  FindPrevUserKey();
  direction_ = kReverse;
}

S
Stanislau Hlebik 已提交
707 708 709 710
void DBIter::PrevInternal() {
  if (!iter_->Valid()) {
    valid_ = false;
    return;
711 712
  }

S
Stanislau Hlebik 已提交
713 714 715
  ParsedInternalKey ikey;

  while (iter_->Valid()) {
716 717 718
    saved_key_.SetUserKey(
        ExtractUserKey(iter_->key()),
        !iter_->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
719

720 721 722 723 724 725 726 727
    if (prefix_extractor_ && prefix_same_as_start_ &&
        prefix_extractor_->Transform(saved_key_.GetUserKey())
                .compare(prefix_start_key_) != 0) {
      // Current key does not have the same prefix as start
      valid_ = false;
      return;
    }

728 729 730 731 732 733 734 735
    if (iterate_lower_bound_ != nullptr &&
        user_comparator_->Compare(saved_key_.GetUserKey(),
                                  *iterate_lower_bound_) < 0) {
      // We've iterated earlier than the user-specified lower bound.
      valid_ = false;
      return;
    }

S
Stanislau Hlebik 已提交
736
    if (FindValueForCurrentKey()) {
J
jorlow@chromium.org 已提交
737 738 739
      if (!iter_->Valid()) {
        return;
      }
S
Stanislau Hlebik 已提交
740
      FindParseableKey(&ikey, kReverse);
741
      if (user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
742
        FindPrevUserKey();
J
jorlow@chromium.org 已提交
743
      }
S
Stanislau Hlebik 已提交
744
      return;
J
jorlow@chromium.org 已提交
745
    }
746 747 748 749 750

    if (TooManyInternalKeysSkipped(false)) {
      return;
    }

S
Stanislau Hlebik 已提交
751 752 753 754
    if (!iter_->Valid()) {
      break;
    }
    FindParseableKey(&ikey, kReverse);
755
    if (user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
756 757 758 759
      FindPrevUserKey();
    }
  }
  // We haven't found any key - iterator is not valid
A
Aaron Gao 已提交
760
  // Or the prefix is different than start prefix
761
  assert(!iter_->Valid());
S
Stanislau Hlebik 已提交
762
  valid_ = false;
J
jorlow@chromium.org 已提交
763 764
}

S
Stanislau Hlebik 已提交
765
// This function checks, if the entry with biggest sequence_number <= sequence_
A
Andres Noetzli 已提交
766 767
// is non kTypeDeletion or kTypeSingleDeletion. If it's not, we save value in
// saved_value_
S
Stanislau Hlebik 已提交
768 769
bool DBIter::FindValueForCurrentKey() {
  assert(iter_->Valid());
770
  merge_context_.Clear();
771
  current_entry_is_merged_ = false;
A
Andres Noetzli 已提交
772 773
  // last entry before merge (could be kTypeDeletion, kTypeSingleDeletion or
  // kTypeValue)
S
Stanislau Hlebik 已提交
774 775
  ValueType last_not_merge_type = kTypeDeletion;
  ValueType last_key_entry_type = kTypeDeletion;
J
jorlow@chromium.org 已提交
776

S
Stanislau Hlebik 已提交
777 778 779
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kReverse);

780 781 782
  // Temporarily pin blocks that hold (merge operands / the value)
  ReleaseTempPinnedData();
  TempPinData();
S
Stanislau Hlebik 已提交
783
  size_t num_skipped = 0;
Y
Yi Wu 已提交
784
  while (iter_->Valid() && IsVisible(ikey.sequence) &&
785
         user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
786 787 788 789
    if (TooManyInternalKeysSkipped()) {
      return false;
    }

S
Stanislau Hlebik 已提交
790 791 792 793 794 795 796 797
    // 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:
Y
Yi Wu 已提交
798
      case kTypeBlobIndex:
799 800 801
        if (range_del_agg_.ShouldDelete(
                ikey,
                RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
A
Andrew Kryczka 已提交
802 803 804 805 806 807
          last_key_entry_type = kTypeRangeDeletion;
          PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
        } else {
          assert(iter_->IsValuePinned());
          pinned_value_ = iter_->value();
        }
808
        merge_context_.Clear();
A
Andrew Kryczka 已提交
809
        last_not_merge_type = last_key_entry_type;
S
Stanislau Hlebik 已提交
810 811
        break;
      case kTypeDeletion:
A
Andres Noetzli 已提交
812
      case kTypeSingleDeletion:
813
        merge_context_.Clear();
A
Andres Noetzli 已提交
814
        last_not_merge_type = last_key_entry_type;
815
        PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
S
Stanislau Hlebik 已提交
816 817
        break;
      case kTypeMerge:
818 819 820
        if (range_del_agg_.ShouldDelete(
                ikey,
                RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
A
Andrew Kryczka 已提交
821 822 823 824 825 826 827 828
          merge_context_.Clear();
          last_key_entry_type = kTypeRangeDeletion;
          last_not_merge_type = last_key_entry_type;
          PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
        } else {
          assert(merge_operator_ != nullptr);
          merge_context_.PushOperandBack(
              iter_->value(), iter_->IsValuePinned() /* operand_pinned */);
829
          PERF_COUNTER_ADD(internal_merge_count, 1);
A
Andrew Kryczka 已提交
830
        }
S
Stanislau Hlebik 已提交
831 832 833 834 835
        break;
      default:
        assert(false);
    }

836
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
837
    assert(user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()));
S
Stanislau Hlebik 已提交
838 839 840 841 842
    iter_->Prev();
    ++num_skipped;
    FindParseableKey(&ikey, kReverse);
  }

843
  Status s;
Y
Yi Wu 已提交
844
  is_blob_ = false;
S
Stanislau Hlebik 已提交
845 846
  switch (last_key_entry_type) {
    case kTypeDeletion:
A
Andres Noetzli 已提交
847
    case kTypeSingleDeletion:
A
Andrew Kryczka 已提交
848
    case kTypeRangeDeletion:
S
Stanislau Hlebik 已提交
849 850 851
      valid_ = false;
      return false;
    case kTypeMerge:
852
      current_entry_is_merged_ = true;
A
Aaron Gao 已提交
853
      if (last_not_merge_type == kTypeDeletion ||
A
Andrew Kryczka 已提交
854 855
          last_not_merge_type == kTypeSingleDeletion ||
          last_not_merge_type == kTypeRangeDeletion) {
856 857 858
        s = MergeHelper::TimedFullMerge(
            merge_operator_, saved_key_.GetUserKey(), nullptr,
            merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
859
            env_, &pinned_value_, true);
Y
Yi Wu 已提交
860 861 862 863 864 865 866 867 868 869 870 871
      } else if (last_not_merge_type == kTypeBlobIndex) {
        if (!allow_blob_) {
          ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
          status_ = Status::NotSupported(
              "Encounter unexpected blob index. Please open DB with "
              "rocksdb::blob_db::BlobDB instead.");
        } else {
          status_ =
              Status::NotSupported("Blob DB does not support merge operator.");
        }
        valid_ = false;
        return true;
872
      } else {
S
Stanislau Hlebik 已提交
873
        assert(last_not_merge_type == kTypeValue);
874
        s = MergeHelper::TimedFullMerge(
875
            merge_operator_, saved_key_.GetUserKey(), &pinned_value_,
876
            merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
877
            env_, &pinned_value_, true);
878
      }
S
Stanislau Hlebik 已提交
879 880 881 882
      break;
    case kTypeValue:
      // do nothing - we've already has value in saved_value_
      break;
Y
Yi Wu 已提交
883 884 885 886 887 888 889 890 891 892 893
    case kTypeBlobIndex:
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
        valid_ = false;
        return true;
      }
      is_blob_ = true;
      break;
S
Stanislau Hlebik 已提交
894 895 896
    default:
      assert(false);
      break;
J
jorlow@chromium.org 已提交
897
  }
S
Stanislau Hlebik 已提交
898
  valid_ = true;
899 900 901
  if (!s.ok()) {
    status_ = s;
  }
S
Stanislau Hlebik 已提交
902 903
  return true;
}
J
jorlow@chromium.org 已提交
904

S
Stanislau Hlebik 已提交
905 906 907
// This function is used in FindValueForCurrentKey.
// We use Seek() function instead of Prev() to find necessary value
bool DBIter::FindValueForCurrentKeyUsingSeek() {
908 909 910
  // FindValueForCurrentKey will enable pinning before calling
  // FindValueForCurrentKeyUsingSeek()
  assert(pinned_iters_mgr_.PinningEnabled());
S
Stanislau Hlebik 已提交
911
  std::string last_key;
912 913
  AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetUserKey(),
                                                 sequence_, kValueTypeForSeek));
S
Stanislau Hlebik 已提交
914 915 916 917 918 919 920
  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
Andrew Kryczka 已提交
921
  if (ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion ||
922 923
      range_del_agg_.ShouldDelete(
          ikey, RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
J
jorlow@chromium.org 已提交
924
    valid_ = false;
S
Stanislau Hlebik 已提交
925 926
    return false;
  }
Y
Yi Wu 已提交
927 928 929 930 931 932 933 934 935
  if (ikey.type == kTypeBlobIndex && !allow_blob_) {
    ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
    status_ = Status::NotSupported(
        "Encounter unexpected blob index. Please open DB with "
        "rocksdb::blob_db::BlobDB instead.");
    valid_ = false;
    return true;
  }
  if (ikey.type == kTypeValue || ikey.type == kTypeBlobIndex) {
A
Andrew Kryczka 已提交
936 937 938 939 940
    assert(iter_->IsValuePinned());
    pinned_value_ = iter_->value();
    valid_ = true;
    return true;
  }
S
Stanislau Hlebik 已提交
941 942 943

  // kTypeMerge. We need to collect all kTypeMerge values and save them
  // in operands
944
  current_entry_is_merged_ = true;
945
  merge_context_.Clear();
946 947
  while (
      iter_->Valid() &&
948
      user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()) &&
949 950 951
      ikey.type == kTypeMerge &&
      !range_del_agg_.ShouldDelete(
          ikey, RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
952 953
    merge_context_.PushOperand(iter_->value(),
                               iter_->IsValuePinned() /* operand_pinned */);
954
    PERF_COUNTER_ADD(internal_merge_count, 1);
S
Stanislau Hlebik 已提交
955 956 957 958
    iter_->Next();
    FindParseableKey(&ikey, kForward);
  }

959
  Status s;
S
Stanislau Hlebik 已提交
960
  if (!iter_->Valid() ||
961
      !user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()) ||
A
Andrew Kryczka 已提交
962
      ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion ||
963 964
      range_del_agg_.ShouldDelete(
          ikey, RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
965
    s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
966 967
                                    nullptr, merge_context_.GetOperands(),
                                    &saved_value_, logger_, statistics_, env_,
968
                                    &pinned_value_, true);
S
Stanislau Hlebik 已提交
969 970
    // Make iter_ valid and point to saved_key_
    if (!iter_->Valid() ||
971
        !user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
972 973 974
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    }
J
jorlow@chromium.org 已提交
975
    valid_ = true;
976 977 978
    if (!s.ok()) {
      status_ = s;
    }
S
Stanislau Hlebik 已提交
979 980 981
    return true;
  }

I
Igor Canadi 已提交
982
  const Slice& val = iter_->value();
983 984 985
  s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
                                  &val, merge_context_.GetOperands(),
                                  &saved_value_, logger_, statistics_, env_,
986
                                  &pinned_value_, true);
S
Stanislau Hlebik 已提交
987
  valid_ = true;
988 989 990
  if (!s.ok()) {
    status_ = s;
  }
S
Stanislau Hlebik 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
  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() &&
1005
         !user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    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);
1019
  int cmp;
1020 1021 1022
  while (iter_->Valid() &&
         ((cmp = user_comparator_->Compare(ikey.user_key,
                                           saved_key_.GetUserKey())) == 0 ||
Y
Yi Wu 已提交
1023
          (cmp > 0 && !IsVisible(ikey.sequence)))) {
1024 1025 1026 1027
    if (TooManyInternalKeysSkipped()) {
      return;
    }

1028 1029 1030 1031 1032
    if (cmp == 0) {
      if (num_skipped >= max_skip_) {
        num_skipped = 0;
        IterKey last_key;
        last_key.SetInternalKey(ParsedInternalKey(
1033 1034
            saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
        iter_->Seek(last_key.GetInternalKey());
1035 1036 1037 1038
        RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
      } else {
        ++num_skipped;
      }
S
Stanislau Hlebik 已提交
1039
    }
S
Siying Dong 已提交
1040
    assert(ikey.sequence != kMaxSequenceNumber);
Y
Yi Wu 已提交
1041
    if (!IsVisible(ikey.sequence)) {
1042 1043 1044 1045
      PERF_COUNTER_ADD(internal_recent_skipped_count, 1);
    } else {
      PERF_COUNTER_ADD(internal_key_skipped_count, 1);
    }
S
Stanislau Hlebik 已提交
1046 1047 1048 1049 1050
    iter_->Prev();
    FindParseableKey(&ikey, kReverse);
  }
}

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
bool DBIter::TooManyInternalKeysSkipped(bool increment) {
  if ((max_skippable_internal_keys_ > 0) &&
      (num_internal_keys_skipped_ > max_skippable_internal_keys_)) {
    valid_ = false;
    status_ = Status::Incomplete("Too many internal keys skipped.");
    return true;
  } else if (increment) {
    num_internal_keys_skipped_++;
  }
  return false;
}

Y
Yi Wu 已提交
1063 1064 1065 1066 1067
bool DBIter::IsVisible(SequenceNumber sequence) {
  return sequence <= sequence_ &&
         (read_callback_ == nullptr || read_callback_->IsCommitted(sequence));
}

S
Stanislau Hlebik 已提交
1068 1069 1070 1071 1072 1073 1074 1075
// 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 已提交
1076 1077
  }
}
J
jorlow@chromium.org 已提交
1078

J
jorlow@chromium.org 已提交
1079
void DBIter::Seek(const Slice& target) {
L
Lei Jin 已提交
1080
  StopWatch sw(env_, statistics_, DB_SEEK);
1081
  ReleaseTempPinnedData();
1082
  ResetInternalKeysSkippedCounter();
1083 1084
  saved_key_.Clear();
  saved_key_.SetInternalKey(target, sequence_);
1085 1086 1087

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1088
    iter_->Seek(saved_key_.GetInternalKey());
1089
    range_del_agg_.InvalidateTombstoneMapPositions();
1090
  }
M
Manuel Ung 已提交
1091
  RecordTick(statistics_, NUMBER_DB_SEEK);
J
jorlow@chromium.org 已提交
1092
  if (iter_->Valid()) {
1093 1094 1095
    if (prefix_extractor_ && prefix_same_as_start_) {
      prefix_start_key_ = prefix_extractor_->Transform(target);
    }
1096 1097
    direction_ = kForward;
    ClearSavedValue();
1098 1099 1100 1101
    FindNextUserEntry(false /* not skipping */, prefix_same_as_start_);
    if (!valid_) {
      prefix_start_key_.clear();
    }
M
Manuel Ung 已提交
1102 1103 1104 1105
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1106
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1107 1108
      }
    }
J
jorlow@chromium.org 已提交
1109 1110 1111
  } else {
    valid_ = false;
  }
1112

1113
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1114 1115
    prefix_start_buf_.SetUserKey(prefix_start_key_);
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
1116
  }
J
jorlow@chromium.org 已提交
1117
}
J
jorlow@chromium.org 已提交
1118

A
Aaron Gao 已提交
1119 1120 1121
void DBIter::SeekForPrev(const Slice& target) {
  StopWatch sw(env_, statistics_, DB_SEEK);
  ReleaseTempPinnedData();
1122
  ResetInternalKeysSkippedCounter();
A
Aaron Gao 已提交
1123 1124 1125 1126 1127 1128 1129
  saved_key_.Clear();
  // now saved_key is used to store internal key.
  saved_key_.SetInternalKey(target, 0 /* sequence_number */,
                            kValueTypeForSeekForPrev);

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1130
    iter_->SeekForPrev(saved_key_.GetInternalKey());
1131
    range_del_agg_.InvalidateTombstoneMapPositions();
A
Aaron Gao 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
  }

  RecordTick(statistics_, NUMBER_DB_SEEK);
  if (iter_->Valid()) {
    if (prefix_extractor_ && prefix_same_as_start_) {
      prefix_start_key_ = prefix_extractor_->Transform(target);
    }
    direction_ = kReverse;
    ClearSavedValue();
    PrevInternal();
    if (!valid_) {
      prefix_start_key_.clear();
    }
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1149
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
A
Aaron Gao 已提交
1150 1151 1152 1153 1154 1155
      }
    }
  } else {
    valid_ = false;
  }
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1156 1157
    prefix_start_buf_.SetUserKey(prefix_start_key_);
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
A
Aaron Gao 已提交
1158 1159 1160
  }
}

J
jorlow@chromium.org 已提交
1161
void DBIter::SeekToFirst() {
S
Stanislau Hlebik 已提交
1162
  // Don't use iter_::Seek() if we set a prefix extractor
1163
  // because prefix seek will be used.
1164
  if (prefix_extractor_ != nullptr) {
S
Stanislau Hlebik 已提交
1165 1166
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
1167 1168 1169 1170
  if (iterate_lower_bound_ != nullptr) {
    Seek(*iterate_lower_bound_);
    return;
  }
J
jorlow@chromium.org 已提交
1171
  direction_ = kForward;
1172
  ReleaseTempPinnedData();
1173
  ResetInternalKeysSkippedCounter();
J
jorlow@chromium.org 已提交
1174
  ClearSavedValue();
1175 1176 1177 1178

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->SeekToFirst();
1179
    range_del_agg_.InvalidateTombstoneMapPositions();
1180 1181
  }

M
Manuel Ung 已提交
1182
  RecordTick(statistics_, NUMBER_DB_SEEK);
J
jorlow@chromium.org 已提交
1183
  if (iter_->Valid()) {
1184 1185 1186
    saved_key_.SetUserKey(
        ExtractUserKey(iter_->key()),
        !iter_->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
1187
    FindNextUserEntry(false /* not skipping */, false /* no prefix check */);
M
Manuel Ung 已提交
1188 1189 1190 1191
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1192
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1193 1194
      }
    }
J
jorlow@chromium.org 已提交
1195 1196
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
1197
  }
1198
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1199 1200 1201
    prefix_start_buf_.SetUserKey(
        prefix_extractor_->Transform(saved_key_.GetUserKey()));
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
1202
  }
J
jorlow@chromium.org 已提交
1203 1204
}

J
jorlow@chromium.org 已提交
1205
void DBIter::SeekToLast() {
S
Stanislau Hlebik 已提交
1206
  // Don't use iter_::Seek() if we set a prefix extractor
1207
  // because prefix seek will be used.
1208
  if (prefix_extractor_ != nullptr) {
S
Stanislau Hlebik 已提交
1209 1210
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
J
jorlow@chromium.org 已提交
1211
  direction_ = kReverse;
1212
  ReleaseTempPinnedData();
1213
  ResetInternalKeysSkippedCounter();
J
jorlow@chromium.org 已提交
1214
  ClearSavedValue();
1215 1216 1217 1218

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->SeekToLast();
1219
    range_del_agg_.InvalidateTombstoneMapPositions();
1220
  }
1221 1222 1223 1224
  // 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) {
1225
    SeekForPrev(*iterate_upper_bound_);
1226
    range_del_agg_.InvalidateTombstoneMapPositions();
1227 1228 1229 1230
    if (!Valid()) {
      return;
    } else if (user_comparator_->Equal(*iterate_upper_bound_, key())) {
      Prev();
1231
    }
1232 1233
  } else {
    PrevInternal();
1234
  }
M
Manuel Ung 已提交
1235 1236 1237 1238 1239
  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());
1240
      PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1241 1242
    }
  }
1243
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1244 1245 1246
    prefix_start_buf_.SetUserKey(
        prefix_extractor_->Transform(saved_key_.GetUserKey()));
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
1247
  }
J
jorlow@chromium.org 已提交
1248 1249
}

1250 1251 1252 1253 1254
Iterator* NewDBIterator(Env* env, const ReadOptions& read_options,
                        const ImmutableCFOptions& cf_options,
                        const Comparator* user_key_comparator,
                        InternalIterator* internal_iter,
                        const SequenceNumber& sequence,
Y
Yi Wu 已提交
1255
                        uint64_t max_sequential_skip_in_iterations,
Y
Yi Wu 已提交
1256 1257 1258 1259 1260
                        ReadCallback* read_callback, bool allow_blob) {
  DBIter* db_iter =
      new DBIter(env, read_options, cf_options, user_key_comparator,
                 internal_iter, sequence, false,
                 max_sequential_skip_in_iterations, read_callback, allow_blob);
1261
  return db_iter;
1262 1263
}

I
Igor Canadi 已提交
1264
ArenaWrappedDBIter::~ArenaWrappedDBIter() { db_iter_->~DBIter(); }
1265

A
Andrew Kryczka 已提交
1266 1267 1268 1269
RangeDelAggregator* ArenaWrappedDBIter::GetRangeDelAggregator() {
  return db_iter_->GetRangeDelAggregator();
}

S
sdong 已提交
1270
void ArenaWrappedDBIter::SetIterUnderDBIter(InternalIterator* iter) {
1271 1272 1273 1274 1275 1276 1277 1278 1279
  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);
}
A
Aaron Gao 已提交
1280 1281 1282
inline void ArenaWrappedDBIter::SeekForPrev(const Slice& target) {
  db_iter_->SeekForPrev(target);
}
1283 1284 1285 1286 1287
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(); }
Y
Yi Wu 已提交
1288
bool ArenaWrappedDBIter::IsBlob() const { return db_iter_->IsBlob(); }
1289 1290
inline Status ArenaWrappedDBIter::GetProperty(std::string prop_name,
                                              std::string* prop) {
S
Siying Dong 已提交
1291 1292 1293 1294 1295 1296 1297
  if (prop_name == "rocksdb.iterator.super-version-number") {
    // First try to pass the value returned from inner iterator.
    if (!db_iter_->GetProperty(prop_name, prop).ok()) {
      *prop = ToString(sv_number_);
    }
    return Status::OK();
  }
1298 1299
  return db_iter_->GetProperty(prop_name, prop);
}
S
Siying Dong 已提交
1300 1301 1302 1303 1304

void ArenaWrappedDBIter::Init(Env* env, const ReadOptions& read_options,
                              const ImmutableCFOptions& cf_options,
                              const SequenceNumber& sequence,
                              uint64_t max_sequential_skip_in_iteration,
Y
Yi Wu 已提交
1305 1306
                              uint64_t version_number,
                              ReadCallback* read_callback, bool allow_blob) {
S
Siying Dong 已提交
1307 1308 1309
  auto mem = arena_.AllocateAligned(sizeof(DBIter));
  db_iter_ = new (mem)
      DBIter(env, read_options, cf_options, cf_options.user_comparator, nullptr,
Y
Yi Wu 已提交
1310 1311
             sequence, true, max_sequential_skip_in_iteration, read_callback,
             allow_blob);
S
Siying Dong 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
  sv_number_ = version_number;
}

Status ArenaWrappedDBIter::Refresh() {
  if (cfd_ == nullptr || db_impl_ == nullptr) {
    return Status::NotSupported("Creating renew iterator is not allowed.");
  }
  assert(db_iter_ != nullptr);
  SequenceNumber latest_seq = db_impl_->GetLatestSequenceNumber();
  uint64_t cur_sv_number = cfd_->GetSuperVersionNumber();
  if (sv_number_ != cur_sv_number) {
    Env* env = db_iter_->env();
    db_iter_->~DBIter();
    arena_.~Arena();
    new (&arena_) Arena();

    SuperVersion* sv = cfd_->GetReferencedSuperVersion(db_impl_->mutex());
    Init(env, read_options_, *(cfd_->ioptions()), latest_seq,
         sv->mutable_cf_options.max_sequential_skip_in_iterations,
Y
Yi Wu 已提交
1331
         cur_sv_number, read_callback_, allow_blob_);
S
Siying Dong 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340

    InternalIterator* internal_iter = db_impl_->NewInternalIterator(
        read_options_, cfd_, sv, &arena_, db_iter_->GetRangeDelAggregator());
    SetIterUnderDBIter(internal_iter);
  } else {
    db_iter_->set_sequence(latest_seq);
    db_iter_->set_valid(false);
  }
  return Status::OK();
1341
}
J
jorlow@chromium.org 已提交
1342

1343
ArenaWrappedDBIter* NewArenaWrappedDbIterator(
1344
    Env* env, const ReadOptions& read_options,
S
Siying Dong 已提交
1345 1346
    const ImmutableCFOptions& cf_options, const SequenceNumber& sequence,
    uint64_t max_sequential_skip_in_iterations, uint64_t version_number,
Y
Yi Wu 已提交
1347 1348
    ReadCallback* read_callback, DBImpl* db_impl, ColumnFamilyData* cfd,
    bool allow_blob) {
1349
  ArenaWrappedDBIter* iter = new ArenaWrappedDBIter();
S
Siying Dong 已提交
1350
  iter->Init(env, read_options, cf_options, sequence,
Y
Yi Wu 已提交
1351 1352
             max_sequential_skip_in_iterations, version_number, read_callback,
             allow_blob);
S
Siying Dong 已提交
1353
  if (db_impl != nullptr && cfd != nullptr) {
Y
Yi Wu 已提交
1354 1355
    iter->StoreRefreshInfo(read_options, db_impl, cfd, read_callback,
                           allow_blob);
S
Siying Dong 已提交
1356
  }
1357

1358
  return iter;
J
jorlow@chromium.org 已提交
1359 1360
}

1361
}  // namespace rocksdb