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 "gtest/gtest.h"
11 #include "leveldb/db.h"
12 #include "leveldb/write_batch.h"
13 #include "util/testutil.h"
14
15 namespace {
16
17 const int kNumKeys = 1100000;
18
Key1(int i)19 std::string Key1(int i) {
20 char buf[100];
21 std::snprintf(buf, sizeof(buf), "my_key_%d", i);
22 return buf;
23 }
24
Key2(int i)25 std::string Key2(int i) { return Key1(i) + "_xxx"; }
26
TEST(Issue178,Test)27 TEST(Issue178, Test) {
28 // Get rid of any state from an old run.
29 std::string dbpath = testing::TempDir() + "leveldb_cbug_test";
30 DestroyDB(dbpath, leveldb::Options());
31
32 // Open database. Disable compression since it affects the creation
33 // of layers and the code below is trying to test against a very
34 // specific scenario.
35 leveldb::DB* db;
36 leveldb::Options db_options;
37 db_options.create_if_missing = true;
38 db_options.compression = leveldb::kNoCompression;
39 ASSERT_LEVELDB_OK(leveldb::DB::Open(db_options, dbpath, &db));
40
41 // create first key range
42 leveldb::WriteBatch batch;
43 for (size_t i = 0; i < kNumKeys; i++) {
44 batch.Put(Key1(i), "value for range 1 key");
45 }
46 ASSERT_LEVELDB_OK(db->Write(leveldb::WriteOptions(), &batch));
47
48 // create second key range
49 batch.Clear();
50 for (size_t i = 0; i < kNumKeys; i++) {
51 batch.Put(Key2(i), "value for range 2 key");
52 }
53 ASSERT_LEVELDB_OK(db->Write(leveldb::WriteOptions(), &batch));
54
55 // delete second key range
56 batch.Clear();
57 for (size_t i = 0; i < kNumKeys; i++) {
58 batch.Delete(Key2(i));
59 }
60 ASSERT_LEVELDB_OK(db->Write(leveldb::WriteOptions(), &batch));
61
62 // compact database
63 std::string start_key = Key1(0);
64 std::string end_key = Key1(kNumKeys - 1);
65 leveldb::Slice least(start_key.data(), start_key.size());
66 leveldb::Slice greatest(end_key.data(), end_key.size());
67
68 // commenting out the line below causes the example to work correctly
69 db->CompactRange(&least, &greatest);
70
71 // count the keys
72 leveldb::Iterator* iter = db->NewIterator(leveldb::ReadOptions());
73 size_t num_keys = 0;
74 for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
75 num_keys++;
76 }
77 delete iter;
78 ASSERT_EQ(kNumKeys, num_keys) << "Bad number of keys";
79
80 // close database
81 delete db;
82 DestroyDB(dbpath, leveldb::Options());
83 }
84
85 } // anonymous namespace
86
main(int argc,char ** argv)87 int main(int argc, char** argv) {
88 testing::InitGoogleTest(&argc, argv);
89 return RUN_ALL_TESTS();
90 }
91