table_test.cc 41.6 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  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
// 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.
K
Kai Liu 已提交
9
#include <algorithm>
J
jorlow@chromium.org 已提交
10
#include <map>
11
#include <string>
J
Jim Paton 已提交
12
#include <memory>
K
Kai Liu 已提交
13 14
#include <vector>

J
jorlow@chromium.org 已提交
15
#include "db/dbformat.h"
I
Igor Canadi 已提交
16 17
#include "rocksdb/statistics.h"
#include "util/statistics.h"
J
jorlow@chromium.org 已提交
18 19
#include "db/memtable.h"
#include "db/write_batch_internal.h"
20

K
Kai Liu 已提交
21
#include "rocksdb/cache.h"
22
#include "rocksdb/db.h"
23
#include "rocksdb/plain_table_factory.h"
24 25
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
K
kailiu 已提交
26
#include "rocksdb/slice_transform.h"
27
#include "rocksdb/memtablerep.h"
28
#include "table/meta_blocks.h"
29
#include "rocksdb/plain_table_factory.h"
K
Kai Liu 已提交
30
#include "table/block_based_table_builder.h"
31
#include "table/block_based_table_factory.h"
K
Kai Liu 已提交
32
#include "table/block_based_table_reader.h"
J
jorlow@chromium.org 已提交
33
#include "table/block_builder.h"
K
Kai Liu 已提交
34
#include "table/block.h"
J
jorlow@chromium.org 已提交
35
#include "table/format.h"
36

J
jorlow@chromium.org 已提交
37 38 39 40
#include "util/random.h"
#include "util/testharness.h"
#include "util/testutil.h"

41
namespace rocksdb {
J
jorlow@chromium.org 已提交
42

43
namespace {
K
Kai Liu 已提交
44

J
jorlow@chromium.org 已提交
45 46
// Return reverse of "key".
// Used to test non-lexicographic comparators.
K
Kai Liu 已提交
47 48 49
std::string Reverse(const Slice& key) {
  auto rev = key.ToString();
  std::reverse(rev.begin(), rev.end());
J
jorlow@chromium.org 已提交
50 51 52 53 54 55
  return rev;
}

class ReverseKeyComparator : public Comparator {
 public:
  virtual const char* Name() const {
56
    return "rocksdb.ReverseBytewiseComparator";
J
jorlow@chromium.org 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  }

  virtual int Compare(const Slice& a, const Slice& b) const {
    return BytewiseComparator()->Compare(Reverse(a), Reverse(b));
  }

  virtual void FindShortestSeparator(
      std::string* start,
      const Slice& limit) const {
    std::string s = Reverse(*start);
    std::string l = Reverse(limit);
    BytewiseComparator()->FindShortestSeparator(&s, l);
    *start = Reverse(s);
  }

  virtual void FindShortSuccessor(std::string* key) const {
    std::string s = Reverse(*key);
    BytewiseComparator()->FindShortSuccessor(&s);
    *key = Reverse(s);
  }
};

K
Kai Liu 已提交
79 80 81
ReverseKeyComparator reverse_key_comparator;

void Increment(const Comparator* cmp, std::string* key) {
J
jorlow@chromium.org 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  if (cmp == BytewiseComparator()) {
    key->push_back('\0');
  } else {
    assert(cmp == &reverse_key_comparator);
    std::string rev = Reverse(*key);
    rev.push_back('\0');
    *key = Reverse(rev);
  }
}

// An STL comparator that uses a Comparator
struct STLLessThan {
  const Comparator* cmp;

  STLLessThan() : cmp(BytewiseComparator()) { }
A
Abhishek Kona 已提交
97
  explicit STLLessThan(const Comparator* c) : cmp(c) { }
J
jorlow@chromium.org 已提交
98 99 100 101
  bool operator()(const std::string& a, const std::string& b) const {
    return cmp->Compare(Slice(a), Slice(b)) < 0;
  }
};
K
Kai Liu 已提交
102

H
Hans Wennborg 已提交
103
}  // namespace
J
jorlow@chromium.org 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

class StringSink: public WritableFile {
 public:
  ~StringSink() { }

  const std::string& contents() const { return contents_; }

  virtual Status Close() { return Status::OK(); }
  virtual Status Flush() { return Status::OK(); }
  virtual Status Sync() { return Status::OK(); }

  virtual Status Append(const Slice& data) {
    contents_.append(data.data(), data.size());
    return Status::OK();
  }

 private:
  std::string contents_;
};


class StringSource: public RandomAccessFile {
 public:
127 128 129
  StringSource(const Slice& contents, uint64_t uniq_id, bool mmap)
      : contents_(contents.data(), contents.size()), uniq_id_(uniq_id),
        mmap_(mmap) {
J
jorlow@chromium.org 已提交
130 131 132 133
  }

  virtual ~StringSource() { }

J
jorlow@chromium.org 已提交
134
  uint64_t Size() const { return contents_.size(); }
J
jorlow@chromium.org 已提交
135 136 137 138 139 140 141 142 143

  virtual Status Read(uint64_t offset, size_t n, Slice* result,
                       char* scratch) const {
    if (offset > contents_.size()) {
      return Status::InvalidArgument("invalid Read offset");
    }
    if (offset + n > contents_.size()) {
      n = contents_.size() - offset;
    }
144 145 146 147 148 149
    if (!mmap_) {
      memcpy(scratch, &contents_[offset], n);
      *result = Slice(scratch, n);
    } else {
      *result = Slice(&contents_[offset], n);
    }
J
jorlow@chromium.org 已提交
150 151 152
    return Status::OK();
  }

153 154 155 156 157 158 159 160 161 162 163
  virtual size_t GetUniqueId(char* id, size_t max_size) const {
    if (max_size < 20) {
      return 0;
    }

    char* rid = id;
    rid = EncodeVarint64(rid, uniq_id_);
    rid = EncodeVarint64(rid, 0);
    return static_cast<size_t>(rid-id);
  }

J
jorlow@chromium.org 已提交
164 165
 private:
  std::string contents_;
166
  uint64_t uniq_id_;
167
  bool mmap_;
J
jorlow@chromium.org 已提交
168 169
};

K
Kai Liu 已提交
170
typedef std::map<std::string, std::string, STLLessThan> KVMap;
J
jorlow@chromium.org 已提交
171 172 173 174 175

// Helper class for tests to unify the interface between
// BlockBuilder/TableBuilder and Block/Table.
class Constructor {
 public:
K
Kai Liu 已提交
176
  explicit Constructor(const Comparator* cmp) : data_(STLLessThan(cmp)) {}
J
jorlow@chromium.org 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  virtual ~Constructor() { }

  void Add(const std::string& key, const Slice& value) {
    data_[key] = value.ToString();
  }

  // Finish constructing the data structure with all the keys that have
  // been added so far.  Returns the keys in sorted order in "*keys"
  // and stores the key/value pairs in "*kvmap"
  void Finish(const Options& options,
              std::vector<std::string>* keys,
              KVMap* kvmap) {
    *kvmap = data_;
    keys->clear();
    for (KVMap::const_iterator it = data_.begin();
         it != data_.end();
         ++it) {
      keys->push_back(it->first);
    }
    data_.clear();
    Status s = FinishImpl(options, *kvmap);
    ASSERT_TRUE(s.ok()) << s.ToString();
  }

  // Construct the data structure from the data in "data"
  virtual Status FinishImpl(const Options& options, const KVMap& data) = 0;

  virtual Iterator* NewIterator() const = 0;

  virtual const KVMap& data() { return data_; }

A
Abhishek Kona 已提交
208
  virtual DB* db() const { return nullptr; }  // Overridden in DBConstructor
J
jorlow@chromium.org 已提交
209

J
jorlow@chromium.org 已提交
210 211 212 213 214 215 216 217 218
 private:
  KVMap data_;
};

class BlockConstructor: public Constructor {
 public:
  explicit BlockConstructor(const Comparator* cmp)
      : Constructor(cmp),
        comparator_(cmp),
A
Abhishek Kona 已提交
219
        block_(nullptr) { }
J
jorlow@chromium.org 已提交
220 221 222 223 224
  ~BlockConstructor() {
    delete block_;
  }
  virtual Status FinishImpl(const Options& options, const KVMap& data) {
    delete block_;
A
Abhishek Kona 已提交
225
    block_ = nullptr;
226
    BlockBuilder builder(options);
J
jorlow@chromium.org 已提交
227 228 229 230 231 232 233

    for (KVMap::const_iterator it = data.begin();
         it != data.end();
         ++it) {
      builder.Add(it->first, it->second);
    }
    // Open the block
S
Sanjay Ghemawat 已提交
234 235 236 237 238 239
    data_ = builder.Finish().ToString();
    BlockContents contents;
    contents.data = data_;
    contents.cachable = false;
    contents.heap_allocated = false;
    block_ = new Block(contents);
J
jorlow@chromium.org 已提交
240 241 242 243 244 245 246 247
    return Status::OK();
  }
  virtual Iterator* NewIterator() const {
    return block_->NewIterator(comparator_);
  }

 private:
  const Comparator* comparator_;
S
Sanjay Ghemawat 已提交
248
  std::string data_;
J
jorlow@chromium.org 已提交
249 250 251 252 253
  Block* block_;

  BlockConstructor();
};

254 255
// A helper class that converts internal format keys into user keys
class KeyConvertingIterator: public Iterator {
J
jorlow@chromium.org 已提交
256
 public:
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  explicit KeyConvertingIterator(Iterator* iter) : iter_(iter) { }
  virtual ~KeyConvertingIterator() { delete iter_; }
  virtual bool Valid() const { return iter_->Valid(); }
  virtual void Seek(const Slice& target) {
    ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
    std::string encoded;
    AppendInternalKey(&encoded, ikey);
    iter_->Seek(encoded);
  }
  virtual void SeekToFirst() { iter_->SeekToFirst(); }
  virtual void SeekToLast() { iter_->SeekToLast(); }
  virtual void Next() { iter_->Next(); }
  virtual void Prev() { iter_->Prev(); }

  virtual Slice key() const {
    assert(Valid());
    ParsedInternalKey key;
    if (!ParseInternalKey(iter_->key(), &key)) {
      status_ = Status::Corruption("malformed internal key");
      return Slice("corrupted key");
    }
    return key.user_key;
J
jorlow@chromium.org 已提交
279
  }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

  virtual Slice value() const { return iter_->value(); }
  virtual Status status() const {
    return status_.ok() ? iter_->status() : status_;
  }

 private:
  mutable Status status_;
  Iterator* iter_;

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

class TableConstructor: public Constructor {
 public:
K
kailiu 已提交
297 298 299 300
  explicit TableConstructor(const Comparator* cmp,
                            bool convert_to_internal_key = false)
      : Constructor(cmp), convert_to_internal_key_(convert_to_internal_key) {}
  ~TableConstructor() { Reset(); }
301

J
jorlow@chromium.org 已提交
302 303
  virtual Status FinishImpl(const Options& options, const KVMap& data) {
    Reset();
304
    sink_.reset(new StringSink());
305 306 307 308
    unique_ptr<TableBuilder> builder;
    builder.reset(
        options.table_factory->GetTableBuilder(options, sink_.get(),
                                               options.compression));
J
jorlow@chromium.org 已提交
309 310 311 312

    for (KVMap::const_iterator it = data.begin();
         it != data.end();
         ++it) {
313 314 315 316 317 318 319 320 321
      if (convert_to_internal_key_) {
        ParsedInternalKey ikey(it->first, kMaxSequenceNumber, kTypeValue);
        std::string encoded;
        AppendInternalKey(&encoded, ikey);
        builder->Add(encoded, it->second);
      } else {
        builder->Add(it->first, it->second);
      }
      ASSERT_TRUE(builder->status().ok());
J
jorlow@chromium.org 已提交
322
    }
323
    Status s = builder->Finish();
J
jorlow@chromium.org 已提交
324 325
    ASSERT_TRUE(s.ok()) << s.ToString();

326
    ASSERT_EQ(sink_->contents().size(), builder->FileSize());
J
jorlow@chromium.org 已提交
327 328

    // Open the table
329
    uniq_id_ = cur_uniq_id_++;
K
kailiu 已提交
330 331 332 333 334
    source_.reset(new StringSource(sink_->contents(), uniq_id_,
                                   options.allow_mmap_reads));
    return options.table_factory->GetTableReader(
        options, soptions, std::move(source_), sink_->contents().size(),
        &table_reader_);
J
jorlow@chromium.org 已提交
335 336 337
  }

  virtual Iterator* NewIterator() const {
338 339 340 341 342 343
    Iterator* iter = table_reader_->NewIterator(ReadOptions());
    if (convert_to_internal_key_) {
      return new KeyConvertingIterator(iter);
    } else {
      return iter;
    }
J
jorlow@chromium.org 已提交
344 345 346
  }

  uint64_t ApproximateOffsetOf(const Slice& key) const {
S
Siying Dong 已提交
347
    return table_reader_->ApproximateOffsetOf(key);
J
jorlow@chromium.org 已提交
348 349
  }

350
  virtual Status Reopen(const Options& options) {
351 352 353
    source_.reset(
        new StringSource(sink_->contents(), uniq_id_,
                         options.allow_mmap_reads));
S
Siying Dong 已提交
354 355 356 357
    return options.table_factory->GetTableReader(options, soptions,
                                                 std::move(source_),
                                                 sink_->contents().size(),
                                                 &table_reader_);
358 359
  }

S
Siying Dong 已提交
360 361
  virtual TableReader* table_reader() {
    return table_reader_.get();
362 363
  }

J
jorlow@chromium.org 已提交
364 365
 private:
  void Reset() {
366
    uniq_id_ = 0;
S
Siying Dong 已提交
367
    table_reader_.reset();
368
    sink_.reset();
369
    source_.reset();
J
jorlow@chromium.org 已提交
370
  }
371
  bool convert_to_internal_key_;
J
jorlow@chromium.org 已提交
372

373 374
  uint64_t uniq_id_;
  unique_ptr<StringSink> sink_;
375
  unique_ptr<StringSource> source_;
S
Siying Dong 已提交
376
  unique_ptr<TableReader> table_reader_;
J
jorlow@chromium.org 已提交
377

378
  TableConstructor();
379 380

  static uint64_t cur_uniq_id_;
H
Haobo Xu 已提交
381
  const EnvOptions soptions;
J
jorlow@chromium.org 已提交
382
};
383
uint64_t TableConstructor::cur_uniq_id_ = 1;
J
jorlow@chromium.org 已提交
384 385 386 387 388

class MemTableConstructor: public Constructor {
 public:
  explicit MemTableConstructor(const Comparator* cmp)
      : Constructor(cmp),
J
Jim Paton 已提交
389 390
        internal_comparator_(cmp),
        table_factory_(new SkipListFactory) {
I
Igor Canadi 已提交
391 392 393
    Options options;
    options.memtable_factory = table_factory_;
    memtable_ = new MemTable(internal_comparator_, options);
394
    memtable_->Ref();
J
jorlow@chromium.org 已提交
395 396
  }
  ~MemTableConstructor() {
397
    delete memtable_->Unref();
J
jorlow@chromium.org 已提交
398 399
  }
  virtual Status FinishImpl(const Options& options, const KVMap& data) {
400
    delete memtable_->Unref();
I
Igor Canadi 已提交
401 402 403
    Options memtable_options;
    memtable_options.memtable_factory = table_factory_;
    memtable_ = new MemTable(internal_comparator_, memtable_options);
404
    memtable_->Ref();
J
jorlow@chromium.org 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    int seq = 1;
    for (KVMap::const_iterator it = data.begin();
         it != data.end();
         ++it) {
      memtable_->Add(seq, kTypeValue, it->first, it->second);
      seq++;
    }
    return Status::OK();
  }
  virtual Iterator* NewIterator() const {
    return new KeyConvertingIterator(memtable_->NewIterator());
  }

 private:
  InternalKeyComparator internal_comparator_;
  MemTable* memtable_;
J
Jim Paton 已提交
421
  std::shared_ptr<SkipListFactory> table_factory_;
J
jorlow@chromium.org 已提交
422 423 424 425 426 427 428
};

class DBConstructor: public Constructor {
 public:
  explicit DBConstructor(const Comparator* cmp)
      : Constructor(cmp),
        comparator_(cmp) {
A
Abhishek Kona 已提交
429
    db_ = nullptr;
J
jorlow@chromium.org 已提交
430 431 432 433 434 435 436
    NewDB();
  }
  ~DBConstructor() {
    delete db_;
  }
  virtual Status FinishImpl(const Options& options, const KVMap& data) {
    delete db_;
A
Abhishek Kona 已提交
437
    db_ = nullptr;
J
jorlow@chromium.org 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451
    NewDB();
    for (KVMap::const_iterator it = data.begin();
         it != data.end();
         ++it) {
      WriteBatch batch;
      batch.Put(it->first, it->second);
      ASSERT_TRUE(db_->Write(WriteOptions(), &batch).ok());
    }
    return Status::OK();
  }
  virtual Iterator* NewIterator() const {
    return db_->NewIterator(ReadOptions());
  }

J
jorlow@chromium.org 已提交
452 453
  virtual DB* db() const { return db_; }

J
jorlow@chromium.org 已提交
454 455 456 457
 private:
  void NewDB() {
    std::string name = test::TmpDir() + "/table_testdb";

458
    Options options;
J
jorlow@chromium.org 已提交
459 460 461 462 463 464
    options.comparator = comparator_;
    Status status = DestroyDB(name, options);
    ASSERT_TRUE(status.ok()) << status.ToString();

    options.create_if_missing = true;
    options.error_if_exists = true;
J
jorlow@chromium.org 已提交
465
    options.write_buffer_size = 10000;  // Something small to force merging
J
jorlow@chromium.org 已提交
466 467 468 469 470 471 472 473
    status = DB::Open(options, name, &db_);
    ASSERT_TRUE(status.ok()) << status.ToString();
  }

  const Comparator* comparator_;
  DB* db_;
};

H
heyongqiang 已提交
474 475 476
static bool SnappyCompressionSupported() {
  std::string out;
  Slice in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
477
  return port::Snappy_Compress(Options().compression_opts,
478
                               in.data(), in.size(),
479
                               &out);
H
heyongqiang 已提交
480 481 482 483 484
}

static bool ZlibCompressionSupported() {
  std::string out;
  Slice in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
485
  return port::Zlib_Compress(Options().compression_opts,
486
                             in.data(), in.size(),
487
                             &out);
H
heyongqiang 已提交
488 489
}

C
Chip Turner 已提交
490
#ifdef BZIP2
H
heyongqiang 已提交
491 492 493
static bool BZip2CompressionSupported() {
  std::string out;
  Slice in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
494
  return port::BZip2_Compress(Options().compression_opts,
495
                              in.data(), in.size(),
496
                              &out);
H
heyongqiang 已提交
497
}
C
Chip Turner 已提交
498
#endif
H
heyongqiang 已提交
499

J
jorlow@chromium.org 已提交
500
enum TestType {
501 502 503
  BLOCK_BASED_TABLE_TEST,
  PLAIN_TABLE_SEMI_FIXED_PREFIX,
  PLAIN_TABLE_FULL_STR_PREFIX,
J
jorlow@chromium.org 已提交
504 505
  BLOCK_TEST,
  MEMTABLE_TEST,
506
  DB_TEST
J
jorlow@chromium.org 已提交
507 508 509 510 511 512
};

struct TestArgs {
  TestType type;
  bool reverse_compare;
  int restart_interval;
H
heyongqiang 已提交
513
  CompressionType compression;
J
jorlow@chromium.org 已提交
514 515
};

516
static std::vector<TestArgs> GenerateArgList() {
K
Kai Liu 已提交
517 518 519 520 521 522 523
  std::vector<TestArgs> test_args;
  std::vector<TestType> test_types = {
      BLOCK_BASED_TABLE_TEST,      PLAIN_TABLE_SEMI_FIXED_PREFIX,
      PLAIN_TABLE_FULL_STR_PREFIX, BLOCK_TEST,
      MEMTABLE_TEST,               DB_TEST};
  std::vector<bool> reverse_compare_types = {false, true};
  std::vector<int> restart_intervals = {16, 1, 1024};
H
heyongqiang 已提交
524 525

  // Only add compression if it is supported
K
Kai Liu 已提交
526
  std::vector<CompressionType> compression_types = {kNoCompression};
H
heyongqiang 已提交
527
#ifdef SNAPPY
K
Kai Liu 已提交
528
  if (SnappyCompressionSupported()) {
H
heyongqiang 已提交
529
    compression_types.push_back(kSnappyCompression);
K
Kai Liu 已提交
530
  }
H
heyongqiang 已提交
531 532 533
#endif

#ifdef ZLIB
K
Kai Liu 已提交
534
  if (ZlibCompressionSupported()) {
H
heyongqiang 已提交
535
    compression_types.push_back(kZlibCompression);
K
Kai Liu 已提交
536
  }
H
heyongqiang 已提交
537 538
#endif

H
heyongqiang 已提交
539
#ifdef BZIP2
K
Kai Liu 已提交
540
  if (BZip2CompressionSupported()) {
H
heyongqiang 已提交
541
    compression_types.push_back(kBZip2Compression);
K
Kai Liu 已提交
542
  }
H
heyongqiang 已提交
543 544
#endif

K
Kai Liu 已提交
545 546 547 548
  for (auto test_type : test_types) {
    for (auto reverse_compare : reverse_compare_types) {
      if (test_type == PLAIN_TABLE_SEMI_FIXED_PREFIX ||
          test_type == PLAIN_TABLE_FULL_STR_PREFIX) {
549 550
        // Plain table doesn't use restart index or compression.
        TestArgs one_arg;
K
Kai Liu 已提交
551 552 553
        one_arg.type = test_type;
        one_arg.reverse_compare = reverse_compare;
        one_arg.restart_interval = restart_intervals[0];
554
        one_arg.compression = compression_types[0];
K
Kai Liu 已提交
555
        test_args.push_back(one_arg);
556 557
        continue;
      }
H
heyongqiang 已提交
558

K
Kai Liu 已提交
559 560
      for (auto restart_interval : restart_intervals) {
        for (auto compression_type : compression_types) {
561
          TestArgs one_arg;
K
Kai Liu 已提交
562 563 564 565 566
          one_arg.type = test_type;
          one_arg.reverse_compare = reverse_compare;
          one_arg.restart_interval = restart_interval;
          one_arg.compression = compression_type;
          test_args.push_back(one_arg);
567
        }
K
Kai Liu 已提交
568
      }
569
    }
K
Kai Liu 已提交
570 571
  }
  return test_args;
H
heyongqiang 已提交
572
}
J
jorlow@chromium.org 已提交
573

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
// In order to make all tests run for plain table format, including
// those operating on empty keys, create a new prefix transformer which
// return fixed prefix if the slice is not shorter than the prefix length,
// and the full slice if it is shorter.
class FixedOrLessPrefixTransform : public SliceTransform {
 private:
  const size_t prefix_len_;

 public:
  explicit FixedOrLessPrefixTransform(size_t prefix_len) :
      prefix_len_(prefix_len) {
  }

  virtual const char* Name() const {
    return "rocksdb.FixedPrefix";
  }

  virtual Slice Transform(const Slice& src) const {
    assert(InDomain(src));
    if (src.size() < prefix_len_) {
      return src;
    }
    return Slice(src.data(), prefix_len_);
  }

  virtual bool InDomain(const Slice& src) const {
    return true;
  }

  virtual bool InRange(const Slice& dst) const {
    return (dst.size() <= prefix_len_);
  }
};

J
jorlow@chromium.org 已提交
608 609
class Harness {
 public:
A
Abhishek Kona 已提交
610
  Harness() : constructor_(nullptr) { }
J
jorlow@chromium.org 已提交
611 612 613

  void Init(const TestArgs& args) {
    delete constructor_;
A
Abhishek Kona 已提交
614
    constructor_ = nullptr;
615
    options_ = Options();
J
jorlow@chromium.org 已提交
616 617

    options_.block_restart_interval = args.restart_interval;
H
heyongqiang 已提交
618
    options_.compression = args.compression;
J
jorlow@chromium.org 已提交
619 620 621 622 623 624
    // Use shorter block size for tests to exercise block boundary
    // conditions more.
    options_.block_size = 256;
    if (args.reverse_compare) {
      options_.comparator = &reverse_key_comparator;
    }
625 626 627
    internal_comparator_.reset(new InternalKeyComparator(options_.comparator));
    support_prev_ = true;
    only_support_prefix_seek_ = false;
K
kailiu 已提交
628
    BlockBasedTableOptions table_options;
J
jorlow@chromium.org 已提交
629
    switch (args.type) {
630 631 632 633 634 635 636 637 638 639
      case BLOCK_BASED_TABLE_TEST:
        table_options.flush_block_policy_factory.reset(
            new FlushBlockBySizePolicyFactory(options_.block_size,
                                              options_.block_size_deviation));
        options_.table_factory.reset(new BlockBasedTableFactory(table_options));
        constructor_ = new TableConstructor(options_.comparator);
        break;
      case PLAIN_TABLE_SEMI_FIXED_PREFIX:
        support_prev_ = false;
        only_support_prefix_seek_ = true;
640
        options_.prefix_extractor = prefix_transform.get();
641 642 643 644 645 646 647 648
        options_.allow_mmap_reads = true;
        options_.table_factory.reset(new PlainTableFactory());
        constructor_ = new TableConstructor(options_.comparator, true);
        options_.comparator = internal_comparator_.get();
        break;
      case PLAIN_TABLE_FULL_STR_PREFIX:
        support_prev_ = false;
        only_support_prefix_seek_ = true;
K
Kai Liu 已提交
649
        options_.prefix_extractor = noop_transform.get();
650 651 652 653
        options_.allow_mmap_reads = true;
        options_.table_factory.reset(new PlainTableFactory());
        constructor_ = new TableConstructor(options_.comparator, true);
        options_.comparator = internal_comparator_.get();
J
jorlow@chromium.org 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        break;
      case BLOCK_TEST:
        constructor_ = new BlockConstructor(options_.comparator);
        break;
      case MEMTABLE_TEST:
        constructor_ = new MemTableConstructor(options_.comparator);
        break;
      case DB_TEST:
        constructor_ = new DBConstructor(options_.comparator);
        break;
    }
  }

  ~Harness() {
    delete constructor_;
  }

  void Add(const std::string& key, const std::string& value) {
    constructor_->Add(key, value);
  }

  void Test(Random* rnd) {
    std::vector<std::string> keys;
    KVMap data;
    constructor_->Finish(options_, &keys, &data);

    TestForwardScan(keys, data);
681 682 683
    if (support_prev_) {
      TestBackwardScan(keys, data);
    }
J
jorlow@chromium.org 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    TestRandomAccess(rnd, keys, data);
  }

  void TestForwardScan(const std::vector<std::string>& keys,
                       const KVMap& data) {
    Iterator* iter = constructor_->NewIterator();
    ASSERT_TRUE(!iter->Valid());
    iter->SeekToFirst();
    for (KVMap::const_iterator model_iter = data.begin();
         model_iter != data.end();
         ++model_iter) {
      ASSERT_EQ(ToString(data, model_iter), ToString(iter));
      iter->Next();
    }
    ASSERT_TRUE(!iter->Valid());
    delete iter;
  }

  void TestBackwardScan(const std::vector<std::string>& keys,
                        const KVMap& data) {
    Iterator* iter = constructor_->NewIterator();
    ASSERT_TRUE(!iter->Valid());
    iter->SeekToLast();
    for (KVMap::const_reverse_iterator model_iter = data.rbegin();
         model_iter != data.rend();
         ++model_iter) {
      ASSERT_EQ(ToString(data, model_iter), ToString(iter));
      iter->Prev();
    }
    ASSERT_TRUE(!iter->Valid());
    delete iter;
  }

  void TestRandomAccess(Random* rnd,
                        const std::vector<std::string>& keys,
                        const KVMap& data) {
    static const bool kVerbose = false;
    Iterator* iter = constructor_->NewIterator();
    ASSERT_TRUE(!iter->Valid());
    KVMap::const_iterator model_iter = data.begin();
    if (kVerbose) fprintf(stderr, "---\n");
    for (int i = 0; i < 200; i++) {
726
      const int toss = rnd->Uniform(support_prev_ ? 5 : 3);
J
jorlow@chromium.org 已提交
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
      switch (toss) {
        case 0: {
          if (iter->Valid()) {
            if (kVerbose) fprintf(stderr, "Next\n");
            iter->Next();
            ++model_iter;
            ASSERT_EQ(ToString(data, model_iter), ToString(iter));
          }
          break;
        }

        case 1: {
          if (kVerbose) fprintf(stderr, "SeekToFirst\n");
          iter->SeekToFirst();
          model_iter = data.begin();
          ASSERT_EQ(ToString(data, model_iter), ToString(iter));
          break;
        }

        case 2: {
          std::string key = PickRandomKey(rnd, keys);
          model_iter = data.lower_bound(key);
          if (kVerbose) fprintf(stderr, "Seek '%s'\n",
                                EscapeString(key).c_str());
          iter->Seek(Slice(key));
          ASSERT_EQ(ToString(data, model_iter), ToString(iter));
          break;
        }

        case 3: {
          if (iter->Valid()) {
            if (kVerbose) fprintf(stderr, "Prev\n");
            iter->Prev();
            if (model_iter == data.begin()) {
              model_iter = data.end();   // Wrap around to invalid value
            } else {
              --model_iter;
            }
            ASSERT_EQ(ToString(data, model_iter), ToString(iter));
          }
          break;
        }

        case 4: {
          if (kVerbose) fprintf(stderr, "SeekToLast\n");
          iter->SeekToLast();
          if (keys.empty()) {
            model_iter = data.end();
          } else {
            std::string last = data.rbegin()->first;
            model_iter = data.lower_bound(last);
          }
          ASSERT_EQ(ToString(data, model_iter), ToString(iter));
          break;
        }
      }
    }
    delete iter;
  }

  std::string ToString(const KVMap& data, const KVMap::const_iterator& it) {
    if (it == data.end()) {
      return "END";
    } else {
      return "'" + it->first + "->" + it->second + "'";
    }
  }

  std::string ToString(const KVMap& data,
                       const KVMap::const_reverse_iterator& it) {
    if (it == data.rend()) {
      return "END";
    } else {
      return "'" + it->first + "->" + it->second + "'";
    }
  }

  std::string ToString(const Iterator* it) {
    if (!it->Valid()) {
      return "END";
    } else {
      return "'" + it->key().ToString() + "->" + it->value().ToString() + "'";
    }
  }

  std::string PickRandomKey(Random* rnd, const std::vector<std::string>& keys) {
    if (keys.empty()) {
      return "foo";
    } else {
      const int index = rnd->Uniform(keys.size());
      std::string result = keys[index];
818
      switch (rnd->Uniform(support_prev_ ? 3 : 1)) {
J
jorlow@chromium.org 已提交
819 820 821 822 823
        case 0:
          // Return an existing key
          break;
        case 1: {
          // Attempt to return something smaller than an existing key
824 825 826 827 828
          if (result.size() > 0 && result[result.size() - 1] > '\0'
              && (!only_support_prefix_seek_
                  || options_.prefix_extractor->Transform(result).size()
                  < result.size())) {
            result[result.size() - 1]--;
J
jorlow@chromium.org 已提交
829 830
          }
          break;
831
      }
J
jorlow@chromium.org 已提交
832 833 834 835 836 837 838 839 840 841
        case 2: {
          // Return something larger than an existing key
          Increment(options_.comparator, &result);
          break;
        }
      }
      return result;
    }
  }

A
Abhishek Kona 已提交
842
  // Returns nullptr if not running against a DB
J
jorlow@chromium.org 已提交
843 844
  DB* db() const { return constructor_->db(); }

J
jorlow@chromium.org 已提交
845
 private:
846
  Options options_ = Options();
J
jorlow@chromium.org 已提交
847
  Constructor* constructor_;
848 849 850
  bool support_prev_;
  bool only_support_prefix_seek_;
  shared_ptr<Comparator> internal_comparator_;
K
Kai Liu 已提交
851
  static std::unique_ptr<const SliceTransform> noop_transform;
852
  static std::unique_ptr<const SliceTransform> prefix_transform;
J
jorlow@chromium.org 已提交
853 854
};

K
Kai Liu 已提交
855 856
std::unique_ptr<const SliceTransform> Harness::noop_transform(
    NewNoopTransform());
857 858
std::unique_ptr<const SliceTransform> Harness::prefix_transform(
    new FixedOrLessPrefixTransform(2));
K
Kai Liu 已提交
859

J
jorlow@chromium.org 已提交
860 861 862 863 864 865 866 867 868 869 870
static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  bool result = (val >= low) && (val <= high);
  if (!result) {
    fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
            (unsigned long long)(val),
            (unsigned long long)(low),
            (unsigned long long)(high));
  }
  return result;
}

K
Kai Liu 已提交
871
// Tests against all kinds of tables
K
Kai Liu 已提交
872 873 874
class GeneralTableTest {};
class BlockBasedTableTest {};
class PlainTableTest {};
J
jorlow@chromium.org 已提交
875

K
Kai Liu 已提交
876 877
// This test include all the basic checks except those for index size and block
// size, which will be conducted in separated unit tests.
K
Kai Liu 已提交
878
TEST(BlockBasedTableTest, BasicBlockBasedTableProperties) {
879
  TableConstructor c(BytewiseComparator());
K
Kai Liu 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892

  c.Add("a1", "val1");
  c.Add("b2", "val2");
  c.Add("c3", "val3");
  c.Add("d4", "val4");
  c.Add("e5", "val5");
  c.Add("f6", "val6");
  c.Add("g7", "val7");
  c.Add("h8", "val8");
  c.Add("j9", "val9");

  std::vector<std::string> keys;
  KVMap kvmap;
893
  Options options;
K
Kai Liu 已提交
894 895 896 897 898
  options.compression = kNoCompression;
  options.block_restart_interval = 1;

  c.Finish(options, &keys, &kvmap);

K
kailiu 已提交
899 900
  auto& props = c.table_reader()->GetTableProperties();
  ASSERT_EQ(kvmap.size(), props.num_entries);
K
Kai Liu 已提交
901 902 903 904

  auto raw_key_size = kvmap.size() * 2ul;
  auto raw_value_size = kvmap.size() * 4ul;

K
kailiu 已提交
905 906 907 908
  ASSERT_EQ(raw_key_size, props.raw_key_size);
  ASSERT_EQ(raw_value_size, props.raw_value_size);
  ASSERT_EQ(1ul, props.num_data_blocks);
  ASSERT_EQ("", props.filter_policy_name);  // no filter policy is used
K
Kai Liu 已提交
909 910

  // Verify data size.
911
  BlockBuilder block_builder(options);
K
Kai Liu 已提交
912 913 914 915 916 917
  for (const auto& item : kvmap) {
    block_builder.Add(item.first, item.second);
  }
  Slice content = block_builder.Finish();
  ASSERT_EQ(
      content.size() + kBlockTrailerSize,
K
kailiu 已提交
918
      props.data_size
K
Kai Liu 已提交
919 920 921
  );
}

K
Kai Liu 已提交
922
TEST(BlockBasedTableTest, FilterPolicyNameProperties) {
923
  TableConstructor c(BytewiseComparator());
924 925 926
  c.Add("a1", "val1");
  std::vector<std::string> keys;
  KVMap kvmap;
927
  Options options;
928 929 930 931
  std::unique_ptr<const FilterPolicy> filter_policy(
    NewBloomFilterPolicy(10)
  );
  options.filter_policy = filter_policy.get();
932 933

  c.Finish(options, &keys, &kvmap);
K
kailiu 已提交
934 935
  auto& props = c.table_reader()->GetTableProperties();
  ASSERT_EQ("rocksdb.BuiltinBloomFilter", props.filter_policy_name);
936 937
}

K
Kai Liu 已提交
938 939 940 941 942 943 944 945 946
static std::string RandomString(Random* rnd, int len) {
  std::string r;
  test::RandomString(rnd, len, &r);
  return r;
}

// It's very hard to figure out the index block size of a block accurately.
// To make sure we get the index size, we just make sure as key number
// grows, the filter block size also grows.
K
Kai Liu 已提交
947
TEST(BlockBasedTableTest, IndexSizeStat) {
K
Kai Liu 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
  uint64_t last_index_size = 0;

  // we need to use random keys since the pure human readable texts
  // may be well compressed, resulting insignifcant change of index
  // block size.
  Random rnd(test::RandomSeed());
  std::vector<std::string> keys;

  for (int i = 0; i < 100; ++i) {
    keys.push_back(RandomString(&rnd, 10000));
  }

  // Each time we load one more key to the table. the table index block
  // size is expected to be larger than last time's.
  for (size_t i = 1; i < keys.size(); ++i) {
963
    TableConstructor c(BytewiseComparator());
K
Kai Liu 已提交
964 965 966 967 968 969
    for (size_t j = 0; j < i; ++j) {
      c.Add(keys[j], "val");
    }

    std::vector<std::string> ks;
    KVMap kvmap;
970
    Options options;
K
Kai Liu 已提交
971 972 973 974 975
    options.compression = kNoCompression;
    options.block_restart_interval = 1;

    c.Finish(options, &ks, &kvmap);
    auto index_size =
K
kailiu 已提交
976
      c.table_reader()->GetTableProperties().index_size;
K
Kai Liu 已提交
977 978 979 980 981
    ASSERT_GT(index_size, last_index_size);
    last_index_size = index_size;
  }
}

K
Kai Liu 已提交
982
TEST(BlockBasedTableTest, NumBlockStat) {
K
Kai Liu 已提交
983
  Random rnd(test::RandomSeed());
984
  TableConstructor c(BytewiseComparator());
K
Kai Liu 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
  Options options;
  options.compression = kNoCompression;
  options.block_restart_interval = 1;
  options.block_size = 1000;

  for (int i = 0; i < 10; ++i) {
    // the key/val are slightly smaller than block size, so that each block
    // holds roughly one key/value pair.
    c.Add(RandomString(&rnd, 900), "val");
  }

  std::vector<std::string> ks;
  KVMap kvmap;
  c.Finish(options, &ks, &kvmap);
  ASSERT_EQ(
      kvmap.size(),
K
kailiu 已提交
1001
      c.table_reader()->GetTableProperties().num_data_blocks
K
Kai Liu 已提交
1002 1003 1004
  );
}

K
kailiu 已提交
1005
class BlockCacheProperties {
K
Kai Liu 已提交
1006
 public:
I
Igor Canadi 已提交
1007
  explicit BlockCacheProperties(Statistics* statistics) {
I
Igor Canadi 已提交
1008 1009 1010 1011 1012 1013
    block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_MISS);
    block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_HIT);
    index_block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_INDEX_MISS);
    index_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_INDEX_HIT);
    data_block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_DATA_MISS);
    data_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_DATA_HIT);
K
Kai Liu 已提交
1014 1015
  }

K
kailiu 已提交
1016
  // Check if the fetched props matches the expected ones.
K
Kai Liu 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  void AssertEqual(
      long index_block_cache_miss,
      long index_block_cache_hit,
      long data_block_cache_miss,
      long data_block_cache_hit) const {
    ASSERT_EQ(index_block_cache_miss, this->index_block_cache_miss);
    ASSERT_EQ(index_block_cache_hit, this->index_block_cache_hit);
    ASSERT_EQ(data_block_cache_miss, this->data_block_cache_miss);
    ASSERT_EQ(data_block_cache_hit, this->data_block_cache_hit);
    ASSERT_EQ(
        index_block_cache_miss + data_block_cache_miss,
        this->block_cache_miss
    );
    ASSERT_EQ(
        index_block_cache_hit + data_block_cache_hit,
        this->block_cache_hit
    );
  }

 private:
  long block_cache_miss = 0;
  long block_cache_hit = 0;
  long index_block_cache_miss = 0;
  long index_block_cache_hit = 0;
  long data_block_cache_miss = 0;
  long data_block_cache_hit = 0;
};

K
Kai Liu 已提交
1045
TEST(BlockBasedTableTest, BlockCacheTest) {
K
Kai Liu 已提交
1046
  // -- Table construction
1047
  Options options;
K
Kai Liu 已提交
1048 1049 1050
  options.create_if_missing = true;
  options.statistics = CreateDBStatistics();
  options.block_cache = NewLRUCache(1024);
1051 1052 1053 1054 1055

  // Enable the cache for index/filter blocks
  BlockBasedTableOptions table_options;
  table_options.cache_index_and_filter_blocks = true;
  options.table_factory.reset(new BlockBasedTableFactory(table_options));
K
Kai Liu 已提交
1056 1057 1058
  std::vector<std::string> keys;
  KVMap kvmap;

1059
  TableConstructor c(BytewiseComparator());
K
Kai Liu 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068
  c.Add("key", "value");
  c.Finish(options, &keys, &kvmap);

  // -- PART 1: Open with regular block cache.
  // Since block_cache is disabled, no cache activities will be involved.
  unique_ptr<Iterator> iter;

  // At first, no block will be accessed.
  {
I
Igor Canadi 已提交
1069
    BlockCacheProperties props(options.statistics.get());
K
Kai Liu 已提交
1070
    // index will be added to block cache.
K
kailiu 已提交
1071
    props.AssertEqual(
K
Kai Liu 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
        1,  // index block miss
        0,
        0,
        0
    );
  }

  // Only index block will be accessed
  {
    iter.reset(c.NewIterator());
I
Igor Canadi 已提交
1082
    BlockCacheProperties props(options.statistics.get());
K
Kai Liu 已提交
1083 1084 1085
    // NOTE: to help better highlight the "detla" of each ticker, I use
    // <last_value> + <added_value> to indicate the increment of changed
    // value; other numbers remain the same.
K
kailiu 已提交
1086
    props.AssertEqual(
K
Kai Liu 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        1,
        0 + 1,  // index block hit
        0,
        0
    );
  }

  // Only data block will be accessed
  {
    iter->SeekToFirst();
I
Igor Canadi 已提交
1097
    BlockCacheProperties props(options.statistics.get());
K
kailiu 已提交
1098
    props.AssertEqual(
K
Kai Liu 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        1,
        1,
        0 + 1,  // data block miss
        0
    );
  }

  // Data block will be in cache
  {
    iter.reset(c.NewIterator());
    iter->SeekToFirst();
I
Igor Canadi 已提交
1110
    BlockCacheProperties props(options.statistics.get());
K
kailiu 已提交
1111
    props.AssertEqual(
K
Kai Liu 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
        1,
        1 + 1,  // index block hit
        1,
        0 + 1  // data block hit
    );
  }
  // release the iterator so that the block cache can reset correctly.
  iter.reset();

  // -- PART 2: Open without block cache
  options.block_cache.reset();
1123
  options.statistics = CreateDBStatistics();  // reset the stats
K
Kai Liu 已提交
1124 1125 1126 1127 1128 1129
  c.Reopen(options);

  {
    iter.reset(c.NewIterator());
    iter->SeekToFirst();
    ASSERT_EQ("key", iter->key().ToString());
I
Igor Canadi 已提交
1130
    BlockCacheProperties props(options.statistics.get());
K
Kai Liu 已提交
1131
    // Nothing is affected at all
K
kailiu 已提交
1132
    props.AssertEqual(0, 0, 0, 0);
K
Kai Liu 已提交
1133 1134 1135 1136 1137 1138 1139 1140
  }

  // -- PART 3: Open with very small block cache
  // In this test, no block will ever get hit since the block cache is
  // too small to fit even one entry.
  options.block_cache = NewLRUCache(1);
  c.Reopen(options);
  {
I
Igor Canadi 已提交
1141
    BlockCacheProperties props(options.statistics.get());
K
kailiu 已提交
1142
    props.AssertEqual(
K
Kai Liu 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
        1,  // index block miss
        0,
        0,
        0
    );
  }


  {
    // Both index and data block get accessed.
    // It first cache index block then data block. But since the cache size
    // is only 1, index block will be purged after data block is inserted.
    iter.reset(c.NewIterator());
I
Igor Canadi 已提交
1156
    BlockCacheProperties props(options.statistics.get());
K
kailiu 已提交
1157
    props.AssertEqual(
K
Kai Liu 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
        1 + 1,  // index block miss
        0,
        0,  // data block miss
        0
    );
  }

  {
    // SeekToFirst() accesses data block. With similar reason, we expect data
    // block's cache miss.
    iter->SeekToFirst();
I
Igor Canadi 已提交
1169
    BlockCacheProperties props(options.statistics.get());
K
kailiu 已提交
1170
    props.AssertEqual(
K
Kai Liu 已提交
1171 1172 1173 1174 1175 1176 1177 1178
        2,
        0,
        0 + 1,  // data block miss
        0
    );
  }
}

K
Kai Liu 已提交
1179 1180 1181 1182 1183 1184 1185 1186
TEST(BlockBasedTableTest, BlockCacheLeak) {
  // Check that when we reopen a table we don't lose access to blocks already
  // in the cache. This test checks whether the Table actually makes use of the
  // unique ID from the file.

  Options opt;
  opt.block_size = 1024;
  opt.compression = kNoCompression;
K
Kai Liu 已提交
1187 1188 1189
  opt.block_cache =
      NewLRUCache(16 * 1024 * 1024);  // big enough so we don't ever
                                      // lose cached values.
K
Kai Liu 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

  TableConstructor c(BytewiseComparator());
  c.Add("k01", "hello");
  c.Add("k02", "hello2");
  c.Add("k03", std::string(10000, 'x'));
  c.Add("k04", std::string(200000, 'x'));
  c.Add("k05", std::string(300000, 'x'));
  c.Add("k06", "hello3");
  c.Add("k07", std::string(100000, 'x'));
  std::vector<std::string> keys;
  KVMap kvmap;
  c.Finish(opt, &keys, &kvmap);

  unique_ptr<Iterator> iter(c.NewIterator());
  iter->SeekToFirst();
  while (iter->Valid()) {
    iter->key();
    iter->value();
    iter->Next();
  }
  ASSERT_OK(iter->status());

  ASSERT_OK(c.Reopen(opt));
K
Kai Liu 已提交
1213
  for (const std::string& key : keys) {
K
Kai Liu 已提交
1214 1215 1216 1217 1218 1219 1220 1221
    ASSERT_TRUE(c.table_reader()->TEST_KeyInCache(ReadOptions(), key));
  }
}

extern const uint64_t kPlainTableMagicNumber;
TEST(PlainTableTest, BasicPlainTableProperties) {
  PlainTableFactory factory(8, 8, 0);
  StringSink sink;
K
Kai Liu 已提交
1222 1223
  std::unique_ptr<TableBuilder> builder(
      factory.GetTableBuilder(Options(), &sink, kNoCompression));
K
Kai Liu 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

  for (char c = 'a'; c <= 'z'; ++c) {
    std::string key(16, c);
    std::string value(28, c + 42);
    builder->Add(key, value);
  }
  ASSERT_OK(builder->Finish());

  StringSource source(sink.contents(), 72242, true);

  TableProperties props;
K
Kai Liu 已提交
1235 1236 1237
  auto s = ReadTableProperties(&source, sink.contents().size(),
                               kPlainTableMagicNumber, Env::Default(), nullptr,
                               &props);
K
Kai Liu 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
  ASSERT_OK(s);

  ASSERT_EQ(0ul, props.index_size);
  ASSERT_EQ(0ul, props.filter_size);
  ASSERT_EQ(16ul * 26, props.raw_key_size);
  ASSERT_EQ(28ul * 26, props.raw_value_size);
  ASSERT_EQ(26ul, props.num_entries);
  ASSERT_EQ(1ul, props.num_data_blocks);
}

TEST(GeneralTableTest, ApproximateOffsetOfPlain) {
1249
  TableConstructor c(BytewiseComparator());
J
jorlow@chromium.org 已提交
1250 1251 1252 1253 1254 1255 1256 1257 1258
  c.Add("k01", "hello");
  c.Add("k02", "hello2");
  c.Add("k03", std::string(10000, 'x'));
  c.Add("k04", std::string(200000, 'x'));
  c.Add("k05", std::string(300000, 'x'));
  c.Add("k06", "hello3");
  c.Add("k07", std::string(100000, 'x'));
  std::vector<std::string> keys;
  KVMap kvmap;
1259
  Options options;
J
jorlow@chromium.org 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
  options.block_size = 1024;
  options.compression = kNoCompression;
  c.Finish(options, &keys, &kvmap);

  ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"),      0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"),   10000,  11000));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 210000, 211000));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"),  210000, 211000));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"),  510000, 511000));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"),  510000, 511000));
S
Sanjay Ghemawat 已提交
1274
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"),  610000, 612000));
J
jorlow@chromium.org 已提交
1275 1276 1277

}

K
Kai Liu 已提交
1278
static void DoCompressionTest(CompressionType comp) {
J
jorlow@chromium.org 已提交
1279
  Random rnd(301);
1280
  TableConstructor c(BytewiseComparator());
J
jorlow@chromium.org 已提交
1281 1282 1283 1284 1285 1286 1287
  std::string tmp;
  c.Add("k01", "hello");
  c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  c.Add("k03", "hello3");
  c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  std::vector<std::string> keys;
  KVMap kvmap;
1288
  Options options;
J
jorlow@chromium.org 已提交
1289
  options.block_size = 1024;
H
heyongqiang 已提交
1290
  options.compression = comp;
J
jorlow@chromium.org 已提交
1291 1292 1293 1294 1295 1296 1297
  c.Finish(options, &keys, &kvmap);

  ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"),       0,      0));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"),    2000,   3000));
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"),    2000,   3000));
1298
  ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"),    4000,   6100));
J
jorlow@chromium.org 已提交
1299 1300
}

K
Kai Liu 已提交
1301
TEST(GeneralTableTest, ApproximateOffsetOfCompressed) {
H
heyongqiang 已提交
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
  CompressionType compression_state[2];
  int valid = 0;
  if (!SnappyCompressionSupported()) {
    fprintf(stderr, "skipping snappy compression tests\n");
  } else {
    compression_state[valid] = kSnappyCompression;
    valid++;
  }

  if (!ZlibCompressionSupported()) {
    fprintf(stderr, "skipping zlib compression tests\n");
  } else {
    compression_state[valid] = kZlibCompression;
    valid++;
  }

  for(int i =0; i < valid; i++)
  {
K
Kai Liu 已提交
1320
    DoCompressionTest(compression_state[i]);
H
heyongqiang 已提交
1321 1322 1323 1324
  }

}

1325
TEST(Harness, Randomized) {
1326
  std::vector<TestArgs> args = GenerateArgList();
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  for (unsigned int i = 0; i < args.size(); i++) {
    Init(args[i]);
    Random rnd(test::RandomSeed() + 5);
    for (int num_entries = 0; num_entries < 2000;
         num_entries += (num_entries < 50 ? 1 : 200)) {
      if ((num_entries % 10) == 0) {
        fprintf(stderr, "case %d of %d: num_entries = %d\n",
                (i + 1), int(args.size()), num_entries);
      }
      for (int e = 0; e < num_entries; e++) {
        std::string v;
        Add(test::RandomKey(&rnd, rnd.Skewed(4)),
            test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
      }
      Test(&rnd);
    }
  }
}

TEST(Harness, RandomizedLongDB) {
  Random rnd(test::RandomSeed());
  TestArgs args = { DB_TEST, false, 16, kNoCompression };
  Init(args);
  int num_entries = 100000;
  for (int e = 0; e < num_entries; e++) {
    std::string v;
    Add(test::RandomKey(&rnd, rnd.Skewed(4)),
        test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
  }
  Test(&rnd);

  // We must have created enough data to force merging
  int files = 0;
  for (int level = 0; level < db()->NumberLevels(); level++) {
    std::string value;
    char name[100];
    snprintf(name, sizeof(name), "rocksdb.num-files-at-level%d", level);
    ASSERT_TRUE(db()->GetProperty(name, &value));
    files += atoi(value.c_str());
  }
  ASSERT_GT(files, 0);
}

class MemTableTest { };

TEST(MemTableTest, Simple) {
  InternalKeyComparator cmp(BytewiseComparator());
  auto table_factory = std::make_shared<SkipListFactory>();
I
Igor Canadi 已提交
1375 1376 1377
  Options options;
  options.memtable_factory = table_factory;
  MemTable* memtable = new MemTable(cmp, options);
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
  memtable->Ref();
  WriteBatch batch;
  WriteBatchInternal::SetSequence(&batch, 100);
  batch.Put(std::string("k1"), std::string("v1"));
  batch.Put(std::string("k2"), std::string("v2"));
  batch.Put(std::string("k3"), std::string("v3"));
  batch.Put(std::string("largekey"), std::string("vlarge"));
  ASSERT_TRUE(WriteBatchInternal::InsertInto(&batch, memtable, &options).ok());

  Iterator* iter = memtable->NewIterator();
  iter->SeekToFirst();
  while (iter->Valid()) {
    fprintf(stderr, "key: '%s' -> '%s'\n",
            iter->key().ToString().c_str(),
            iter->value().ToString().c_str());
    iter->Next();
  }

  delete iter;
1397
  delete memtable->Unref();
1398 1399
}

1400 1401
// Test the empty key
TEST(Harness, SimpleEmptyKey) {
K
Kai Liu 已提交
1402 1403 1404
  auto args = GenerateArgList();
  for (const auto& arg : args) {
    Init(arg);
1405 1406 1407 1408 1409 1410 1411
    Random rnd(test::RandomSeed() + 1);
    Add("", "v");
    Test(&rnd);
  }
}

TEST(Harness, SimpleSingle) {
K
Kai Liu 已提交
1412 1413 1414
  auto args = GenerateArgList();
  for (const auto& arg : args) {
    Init(arg);
1415 1416 1417 1418 1419 1420 1421
    Random rnd(test::RandomSeed() + 2);
    Add("abc", "v");
    Test(&rnd);
  }
}

TEST(Harness, SimpleMulti) {
K
Kai Liu 已提交
1422 1423 1424
  auto args = GenerateArgList();
  for (const auto& arg : args) {
    Init(arg);
1425 1426 1427 1428 1429 1430 1431 1432 1433
    Random rnd(test::RandomSeed() + 3);
    Add("abc", "v");
    Add("abcd", "v");
    Add("ac", "v2");
    Test(&rnd);
  }
}

TEST(Harness, SimpleSpecialKey) {
K
Kai Liu 已提交
1434 1435 1436
  auto args = GenerateArgList();
  for (const auto& arg : args) {
    Init(arg);
1437 1438 1439 1440 1441
    Random rnd(test::RandomSeed() + 4);
    Add("\xff\xff", "v3");
    Test(&rnd);
  }
}
1442

1443
}  // namespace rocksdb
J
jorlow@chromium.org 已提交
1444 1445

int main(int argc, char** argv) {
1446
  return rocksdb::test::RunAllTests();
J
jorlow@chromium.org 已提交
1447
}