Merge pull request #3637
[VerusCoin.git] / src / leveldbwrapper.cpp
1 // Copyright (c) 2012-2014 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include "leveldbwrapper.h"
6
7 #include "util.h"
8
9 #include <boost/filesystem.hpp>
10 #include <leveldb/cache.h>
11 #include <leveldb/env.h>
12 #include <leveldb/filter_policy.h>
13 #include <memenv.h>
14
15 void HandleError(const leveldb::Status &status) throw(leveldb_error) {
16     if (status.ok())
17         return;
18     LogPrintf("%s\n", status.ToString());
19     if (status.IsCorruption())
20         throw leveldb_error("Database corrupted");
21     if (status.IsIOError())
22         throw leveldb_error("Database I/O error");
23     if (status.IsNotFound())
24         throw leveldb_error("Database entry missing");
25     throw leveldb_error("Unknown database error");
26 }
27
28 static leveldb::Options GetOptions(size_t nCacheSize) {
29     leveldb::Options options;
30     options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
31     options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
32     options.filter_policy = leveldb::NewBloomFilterPolicy(10);
33     options.compression = leveldb::kNoCompression;
34     options.max_open_files = 64;
35     return options;
36 }
37
38 CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {
39     penv = NULL;
40     readoptions.verify_checksums = true;
41     iteroptions.verify_checksums = true;
42     iteroptions.fill_cache = false;
43     syncoptions.sync = true;
44     options = GetOptions(nCacheSize);
45     options.create_if_missing = true;
46     if (fMemory) {
47         penv = leveldb::NewMemEnv(leveldb::Env::Default());
48         options.env = penv;
49     } else {
50         if (fWipe) {
51             LogPrintf("Wiping LevelDB in %s\n", path.string());
52             leveldb::DestroyDB(path.string(), options);
53         }
54         TryCreateDirectory(path);
55         LogPrintf("Opening LevelDB in %s\n", path.string());
56     }
57     leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
58     HandleError(status);
59     LogPrintf("Opened LevelDB successfully\n");
60 }
61
62 CLevelDBWrapper::~CLevelDBWrapper() {
63     delete pdb;
64     pdb = NULL;
65     delete options.filter_policy;
66     options.filter_policy = NULL;
67     delete options.block_cache;
68     options.block_cache = NULL;
69     delete penv;
70     options.env = NULL;
71 }
72
73 bool CLevelDBWrapper::WriteBatch(CLevelDBBatch &batch, bool fSync) throw(leveldb_error) {
74     leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
75     HandleError(status);
76     return true;
77 }
This page took 0.027863 seconds and 4 git commands to generate.