10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1030 lines
29 KiB

  1. // Copyright (c) 2011 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. #include "leveldb/db.h"
  5. #include "db/db_impl.h"
  6. #include "db/filename.h"
  7. #include "db/version_set.h"
  8. #include "db/write_batch_internal.h"
  9. #include "leveldb/env.h"
  10. #include "leveldb/table.h"
  11. #include "util/logging.h"
  12. #include "util/testharness.h"
  13. #include "util/testutil.h"
  14. namespace leveldb {
  15. static std::string RandomString(Random* rnd, int len) {
  16. std::string r;
  17. test::RandomString(rnd, len, &r);
  18. return r;
  19. }
  20. class DBTest {
  21. public:
  22. std::string dbname_;
  23. Env* env_;
  24. DB* db_;
  25. Options last_options_;
  26. DBTest() : env_(Env::Default()) {
  27. dbname_ = test::TmpDir() + "/db_test";
  28. DestroyDB(dbname_, Options());
  29. db_ = NULL;
  30. Reopen();
  31. }
  32. ~DBTest() {
  33. delete db_;
  34. DestroyDB(dbname_, Options());
  35. }
  36. DBImpl* dbfull() {
  37. return reinterpret_cast<DBImpl*>(db_);
  38. }
  39. void Reopen(Options* options = NULL) {
  40. ASSERT_OK(TryReopen(options));
  41. }
  42. void DestroyAndReopen(Options* options = NULL) {
  43. delete db_;
  44. db_ = NULL;
  45. DestroyDB(dbname_, Options());
  46. ASSERT_OK(TryReopen(options));
  47. }
  48. Status TryReopen(Options* options) {
  49. delete db_;
  50. db_ = NULL;
  51. Options opts;
  52. if (options != NULL) {
  53. opts = *options;
  54. } else {
  55. opts.create_if_missing = true;
  56. }
  57. last_options_ = opts;
  58. return DB::Open(opts, dbname_, &db_);
  59. }
  60. Status Put(const std::string& k, const std::string& v) {
  61. return db_->Put(WriteOptions(), k, v);
  62. }
  63. Status Delete(const std::string& k) {
  64. return db_->Delete(WriteOptions(), k);
  65. }
  66. std::string Get(const std::string& k, const Snapshot* snapshot = NULL) {
  67. ReadOptions options;
  68. options.snapshot = snapshot;
  69. std::string result;
  70. Status s = db_->Get(options, k, &result);
  71. if (s.IsNotFound()) {
  72. result = "NOT_FOUND";
  73. } else if (!s.ok()) {
  74. result = s.ToString();
  75. }
  76. return result;
  77. }
  78. std::string AllEntriesFor(const Slice& user_key) {
  79. Iterator* iter = dbfull()->TEST_NewInternalIterator();
  80. InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
  81. iter->Seek(target.Encode());
  82. std::string result;
  83. if (!iter->status().ok()) {
  84. result = iter->status().ToString();
  85. } else {
  86. result = "[ ";
  87. bool first = true;
  88. while (iter->Valid()) {
  89. ParsedInternalKey ikey;
  90. if (!ParseInternalKey(iter->key(), &ikey)) {
  91. result += "CORRUPTED";
  92. } else {
  93. if (last_options_.comparator->Compare(
  94. ikey.user_key, user_key) != 0) {
  95. break;
  96. }
  97. if (!first) {
  98. result += ", ";
  99. }
  100. first = false;
  101. switch (ikey.type) {
  102. case kTypeValue:
  103. result += iter->value().ToString();
  104. break;
  105. case kTypeDeletion:
  106. result += "DEL";
  107. break;
  108. }
  109. }
  110. iter->Next();
  111. }
  112. if (!first) {
  113. result += " ";
  114. }
  115. result += "]";
  116. }
  117. delete iter;
  118. return result;
  119. }
  120. int NumTableFilesAtLevel(int level) {
  121. std::string property;
  122. ASSERT_TRUE(
  123. db_->GetProperty("leveldb.num-files-at-level" + NumberToString(level),
  124. &property));
  125. return atoi(property.c_str());
  126. }
  127. uint64_t Size(const Slice& start, const Slice& limit) {
  128. Range r(start, limit);
  129. uint64_t size;
  130. db_->GetApproximateSizes(&r, 1, &size);
  131. return size;
  132. }
  133. void Compact(const Slice& start, const Slice& limit) {
  134. dbfull()->TEST_CompactMemTable();
  135. int max_level_with_files = 1;
  136. for (int level = 1; level < config::kNumLevels; level++) {
  137. if (NumTableFilesAtLevel(level) > 0) {
  138. max_level_with_files = level;
  139. }
  140. }
  141. for (int level = 0; level < max_level_with_files; level++) {
  142. dbfull()->TEST_CompactRange(level, "", "~");
  143. }
  144. }
  145. void DumpFileCounts(const char* label) {
  146. fprintf(stderr, "---\n%s:\n", label);
  147. fprintf(stderr, "maxoverlap: %lld\n",
  148. static_cast<long long>(
  149. dbfull()->TEST_MaxNextLevelOverlappingBytes()));
  150. for (int level = 0; level < config::kNumLevels; level++) {
  151. int num = NumTableFilesAtLevel(level);
  152. if (num > 0) {
  153. fprintf(stderr, " level %3d : %d files\n", level, num);
  154. }
  155. }
  156. }
  157. std::string IterStatus(Iterator* iter) {
  158. std::string result;
  159. if (iter->Valid()) {
  160. result = iter->key().ToString() + "->" + iter->value().ToString();
  161. } else {
  162. result = "(invalid)";
  163. }
  164. return result;
  165. }
  166. };
  167. TEST(DBTest, Empty) {
  168. ASSERT_TRUE(db_ != NULL);
  169. ASSERT_EQ("NOT_FOUND", Get("foo"));
  170. }
  171. TEST(DBTest, ReadWrite) {
  172. ASSERT_OK(Put("foo", "v1"));
  173. ASSERT_EQ("v1", Get("foo"));
  174. ASSERT_OK(Put("bar", "v2"));
  175. ASSERT_OK(Put("foo", "v3"));
  176. ASSERT_EQ("v3", Get("foo"));
  177. ASSERT_EQ("v2", Get("bar"));
  178. }
  179. TEST(DBTest, PutDeleteGet) {
  180. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  181. ASSERT_EQ("v1", Get("foo"));
  182. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  183. ASSERT_EQ("v2", Get("foo"));
  184. ASSERT_OK(db_->Delete(WriteOptions(), "foo"));
  185. ASSERT_EQ("NOT_FOUND", Get("foo"));
  186. }
  187. TEST(DBTest, IterEmpty) {
  188. Iterator* iter = db_->NewIterator(ReadOptions());
  189. iter->SeekToFirst();
  190. ASSERT_EQ(IterStatus(iter), "(invalid)");
  191. iter->SeekToLast();
  192. ASSERT_EQ(IterStatus(iter), "(invalid)");
  193. iter->Seek("foo");
  194. ASSERT_EQ(IterStatus(iter), "(invalid)");
  195. delete iter;
  196. }
  197. TEST(DBTest, IterSingle) {
  198. ASSERT_OK(Put("a", "va"));
  199. Iterator* iter = db_->NewIterator(ReadOptions());
  200. iter->SeekToFirst();
  201. ASSERT_EQ(IterStatus(iter), "a->va");
  202. iter->Next();
  203. ASSERT_EQ(IterStatus(iter), "(invalid)");
  204. iter->SeekToFirst();
  205. ASSERT_EQ(IterStatus(iter), "a->va");
  206. iter->Prev();
  207. ASSERT_EQ(IterStatus(iter), "(invalid)");
  208. iter->SeekToLast();
  209. ASSERT_EQ(IterStatus(iter), "a->va");
  210. iter->Next();
  211. ASSERT_EQ(IterStatus(iter), "(invalid)");
  212. iter->SeekToLast();
  213. ASSERT_EQ(IterStatus(iter), "a->va");
  214. iter->Prev();
  215. ASSERT_EQ(IterStatus(iter), "(invalid)");
  216. iter->Seek("");
  217. ASSERT_EQ(IterStatus(iter), "a->va");
  218. iter->Next();
  219. ASSERT_EQ(IterStatus(iter), "(invalid)");
  220. iter->Seek("a");
  221. ASSERT_EQ(IterStatus(iter), "a->va");
  222. iter->Next();
  223. ASSERT_EQ(IterStatus(iter), "(invalid)");
  224. iter->Seek("b");
  225. ASSERT_EQ(IterStatus(iter), "(invalid)");
  226. delete iter;
  227. }
  228. TEST(DBTest, IterMulti) {
  229. ASSERT_OK(Put("a", "va"));
  230. ASSERT_OK(Put("b", "vb"));
  231. ASSERT_OK(Put("c", "vc"));
  232. Iterator* iter = db_->NewIterator(ReadOptions());
  233. iter->SeekToFirst();
  234. ASSERT_EQ(IterStatus(iter), "a->va");
  235. iter->Next();
  236. ASSERT_EQ(IterStatus(iter), "b->vb");
  237. iter->Next();
  238. ASSERT_EQ(IterStatus(iter), "c->vc");
  239. iter->Next();
  240. ASSERT_EQ(IterStatus(iter), "(invalid)");
  241. iter->SeekToFirst();
  242. ASSERT_EQ(IterStatus(iter), "a->va");
  243. iter->Prev();
  244. ASSERT_EQ(IterStatus(iter), "(invalid)");
  245. iter->SeekToLast();
  246. ASSERT_EQ(IterStatus(iter), "c->vc");
  247. iter->Prev();
  248. ASSERT_EQ(IterStatus(iter), "b->vb");
  249. iter->Prev();
  250. ASSERT_EQ(IterStatus(iter), "a->va");
  251. iter->Prev();
  252. ASSERT_EQ(IterStatus(iter), "(invalid)");
  253. iter->SeekToLast();
  254. ASSERT_EQ(IterStatus(iter), "c->vc");
  255. iter->Next();
  256. ASSERT_EQ(IterStatus(iter), "(invalid)");
  257. iter->Seek("");
  258. ASSERT_EQ(IterStatus(iter), "a->va");
  259. iter->Seek("a");
  260. ASSERT_EQ(IterStatus(iter), "a->va");
  261. iter->Seek("ax");
  262. ASSERT_EQ(IterStatus(iter), "b->vb");
  263. iter->Seek("b");
  264. ASSERT_EQ(IterStatus(iter), "b->vb");
  265. iter->Seek("z");
  266. ASSERT_EQ(IterStatus(iter), "(invalid)");
  267. // Switch from reverse to forward
  268. iter->SeekToLast();
  269. iter->Prev();
  270. iter->Prev();
  271. iter->Next();
  272. ASSERT_EQ(IterStatus(iter), "b->vb");
  273. // Switch from forward to reverse
  274. iter->SeekToFirst();
  275. iter->Next();
  276. iter->Next();
  277. iter->Prev();
  278. ASSERT_EQ(IterStatus(iter), "b->vb");
  279. // Make sure iter stays at snapshot
  280. ASSERT_OK(Put("a", "va2"));
  281. ASSERT_OK(Put("a2", "va3"));
  282. ASSERT_OK(Put("b", "vb2"));
  283. ASSERT_OK(Put("c", "vc2"));
  284. ASSERT_OK(Delete("b"));
  285. iter->SeekToFirst();
  286. ASSERT_EQ(IterStatus(iter), "a->va");
  287. iter->Next();
  288. ASSERT_EQ(IterStatus(iter), "b->vb");
  289. iter->Next();
  290. ASSERT_EQ(IterStatus(iter), "c->vc");
  291. iter->Next();
  292. ASSERT_EQ(IterStatus(iter), "(invalid)");
  293. iter->SeekToLast();
  294. ASSERT_EQ(IterStatus(iter), "c->vc");
  295. iter->Prev();
  296. ASSERT_EQ(IterStatus(iter), "b->vb");
  297. iter->Prev();
  298. ASSERT_EQ(IterStatus(iter), "a->va");
  299. iter->Prev();
  300. ASSERT_EQ(IterStatus(iter), "(invalid)");
  301. delete iter;
  302. }
  303. TEST(DBTest, IterSmallAndLargeMix) {
  304. ASSERT_OK(Put("a", "va"));
  305. ASSERT_OK(Put("b", std::string(100000, 'b')));
  306. ASSERT_OK(Put("c", "vc"));
  307. ASSERT_OK(Put("d", std::string(100000, 'd')));
  308. ASSERT_OK(Put("e", std::string(100000, 'e')));
  309. Iterator* iter = db_->NewIterator(ReadOptions());
  310. iter->SeekToFirst();
  311. ASSERT_EQ(IterStatus(iter), "a->va");
  312. iter->Next();
  313. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  314. iter->Next();
  315. ASSERT_EQ(IterStatus(iter), "c->vc");
  316. iter->Next();
  317. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  318. iter->Next();
  319. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  320. iter->Next();
  321. ASSERT_EQ(IterStatus(iter), "(invalid)");
  322. iter->SeekToLast();
  323. ASSERT_EQ(IterStatus(iter), "e->" + std::string(100000, 'e'));
  324. iter->Prev();
  325. ASSERT_EQ(IterStatus(iter), "d->" + std::string(100000, 'd'));
  326. iter->Prev();
  327. ASSERT_EQ(IterStatus(iter), "c->vc");
  328. iter->Prev();
  329. ASSERT_EQ(IterStatus(iter), "b->" + std::string(100000, 'b'));
  330. iter->Prev();
  331. ASSERT_EQ(IterStatus(iter), "a->va");
  332. iter->Prev();
  333. ASSERT_EQ(IterStatus(iter), "(invalid)");
  334. delete iter;
  335. }
  336. TEST(DBTest, Recover) {
  337. ASSERT_OK(Put("foo", "v1"));
  338. ASSERT_OK(Put("baz", "v5"));
  339. Reopen();
  340. ASSERT_EQ("v1", Get("foo"));
  341. ASSERT_EQ("v1", Get("foo"));
  342. ASSERT_EQ("v5", Get("baz"));
  343. ASSERT_OK(Put("bar", "v2"));
  344. ASSERT_OK(Put("foo", "v3"));
  345. Reopen();
  346. ASSERT_EQ("v3", Get("foo"));
  347. ASSERT_OK(Put("foo", "v4"));
  348. ASSERT_EQ("v4", Get("foo"));
  349. ASSERT_EQ("v2", Get("bar"));
  350. ASSERT_EQ("v5", Get("baz"));
  351. }
  352. TEST(DBTest, RecoveryWithEmptyLog) {
  353. ASSERT_OK(Put("foo", "v1"));
  354. ASSERT_OK(Put("foo", "v2"));
  355. Reopen();
  356. Reopen();
  357. ASSERT_OK(Put("foo", "v3"));
  358. Reopen();
  359. ASSERT_EQ("v3", Get("foo"));
  360. }
  361. static std::string Key(int i) {
  362. char buf[100];
  363. snprintf(buf, sizeof(buf), "key%06d", i);
  364. return std::string(buf);
  365. }
  366. TEST(DBTest, MinorCompactionsHappen) {
  367. Options options;
  368. options.write_buffer_size = 10000;
  369. Reopen(&options);
  370. const int N = 500;
  371. int starting_num_tables = NumTableFilesAtLevel(0);
  372. for (int i = 0; i < N; i++) {
  373. ASSERT_OK(Put(Key(i), Key(i) + std::string(1000, 'v')));
  374. }
  375. int ending_num_tables = NumTableFilesAtLevel(0);
  376. ASSERT_GT(ending_num_tables, starting_num_tables);
  377. for (int i = 0; i < N; i++) {
  378. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  379. }
  380. Reopen();
  381. for (int i = 0; i < N; i++) {
  382. ASSERT_EQ(Key(i) + std::string(1000, 'v'), Get(Key(i)));
  383. }
  384. }
  385. TEST(DBTest, RecoverWithLargeLog) {
  386. {
  387. Options options;
  388. Reopen(&options);
  389. ASSERT_OK(Put("big1", std::string(200000, '1')));
  390. ASSERT_OK(Put("big2", std::string(200000, '2')));
  391. ASSERT_OK(Put("small3", std::string(10, '3')));
  392. ASSERT_OK(Put("small4", std::string(10, '4')));
  393. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  394. }
  395. // Make sure that if we re-open with a small write buffer size that
  396. // we flush table files in the middle of a large log file.
  397. Options options;
  398. options.write_buffer_size = 100000;
  399. Reopen(&options);
  400. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  401. ASSERT_EQ(std::string(200000, '1'), Get("big1"));
  402. ASSERT_EQ(std::string(200000, '2'), Get("big2"));
  403. ASSERT_EQ(std::string(10, '3'), Get("small3"));
  404. ASSERT_EQ(std::string(10, '4'), Get("small4"));
  405. ASSERT_GT(NumTableFilesAtLevel(0), 1);
  406. }
  407. TEST(DBTest, CompactionsGenerateMultipleFiles) {
  408. Options options;
  409. options.write_buffer_size = 100000000; // Large write buffer
  410. Reopen(&options);
  411. Random rnd(301);
  412. // Write 8MB (80 values, each 100K)
  413. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  414. std::vector<std::string> values;
  415. for (int i = 0; i < 80; i++) {
  416. values.push_back(RandomString(&rnd, 100000));
  417. ASSERT_OK(Put(Key(i), values[i]));
  418. }
  419. // Reopening moves updates to level-0
  420. Reopen(&options);
  421. dbfull()->TEST_CompactRange(0, "", Key(100000));
  422. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  423. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  424. for (int i = 0; i < 80; i++) {
  425. ASSERT_EQ(Get(Key(i)), values[i]);
  426. }
  427. }
  428. TEST(DBTest, SparseMerge) {
  429. Options options;
  430. options.compression = kNoCompression;
  431. Reopen(&options);
  432. // Suppose there is:
  433. // small amount of data with prefix A
  434. // large amount of data with prefix B
  435. // small amount of data with prefix C
  436. // and that recent updates have made small changes to all three prefixes.
  437. // Check that we do not do a compaction that merges all of B in one shot.
  438. const std::string value(1000, 'x');
  439. Put("A", "va");
  440. // Write approximately 100MB of "B" values
  441. for (int i = 0; i < 100000; i++) {
  442. char key[100];
  443. snprintf(key, sizeof(key), "B%010d", i);
  444. Put(key, value);
  445. }
  446. Put("C", "vc");
  447. Compact("", "z");
  448. // Make sparse update
  449. Put("A", "va2");
  450. Put("B100", "bvalue2");
  451. Put("C", "vc2");
  452. dbfull()->TEST_CompactMemTable();
  453. // Compactions should not cause us to create a situation where
  454. // a file overlaps too much data at the next level.
  455. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  456. dbfull()->TEST_CompactRange(0, "", "z");
  457. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  458. dbfull()->TEST_CompactRange(1, "", "z");
  459. ASSERT_LE(dbfull()->TEST_MaxNextLevelOverlappingBytes(), 20*1048576);
  460. }
  461. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  462. bool result = (val >= low) && (val <= high);
  463. if (!result) {
  464. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  465. (unsigned long long)(val),
  466. (unsigned long long)(low),
  467. (unsigned long long)(high));
  468. }
  469. return result;
  470. }
  471. TEST(DBTest, ApproximateSizes) {
  472. Options options;
  473. options.write_buffer_size = 100000000; // Large write buffer
  474. options.compression = kNoCompression;
  475. DestroyAndReopen();
  476. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  477. Reopen(&options);
  478. ASSERT_TRUE(Between(Size("", "xyz"), 0, 0));
  479. // Write 8MB (80 values, each 100K)
  480. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  481. const int N = 80;
  482. Random rnd(301);
  483. for (int i = 0; i < N; i++) {
  484. ASSERT_OK(Put(Key(i), RandomString(&rnd, 100000)));
  485. }
  486. // 0 because GetApproximateSizes() does not account for memtable space
  487. ASSERT_TRUE(Between(Size("", Key(50)), 0, 0));
  488. // Check sizes across recovery by reopening a few times
  489. for (int run = 0; run < 3; run++) {
  490. Reopen(&options);
  491. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  492. for (int i = 0; i < N; i += 10) {
  493. ASSERT_TRUE(Between(Size("", Key(i)), 100000*i, 100000*i + 10000));
  494. ASSERT_TRUE(Between(Size("", Key(i)+".suffix"),
  495. 100000 * (i+1), 100000 * (i+1) + 10000));
  496. ASSERT_TRUE(Between(Size(Key(i), Key(i+10)),
  497. 100000 * 10, 100000 * 10 + 10000));
  498. }
  499. ASSERT_TRUE(Between(Size("", Key(50)), 5000000, 5010000));
  500. ASSERT_TRUE(Between(Size("", Key(50)+".suffix"), 5100000, 5110000));
  501. dbfull()->TEST_CompactRange(0,
  502. Key(compact_start),
  503. Key(compact_start + 9));
  504. }
  505. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  506. ASSERT_GT(NumTableFilesAtLevel(1), 0);
  507. }
  508. }
  509. TEST(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  510. Options options;
  511. options.compression = kNoCompression;
  512. Reopen();
  513. Random rnd(301);
  514. std::string big1 = RandomString(&rnd, 100000);
  515. ASSERT_OK(Put(Key(0), RandomString(&rnd, 10000)));
  516. ASSERT_OK(Put(Key(1), RandomString(&rnd, 10000)));
  517. ASSERT_OK(Put(Key(2), big1));
  518. ASSERT_OK(Put(Key(3), RandomString(&rnd, 10000)));
  519. ASSERT_OK(Put(Key(4), big1));
  520. ASSERT_OK(Put(Key(5), RandomString(&rnd, 10000)));
  521. ASSERT_OK(Put(Key(6), RandomString(&rnd, 300000)));
  522. ASSERT_OK(Put(Key(7), RandomString(&rnd, 10000)));
  523. // Check sizes across recovery by reopening a few times
  524. for (int run = 0; run < 3; run++) {
  525. Reopen(&options);
  526. ASSERT_TRUE(Between(Size("", Key(0)), 0, 0));
  527. ASSERT_TRUE(Between(Size("", Key(1)), 10000, 11000));
  528. ASSERT_TRUE(Between(Size("", Key(2)), 20000, 21000));
  529. ASSERT_TRUE(Between(Size("", Key(3)), 120000, 121000));
  530. ASSERT_TRUE(Between(Size("", Key(4)), 130000, 131000));
  531. ASSERT_TRUE(Between(Size("", Key(5)), 230000, 231000));
  532. ASSERT_TRUE(Between(Size("", Key(6)), 240000, 241000));
  533. ASSERT_TRUE(Between(Size("", Key(7)), 540000, 541000));
  534. ASSERT_TRUE(Between(Size("", Key(8)), 550000, 551000));
  535. ASSERT_TRUE(Between(Size(Key(3), Key(5)), 110000, 111000));
  536. dbfull()->TEST_CompactRange(0, Key(0), Key(100));
  537. }
  538. }
  539. TEST(DBTest, IteratorPinsRef) {
  540. Put("foo", "hello");
  541. // Get iterator that will yield the current contents of the DB.
  542. Iterator* iter = db_->NewIterator(ReadOptions());
  543. // Write to force compactions
  544. Put("foo", "newvalue1");
  545. for (int i = 0; i < 100; i++) {
  546. ASSERT_OK(Put(Key(i), Key(i) + std::string(100000, 'v'))); // 100K values
  547. }
  548. Put("foo", "newvalue2");
  549. iter->SeekToFirst();
  550. ASSERT_TRUE(iter->Valid());
  551. ASSERT_EQ("foo", iter->key().ToString());
  552. ASSERT_EQ("hello", iter->value().ToString());
  553. iter->Next();
  554. ASSERT_TRUE(!iter->Valid());
  555. delete iter;
  556. }
  557. TEST(DBTest, Snapshot) {
  558. Put("foo", "v1");
  559. const Snapshot* s1 = db_->GetSnapshot();
  560. Put("foo", "v2");
  561. const Snapshot* s2 = db_->GetSnapshot();
  562. Put("foo", "v3");
  563. const Snapshot* s3 = db_->GetSnapshot();
  564. Put("foo", "v4");
  565. ASSERT_EQ("v1", Get("foo", s1));
  566. ASSERT_EQ("v2", Get("foo", s2));
  567. ASSERT_EQ("v3", Get("foo", s3));
  568. ASSERT_EQ("v4", Get("foo"));
  569. db_->ReleaseSnapshot(s3);
  570. ASSERT_EQ("v1", Get("foo", s1));
  571. ASSERT_EQ("v2", Get("foo", s2));
  572. ASSERT_EQ("v4", Get("foo"));
  573. db_->ReleaseSnapshot(s1);
  574. ASSERT_EQ("v2", Get("foo", s2));
  575. ASSERT_EQ("v4", Get("foo"));
  576. db_->ReleaseSnapshot(s2);
  577. ASSERT_EQ("v4", Get("foo"));
  578. }
  579. TEST(DBTest, HiddenValuesAreRemoved) {
  580. Random rnd(301);
  581. std::string big = RandomString(&rnd, 50000);
  582. Put("foo", big);
  583. Put("pastfoo", "v");
  584. const Snapshot* snapshot = db_->GetSnapshot();
  585. Put("foo", "tiny");
  586. Put("pastfoo2", "v2"); // Advance sequence number one more
  587. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  588. ASSERT_GT(NumTableFilesAtLevel(0), 0);
  589. ASSERT_EQ(big, Get("foo", snapshot));
  590. ASSERT_TRUE(Between(Size("", "pastfoo"), 50000, 60000));
  591. db_->ReleaseSnapshot(snapshot);
  592. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny, " + big + " ]");
  593. dbfull()->TEST_CompactRange(0, "", "x");
  594. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  595. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  596. ASSERT_GE(NumTableFilesAtLevel(1), 1);
  597. dbfull()->TEST_CompactRange(1, "", "x");
  598. ASSERT_EQ(AllEntriesFor("foo"), "[ tiny ]");
  599. ASSERT_TRUE(Between(Size("", "pastfoo"), 0, 1000));
  600. }
  601. TEST(DBTest, DeletionMarkers1) {
  602. Put("foo", "v1");
  603. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  604. dbfull()->TEST_CompactRange(0, "", "z");
  605. dbfull()->TEST_CompactRange(1, "", "z");
  606. ASSERT_EQ(NumTableFilesAtLevel(2), 1); // foo => v1 is now in level 2 file
  607. Delete("foo");
  608. Put("foo", "v2");
  609. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  610. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  611. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, DEL, v1 ]");
  612. dbfull()->TEST_CompactRange(0, "", "z");
  613. // DEL eliminated, but v1 remains because we aren't compacting that level
  614. // (DEL can be eliminated because v2 hides v1).
  615. ASSERT_EQ(AllEntriesFor("foo"), "[ v2, v1 ]");
  616. dbfull()->TEST_CompactRange(1, "", "z");
  617. // Merging L1 w/ L2, so we are the base level for "foo", so DEL is removed.
  618. // (as is v1).
  619. ASSERT_EQ(AllEntriesFor("foo"), "[ v2 ]");
  620. }
  621. TEST(DBTest, DeletionMarkers2) {
  622. Put("foo", "v1");
  623. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  624. dbfull()->TEST_CompactRange(0, "", "z");
  625. dbfull()->TEST_CompactRange(1, "", "z");
  626. ASSERT_EQ(NumTableFilesAtLevel(2), 1); // foo => v1 is now in level 2 file
  627. Delete("foo");
  628. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  629. ASSERT_OK(dbfull()->TEST_CompactMemTable());
  630. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  631. dbfull()->TEST_CompactRange(0, "", "z");
  632. // DEL kept: L2 file overlaps
  633. ASSERT_EQ(AllEntriesFor("foo"), "[ DEL, v1 ]");
  634. dbfull()->TEST_CompactRange(1, "", "z");
  635. // Merging L1 w/ L2, so we are the base level for "foo", so DEL is removed.
  636. // (as is v1).
  637. ASSERT_EQ(AllEntriesFor("foo"), "[ ]");
  638. }
  639. TEST(DBTest, ComparatorCheck) {
  640. class NewComparator : public Comparator {
  641. public:
  642. virtual const char* Name() const { return "leveldb.NewComparator"; }
  643. virtual int Compare(const Slice& a, const Slice& b) const {
  644. return BytewiseComparator()->Compare(a, b);
  645. }
  646. virtual void FindShortestSeparator(std::string* s, const Slice& l) const {
  647. BytewiseComparator()->FindShortestSeparator(s, l);
  648. }
  649. virtual void FindShortSuccessor(std::string* key) const {
  650. BytewiseComparator()->FindShortSuccessor(key);
  651. }
  652. };
  653. NewComparator cmp;
  654. Options new_options;
  655. new_options.comparator = &cmp;
  656. Status s = TryReopen(&new_options);
  657. ASSERT_TRUE(!s.ok());
  658. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  659. << s.ToString();
  660. }
  661. TEST(DBTest, DBOpen_Options) {
  662. std::string dbname = test::TmpDir() + "/db_options_test";
  663. DestroyDB(dbname, Options());
  664. // Does not exist, and create_if_missing == false: error
  665. DB* db = NULL;
  666. Options opts;
  667. opts.create_if_missing = false;
  668. Status s = DB::Open(opts, dbname, &db);
  669. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != NULL);
  670. ASSERT_TRUE(db == NULL);
  671. // Does not exist, and create_if_missing == true: OK
  672. opts.create_if_missing = true;
  673. s = DB::Open(opts, dbname, &db);
  674. ASSERT_OK(s);
  675. ASSERT_TRUE(db != NULL);
  676. delete db;
  677. db = NULL;
  678. // Does exist, and error_if_exists == true: error
  679. opts.create_if_missing = false;
  680. opts.error_if_exists = true;
  681. s = DB::Open(opts, dbname, &db);
  682. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != NULL);
  683. ASSERT_TRUE(db == NULL);
  684. // Does exist, and error_if_exists == false: OK
  685. opts.create_if_missing = true;
  686. opts.error_if_exists = false;
  687. s = DB::Open(opts, dbname, &db);
  688. ASSERT_OK(s);
  689. ASSERT_TRUE(db != NULL);
  690. delete db;
  691. db = NULL;
  692. }
  693. class ModelDB: public DB {
  694. public:
  695. explicit ModelDB(const Options& options): options_(options) { }
  696. ~ModelDB() { }
  697. virtual Status Put(const WriteOptions& o, const Slice& k, const Slice& v) {
  698. return DB::Put(o, k, v);
  699. }
  700. virtual Status Delete(const WriteOptions& o, const Slice& key) {
  701. return DB::Delete(o, key);
  702. }
  703. virtual Status Get(const ReadOptions& options,
  704. const Slice& key, std::string* value) {
  705. assert(false); // Not implemented
  706. return Status::NotFound(key);
  707. }
  708. virtual Iterator* NewIterator(const ReadOptions& options) {
  709. if (options.snapshot == NULL) {
  710. KVMap* saved = new KVMap;
  711. *saved = map_;
  712. return new ModelIter(saved, true);
  713. } else {
  714. const KVMap* snapshot_state =
  715. reinterpret_cast<const KVMap*>(options.snapshot->number_);
  716. return new ModelIter(snapshot_state, false);
  717. }
  718. }
  719. virtual const Snapshot* GetSnapshot() {
  720. KVMap* saved = new KVMap;
  721. *saved = map_;
  722. return snapshots_.New(
  723. reinterpret_cast<SequenceNumber>(saved));
  724. }
  725. virtual void ReleaseSnapshot(const Snapshot* snapshot) {
  726. const KVMap* saved = reinterpret_cast<const KVMap*>(snapshot->number_);
  727. delete saved;
  728. snapshots_.Delete(snapshot);
  729. }
  730. virtual Status Write(const WriteOptions& options, WriteBatch* batch) {
  731. assert(options.post_write_snapshot == NULL); // Not supported
  732. for (WriteBatchInternal::Iterator it(*batch); !it.Done(); it.Next()) {
  733. switch (it.op()) {
  734. case kTypeValue:
  735. map_[it.key().ToString()] = it.value().ToString();
  736. break;
  737. case kTypeDeletion:
  738. map_.erase(it.key().ToString());
  739. break;
  740. }
  741. }
  742. return Status::OK();
  743. }
  744. virtual bool GetProperty(const Slice& property, std::string* value) {
  745. return false;
  746. }
  747. virtual void GetApproximateSizes(const Range* r, int n, uint64_t* sizes) {
  748. for (int i = 0; i < n; i++) {
  749. sizes[i] = 0;
  750. }
  751. }
  752. private:
  753. typedef std::map<std::string, std::string> KVMap;
  754. class ModelIter: public Iterator {
  755. public:
  756. ModelIter(const KVMap* map, bool owned)
  757. : map_(map), owned_(owned), iter_(map_->end()) {
  758. }
  759. ~ModelIter() {
  760. if (owned_) delete map_;
  761. }
  762. virtual bool Valid() const { return iter_ != map_->end(); }
  763. virtual void SeekToFirst() { iter_ = map_->begin(); }
  764. virtual void SeekToLast() {
  765. if (map_->empty()) {
  766. iter_ = map_->end();
  767. } else {
  768. iter_ = map_->find(map_->rbegin()->first);
  769. }
  770. }
  771. virtual void Seek(const Slice& k) {
  772. iter_ = map_->lower_bound(k.ToString());
  773. }
  774. virtual void Next() { ++iter_; }
  775. virtual void Prev() { --iter_; }
  776. virtual Slice key() const { return iter_->first; }
  777. virtual Slice value() const { return iter_->second; }
  778. virtual Status status() const { return Status::OK(); }
  779. private:
  780. const KVMap* const map_;
  781. const bool owned_; // Do we own map_
  782. KVMap::const_iterator iter_;
  783. };
  784. const Options options_;
  785. KVMap map_;
  786. SnapshotList snapshots_;
  787. };
  788. static std::string RandomKey(Random* rnd) {
  789. int len = (rnd->OneIn(3)
  790. ? 1 // Short sometimes to encourage collisions
  791. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  792. return test::RandomKey(rnd, len);
  793. }
  794. static bool CompareIterators(int step,
  795. DB* model,
  796. DB* db,
  797. const Snapshot* model_snap,
  798. const Snapshot* db_snap) {
  799. ReadOptions options;
  800. options.snapshot = model_snap;
  801. Iterator* miter = model->NewIterator(options);
  802. options.snapshot = db_snap;
  803. Iterator* dbiter = db->NewIterator(options);
  804. bool ok = true;
  805. int count = 0;
  806. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  807. ok && miter->Valid() && dbiter->Valid();
  808. miter->Next(), dbiter->Next()) {
  809. count++;
  810. if (miter->key().compare(dbiter->key()) != 0) {
  811. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n",
  812. step,
  813. EscapeString(miter->key()).c_str(),
  814. EscapeString(dbiter->key()).c_str());
  815. ok = false;
  816. break;
  817. }
  818. if (miter->value().compare(dbiter->value()) != 0) {
  819. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  820. step,
  821. EscapeString(miter->key()).c_str(),
  822. EscapeString(miter->value()).c_str(),
  823. EscapeString(miter->value()).c_str());
  824. ok = false;
  825. }
  826. }
  827. if (ok) {
  828. if (miter->Valid() != dbiter->Valid()) {
  829. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  830. step, miter->Valid(), dbiter->Valid());
  831. ok = false;
  832. }
  833. }
  834. fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
  835. delete miter;
  836. delete dbiter;
  837. return ok;
  838. }
  839. TEST(DBTest, Randomized) {
  840. Random rnd(test::RandomSeed());
  841. ModelDB model(last_options_);
  842. const int N = 10000;
  843. const Snapshot* model_snap = NULL;
  844. const Snapshot* db_snap = NULL;
  845. std::string k, v;
  846. for (int step = 0; step < N; step++) {
  847. if (step % 100 == 0) {
  848. fprintf(stderr, "Step %d of %d\n", step, N);
  849. }
  850. int p = rnd.Uniform(100);
  851. if (p < 45) { // Put
  852. k = RandomKey(&rnd);
  853. v = RandomString(&rnd,
  854. rnd.OneIn(20)
  855. ? 100 + rnd.Uniform(100)
  856. : rnd.Uniform(8));
  857. ASSERT_OK(model.Put(WriteOptions(), k, v));
  858. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  859. } else if (p < 90) { // Delete
  860. k = RandomKey(&rnd);
  861. ASSERT_OK(model.Delete(WriteOptions(), k));
  862. ASSERT_OK(db_->Delete(WriteOptions(), k));
  863. } else { // Multi-element batch
  864. WriteBatch b;
  865. const int num = rnd.Uniform(8);
  866. for (int i = 0; i < num; i++) {
  867. if (i == 0 || !rnd.OneIn(10)) {
  868. k = RandomKey(&rnd);
  869. } else {
  870. // Periodically re-use the same key from the previous iter, so
  871. // we have multiple entries in the write batch for the same key
  872. }
  873. if (rnd.OneIn(2)) {
  874. v = RandomString(&rnd, rnd.Uniform(10));
  875. b.Put(k, v);
  876. } else {
  877. b.Delete(k);
  878. }
  879. }
  880. ASSERT_OK(model.Write(WriteOptions(), &b));
  881. ASSERT_OK(db_->Write(WriteOptions(), &b));
  882. }
  883. if ((step % 100) == 0) {
  884. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  885. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  886. // Save a snapshot from each DB this time that we'll use next
  887. // time we compare things, to make sure the current state is
  888. // preserved with the snapshot
  889. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  890. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  891. Reopen();
  892. ASSERT_TRUE(CompareIterators(step, &model, db_, NULL, NULL));
  893. model_snap = model.GetSnapshot();
  894. db_snap = db_->GetSnapshot();
  895. }
  896. }
  897. if (model_snap != NULL) model.ReleaseSnapshot(model_snap);
  898. if (db_snap != NULL) db_->ReleaseSnapshot(db_snap);
  899. }
  900. }
  901. int main(int argc, char** argv) {
  902. return leveldb::test::RunAllTests();
  903. }