Squashed 'src/leveldb/' changes from a31c8aa40..196962ff0
[bitcoinplatinum.git] / doc / index.md
blobbe8569692bb054676bf451e06a8dd4980c32edca
1 leveldb
2 =======
4 _Jeff Dean, Sanjay Ghemawat_
6 The leveldb library provides a persistent key value store. Keys and values are
7 arbitrary byte arrays.  The keys are ordered within the key value store
8 according to a user-specified comparator function.
10 ## Opening A Database
12 A leveldb database has a name which corresponds to a file system directory. All
13 of the contents of database are stored in this directory. The following example
14 shows how to open a database, creating it if necessary:
16 ```c++
17 #include <cassert>
18 #include "leveldb/db.h"
20 leveldb::DB* db;
21 leveldb::Options options;
22 options.create_if_missing = true;
23 leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
24 assert(status.ok());
25 ...
26 ```
28 If you want to raise an error if the database already exists, add the following
29 line before the `leveldb::DB::Open` call:
31 ```c++
32 options.error_if_exists = true;
33 ```
35 ## Status
37 You may have noticed the `leveldb::Status` type above. Values of this type are
38 returned by most functions in leveldb that may encounter an error. You can check
39 if such a result is ok, and also print an associated error message:
41 ```c++
42 leveldb::Status s = ...;
43 if (!s.ok()) cerr << s.ToString() << endl;
44 ```
46 ## Closing A Database
48 When you are done with a database, just delete the database object. Example:
50 ```c++
51 ... open the db as described above ...
52 ... do something with db ...
53 delete db;
54 ```
56 ## Reads And Writes
58 The database provides Put, Delete, and Get methods to modify/query the database.
59 For example, the following code moves the value stored under key1 to key2.
61 ```c++
62 std::string value;
63 leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);
64 if (s.ok()) s = db->Put(leveldb::WriteOptions(), key2, value);
65 if (s.ok()) s = db->Delete(leveldb::WriteOptions(), key1);
66 ```
68 ## Atomic Updates
70 Note that if the process dies after the Put of key2 but before the delete of
71 key1, the same value may be left stored under multiple keys. Such problems can
72 be avoided by using the `WriteBatch` class to atomically apply a set of updates:
74 ```c++
75 #include "leveldb/write_batch.h"
76 ...
77 std::string value;
78 leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);
79 if (s.ok()) {
80   leveldb::WriteBatch batch;
81   batch.Delete(key1);
82   batch.Put(key2, value);
83   s = db->Write(leveldb::WriteOptions(), &batch);
85 ```
87 The `WriteBatch` holds a sequence of edits to be made to the database, and these
88 edits within the batch are applied in order. Note that we called Delete before
89 Put so that if key1 is identical to key2, we do not end up erroneously dropping
90 the value entirely.
92 Apart from its atomicity benefits, `WriteBatch` may also be used to speed up
93 bulk updates by placing lots of individual mutations into the same batch.
95 ## Synchronous Writes
97 By default, each write to leveldb is asynchronous: it returns after pushing the
98 write from the process into the operating system. The transfer from operating
99 system memory to the underlying persistent storage happens asynchronously. The
100 sync flag can be turned on for a particular write to make the write operation
101 not return until the data being written has been pushed all the way to
102 persistent storage. (On Posix systems, this is implemented by calling either
103 `fsync(...)` or `fdatasync(...)` or `msync(..., MS_SYNC)` before the write
104 operation returns.)
106 ```c++
107 leveldb::WriteOptions write_options;
108 write_options.sync = true;
109 db->Put(write_options, ...);
112 Asynchronous writes are often more than a thousand times as fast as synchronous
113 writes. The downside of asynchronous writes is that a crash of the machine may
114 cause the last few updates to be lost. Note that a crash of just the writing
115 process (i.e., not a reboot) will not cause any loss since even when sync is
116 false, an update is pushed from the process memory into the operating system
117 before it is considered done.
119 Asynchronous writes can often be used safely. For example, when loading a large
120 amount of data into the database you can handle lost updates by restarting the
121 bulk load after a crash. A hybrid scheme is also possible where every Nth write
122 is synchronous, and in the event of a crash, the bulk load is restarted just
123 after the last synchronous write finished by the previous run. (The synchronous
124 write can update a marker that describes where to restart on a crash.)
126 `WriteBatch` provides an alternative to asynchronous writes. Multiple updates
127 may be placed in the same WriteBatch and applied together using a synchronous
128 write (i.e., `write_options.sync` is set to true). The extra cost of the
129 synchronous write will be amortized across all of the writes in the batch.
131 ## Concurrency
133 A database may only be opened by one process at a time. The leveldb
134 implementation acquires a lock from the operating system to prevent misuse.
135 Within a single process, the same `leveldb::DB` object may be safely shared by
136 multiple concurrent threads. I.e., different threads may write into or fetch
137 iterators or call Get on the same database without any external synchronization
138 (the leveldb implementation will automatically do the required synchronization).
139 However other objects (like Iterator and `WriteBatch`) may require external
140 synchronization. If two threads share such an object, they must protect access
141 to it using their own locking protocol. More details are available in the public
142 header files.
144 ## Iteration
146 The following example demonstrates how to print all key,value pairs in a
147 database.
149 ```c++
150 leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
151 for (it->SeekToFirst(); it->Valid(); it->Next()) {
152   cout << it->key().ToString() << ": "  << it->value().ToString() << endl;
154 assert(it->status().ok());  // Check for any errors found during the scan
155 delete it;
158 The following variation shows how to process just the keys in the range
159 [start,limit):
161 ```c++
162 for (it->Seek(start);
163    it->Valid() && it->key().ToString() < limit;
164    it->Next()) {
165   ...
169 You can also process entries in reverse order. (Caveat: reverse iteration may be
170 somewhat slower than forward iteration.)
172 ```c++
173 for (it->SeekToLast(); it->Valid(); it->Prev()) {
174   ...
178 ## Snapshots
180 Snapshots provide consistent read-only views over the entire state of the
181 key-value store.  `ReadOptions::snapshot` may be non-NULL to indicate that a
182 read should operate on a particular version of the DB state. If
183 `ReadOptions::snapshot` is NULL, the read will operate on an implicit snapshot
184 of the current state.
186 Snapshots are created by the `DB::GetSnapshot()` method:
188 ```c++
189 leveldb::ReadOptions options;
190 options.snapshot = db->GetSnapshot();
191 ... apply some updates to db ...
192 leveldb::Iterator* iter = db->NewIterator(options);
193 ... read using iter to view the state when the snapshot was created ...
194 delete iter;
195 db->ReleaseSnapshot(options.snapshot);
198 Note that when a snapshot is no longer needed, it should be released using the
199 `DB::ReleaseSnapshot` interface. This allows the implementation to get rid of
200 state that was being maintained just to support reading as of that snapshot.
202 ## Slice
204 The return value of the `it->key()` and `it->value()` calls above are instances
205 of the `leveldb::Slice` type. Slice is a simple structure that contains a length
206 and a pointer to an external byte array. Returning a Slice is a cheaper
207 alternative to returning a `std::string` since we do not need to copy
208 potentially large keys and values. In addition, leveldb methods do not return
209 null-terminated C-style strings since leveldb keys and values are allowed to
210 contain `'\0'` bytes.
212 C++ strings and null-terminated C-style strings can be easily converted to a
213 Slice:
215 ```c++
216 leveldb::Slice s1 = "hello";
218 std::string str("world");
219 leveldb::Slice s2 = str;
222 A Slice can be easily converted back to a C++ string:
224 ```c++
225 std::string str = s1.ToString();
226 assert(str == std::string("hello"));
229 Be careful when using Slices since it is up to the caller to ensure that the
230 external byte array into which the Slice points remains live while the Slice is
231 in use. For example, the following is buggy:
233 ```c++
234 leveldb::Slice slice;
235 if (...) {
236   std::string str = ...;
237   slice = str;
239 Use(slice);
242 When the if statement goes out of scope, str will be destroyed and the backing
243 storage for slice will disappear.
245 ## Comparators
247 The preceding examples used the default ordering function for key, which orders
248 bytes lexicographically. You can however supply a custom comparator when opening
249 a database.  For example, suppose each database key consists of two numbers and
250 we should sort by the first number, breaking ties by the second number. First,
251 define a proper subclass of `leveldb::Comparator` that expresses these rules:
253 ```c++
254 class TwoPartComparator : public leveldb::Comparator {
255  public:
256   // Three-way comparison function:
257   //   if a < b: negative result
258   //   if a > b: positive result
259   //   else: zero result
260   int Compare(const leveldb::Slice& a, const leveldb::Slice& b) const {
261     int a1, a2, b1, b2;
262     ParseKey(a, &a1, &a2);
263     ParseKey(b, &b1, &b2);
264     if (a1 < b1) return -1;
265     if (a1 > b1) return +1;
266     if (a2 < b2) return -1;
267     if (a2 > b2) return +1;
268     return 0;
269   }
271   // Ignore the following methods for now:
272   const char* Name() const { return "TwoPartComparator"; }
273   void FindShortestSeparator(std::string*, const leveldb::Slice&) const {}
274   void FindShortSuccessor(std::string*) const {}
278 Now create a database using this custom comparator:
280 ```c++
281 TwoPartComparator cmp;
282 leveldb::DB* db;
283 leveldb::Options options;
284 options.create_if_missing = true;
285 options.comparator = &cmp;
286 leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
290 ### Backwards compatibility
292 The result of the comparator's Name method is attached to the database when it
293 is created, and is checked on every subsequent database open. If the name
294 changes, the `leveldb::DB::Open` call will fail. Therefore, change the name if
295 and only if the new key format and comparison function are incompatible with
296 existing databases, and it is ok to discard the contents of all existing
297 databases.
299 You can however still gradually evolve your key format over time with a little
300 bit of pre-planning. For example, you could store a version number at the end of
301 each key (one byte should suffice for most uses). When you wish to switch to a
302 new key format (e.g., adding an optional third part to the keys processed by
303 `TwoPartComparator`), (a) keep the same comparator name (b) increment the
304 version number for new keys (c) change the comparator function so it uses the
305 version numbers found in the keys to decide how to interpret them.
307 ## Performance
309 Performance can be tuned by changing the default values of the types defined in
310 `include/leveldb/options.h`.
312 ### Block size
314 leveldb groups adjacent keys together into the same block and such a block is
315 the unit of transfer to and from persistent storage. The default block size is
316 approximately 4096 uncompressed bytes.  Applications that mostly do bulk scans
317 over the contents of the database may wish to increase this size. Applications
318 that do a lot of point reads of small values may wish to switch to a smaller
319 block size if performance measurements indicate an improvement. There isn't much
320 benefit in using blocks smaller than one kilobyte, or larger than a few
321 megabytes. Also note that compression will be more effective with larger block
322 sizes.
324 ### Compression
326 Each block is individually compressed before being written to persistent
327 storage. Compression is on by default since the default compression method is
328 very fast, and is automatically disabled for uncompressible data. In rare cases,
329 applications may want to disable compression entirely, but should only do so if
330 benchmarks show a performance improvement:
332 ```c++
333 leveldb::Options options;
334 options.compression = leveldb::kNoCompression;
335 ... leveldb::DB::Open(options, name, ...) ....
338 ### Cache
340 The contents of the database are stored in a set of files in the filesystem and
341 each file stores a sequence of compressed blocks. If options.cache is non-NULL,
342 it is used to cache frequently used uncompressed block contents.
344 ```c++
345 #include "leveldb/cache.h"
347 leveldb::Options options;
348 options.cache = leveldb::NewLRUCache(100 * 1048576);  // 100MB cache
349 leveldb::DB* db;
350 leveldb::DB::Open(options, name, &db);
351 ... use the db ...
352 delete db
353 delete options.cache;
356 Note that the cache holds uncompressed data, and therefore it should be sized
357 according to application level data sizes, without any reduction from
358 compression. (Caching of compressed blocks is left to the operating system
359 buffer cache, or any custom Env implementation provided by the client.)
361 When performing a bulk read, the application may wish to disable caching so that
362 the data processed by the bulk read does not end up displacing most of the
363 cached contents. A per-iterator option can be used to achieve this:
365 ```c++
366 leveldb::ReadOptions options;
367 options.fill_cache = false;
368 leveldb::Iterator* it = db->NewIterator(options);
369 for (it->SeekToFirst(); it->Valid(); it->Next()) {
370   ...
374 ### Key Layout
376 Note that the unit of disk transfer and caching is a block. Adjacent keys
377 (according to the database sort order) will usually be placed in the same block.
378 Therefore the application can improve its performance by placing keys that are
379 accessed together near each other and placing infrequently used keys in a
380 separate region of the key space.
382 For example, suppose we are implementing a simple file system on top of leveldb.
383 The types of entries we might wish to store are:
385     filename -> permission-bits, length, list of file_block_ids
386     file_block_id -> data
388 We might want to prefix filename keys with one letter (say '/') and the
389 `file_block_id` keys with a different letter (say '0') so that scans over just
390 the metadata do not force us to fetch and cache bulky file contents.
392 ### Filters
394 Because of the way leveldb data is organized on disk, a single `Get()` call may
395 involve multiple reads from disk. The optional FilterPolicy mechanism can be
396 used to reduce the number of disk reads substantially.
398 ```c++
399 leveldb::Options options;
400 options.filter_policy = NewBloomFilterPolicy(10);
401 leveldb::DB* db;
402 leveldb::DB::Open(options, "/tmp/testdb", &db);
403 ... use the database ...
404 delete db;
405 delete options.filter_policy;
408 The preceding code associates a Bloom filter based filtering policy with the
409 database.  Bloom filter based filtering relies on keeping some number of bits of
410 data in memory per key (in this case 10 bits per key since that is the argument
411 we passed to `NewBloomFilterPolicy`). This filter will reduce the number of
412 unnecessary disk reads needed for Get() calls by a factor of approximately
413 a 100. Increasing the bits per key will lead to a larger reduction at the cost
414 of more memory usage. We recommend that applications whose working set does not
415 fit in memory and that do a lot of random reads set a filter policy.
417 If you are using a custom comparator, you should ensure that the filter policy
418 you are using is compatible with your comparator. For example, consider a
419 comparator that ignores trailing spaces when comparing keys.
420 `NewBloomFilterPolicy` must not be used with such a comparator. Instead, the
421 application should provide a custom filter policy that also ignores trailing
422 spaces. For example:
424 ```c++
425 class CustomFilterPolicy : public leveldb::FilterPolicy {
426  private:
427   FilterPolicy* builtin_policy_;
429  public:
430   CustomFilterPolicy() : builtin_policy_(NewBloomFilterPolicy(10)) {}
431   ~CustomFilterPolicy() { delete builtin_policy_; }
433   const char* Name() const { return "IgnoreTrailingSpacesFilter"; }
435   void CreateFilter(const Slice* keys, int n, std::string* dst) const {
436     // Use builtin bloom filter code after removing trailing spaces
437     std::vector<Slice> trimmed(n);
438     for (int i = 0; i < n; i++) {
439       trimmed[i] = RemoveTrailingSpaces(keys[i]);
440     }
441     return builtin_policy_->CreateFilter(&trimmed[i], n, dst);
442   }
446 Advanced applications may provide a filter policy that does not use a bloom
447 filter but uses some other mechanism for summarizing a set of keys. See
448 `leveldb/filter_policy.h` for detail.
450 ## Checksums
452 leveldb associates checksums with all data it stores in the file system. There
453 are two separate controls provided over how aggressively these checksums are
454 verified:
456 `ReadOptions::verify_checksums` may be set to true to force checksum
457 verification of all data that is read from the file system on behalf of a
458 particular read.  By default, no such verification is done.
460 `Options::paranoid_checks` may be set to true before opening a database to make
461 the database implementation raise an error as soon as it detects an internal
462 corruption. Depending on which portion of the database has been corrupted, the
463 error may be raised when the database is opened, or later by another database
464 operation. By default, paranoid checking is off so that the database can be used
465 even if parts of its persistent storage have been corrupted.
467 If a database is corrupted (perhaps it cannot be opened when paranoid checking
468 is turned on), the `leveldb::RepairDB` function may be used to recover as much
469 of the data as possible
471 ## Approximate Sizes
473 The `GetApproximateSizes` method can used to get the approximate number of bytes
474 of file system space used by one or more key ranges.
476 ```c++
477 leveldb::Range ranges[2];
478 ranges[0] = leveldb::Range("a", "c");
479 ranges[1] = leveldb::Range("x", "z");
480 uint64_t sizes[2];
481 leveldb::Status s = db->GetApproximateSizes(ranges, 2, sizes);
484 The preceding call will set `sizes[0]` to the approximate number of bytes of
485 file system space used by the key range `[a..c)` and `sizes[1]` to the
486 approximate number of bytes used by the key range `[x..z)`.
488 ## Environment
490 All file operations (and other operating system calls) issued by the leveldb
491 implementation are routed through a `leveldb::Env` object. Sophisticated clients
492 may wish to provide their own Env implementation to get better control.
493 For example, an application may introduce artificial delays in the file IO
494 paths to limit the impact of leveldb on other activities in the system.
496 ```c++
497 class SlowEnv : public leveldb::Env {
498   ... implementation of the Env interface ...
501 SlowEnv env;
502 leveldb::Options options;
503 options.env = &env;
504 Status s = leveldb::DB::Open(options, ...);
507 ## Porting
509 leveldb may be ported to a new platform by providing platform specific
510 implementations of the types/methods/functions exported by
511 `leveldb/port/port.h`.  See `leveldb/port/port_example.h` for more details.
513 In addition, the new platform may need a new default `leveldb::Env`
514 implementation.  See `leveldb/util/env_posix.h` for an example.
516 ## Other Information
518 Details about the leveldb implementation may be found in the following
519 documents:
521 1. [Implementation notes](impl.md)
522 2. [Format of an immutable Table file](table_format.md)
523 3. [Format of a log file](log_format.md)