/ src / leveldb / issues / issue178_test.cc
issue178_test.cc
 1  // Copyright (c) 2013 The LevelDB Authors. All rights reserved.
 2  // Use of this source code is governed by a BSD-style license that can be
 3  // found in the LICENSE file. See the AUTHORS file for names of contributors.
 4  
 5  // Test for issue 178: a manual compaction causes deleted data to reappear.
 6  #include <cstdlib>
 7  #include <iostream>
 8  #include <sstream>
 9  
10  #include "leveldb/db.h"
11  #include "leveldb/write_batch.h"
12  #include "util/testharness.h"
13  
14  namespace {
15  
16  const int kNumKeys = 1100000;
17  
18  std::string Key1(int i) {
19    char buf[100];
20    snprintf(buf, sizeof(buf), "my_key_%d", i);
21    return buf;
22  }
23  
24  std::string Key2(int i) { return Key1(i) + "_xxx"; }
25  
26  class Issue178 {};
27  
28  TEST(Issue178, Test) {
29    // Get rid of any state from an old run.
30    std::string dbpath = leveldb::test::TmpDir() + "/leveldb_cbug_test";
31    DestroyDB(dbpath, leveldb::Options());
32  
33    // Open database.  Disable compression since it affects the creation
34    // of layers and the code below is trying to test against a very
35    // specific scenario.
36    leveldb::DB* db;
37    leveldb::Options db_options;
38    db_options.create_if_missing = true;
39    db_options.compression = leveldb::kNoCompression;
40    ASSERT_OK(leveldb::DB::Open(db_options, dbpath, &db));
41  
42    // create first key range
43    leveldb::WriteBatch batch;
44    for (size_t i = 0; i < kNumKeys; i++) {
45      batch.Put(Key1(i), "value for range 1 key");
46    }
47    ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));
48  
49    // create second key range
50    batch.Clear();
51    for (size_t i = 0; i < kNumKeys; i++) {
52      batch.Put(Key2(i), "value for range 2 key");
53    }
54    ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));
55  
56    // delete second key range
57    batch.Clear();
58    for (size_t i = 0; i < kNumKeys; i++) {
59      batch.Delete(Key2(i));
60    }
61    ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));
62  
63    // compact database
64    std::string start_key = Key1(0);
65    std::string end_key = Key1(kNumKeys - 1);
66    leveldb::Slice least(start_key.data(), start_key.size());
67    leveldb::Slice greatest(end_key.data(), end_key.size());
68  
69    // commenting out the line below causes the example to work correctly
70    db->CompactRange(&least, &greatest);
71  
72    // count the keys
73    leveldb::Iterator* iter = db->NewIterator(leveldb::ReadOptions());
74    size_t num_keys = 0;
75    for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
76      num_keys++;
77    }
78    delete iter;
79    ASSERT_EQ(kNumKeys, num_keys) << "Bad number of keys";
80  
81    // close database
82    delete db;
83    DestroyDB(dbpath, leveldb::Options());
84  }
85  
86  }  // anonymous namespace
87  
88  int main(int argc, char** argv) { return leveldb::test::RunAllTests(); }