1 // Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style license that can be
7 // found in the LICENSE file. See the AUTHORS file for names of contributors.
8 
9 #pragma once
10 
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <map>
14 #include <memory>
15 #include <string>
16 #include <unordered_map>
17 #include <vector>
18 #include "rocksdb/iterator.h"
19 #include "rocksdb/listener.h"
20 #include "rocksdb/metadata.h"
21 #include "rocksdb/options.h"
22 #include "rocksdb/snapshot.h"
23 #include "rocksdb/sst_file_writer.h"
24 #include "rocksdb/thread_status.h"
25 #include "rocksdb/transaction_log.h"
26 #include "rocksdb/types.h"
27 #include "rocksdb/version.h"
28 
29 #ifdef _WIN32
30 // Windows API macro interference
31 #undef DeleteFile
32 #endif
33 
34 #if defined(__GNUC__) || defined(__clang__)
35 #define ROCKSDB_DEPRECATED_FUNC __attribute__((__deprecated__))
36 #elif _WIN32
37 #define ROCKSDB_DEPRECATED_FUNC __declspec(deprecated)
38 #endif
39 
40 namespace ROCKSDB_NAMESPACE {
41 
42 struct Options;
43 struct DBOptions;
44 struct ColumnFamilyOptions;
45 struct ReadOptions;
46 struct WriteOptions;
47 struct FlushOptions;
48 struct CompactionOptions;
49 struct CompactRangeOptions;
50 struct TableProperties;
51 struct ExternalSstFileInfo;
52 class WriteBatch;
53 class Env;
54 class EventListener;
55 class StatsHistoryIterator;
56 class TraceWriter;
57 #ifdef ROCKSDB_LITE
58 class CompactionJobInfo;
59 #endif
60 class FileSystem;
61 
62 extern const std::string kDefaultColumnFamilyName;
63 extern const std::string kPersistentStatsColumnFamilyName;
64 struct ColumnFamilyDescriptor {
65   std::string name;
66   ColumnFamilyOptions options;
ColumnFamilyDescriptorColumnFamilyDescriptor67   ColumnFamilyDescriptor()
68       : name(kDefaultColumnFamilyName), options(ColumnFamilyOptions()) {}
ColumnFamilyDescriptorColumnFamilyDescriptor69   ColumnFamilyDescriptor(const std::string& _name,
70                          const ColumnFamilyOptions& _options)
71       : name(_name), options(_options) {}
72 };
73 
74 class ColumnFamilyHandle {
75  public:
~ColumnFamilyHandle()76   virtual ~ColumnFamilyHandle() {}
77   // Returns the name of the column family associated with the current handle.
78   virtual const std::string& GetName() const = 0;
79   // Returns the ID of the column family associated with the current handle.
80   virtual uint32_t GetID() const = 0;
81   // Fills "*desc" with the up-to-date descriptor of the column family
82   // associated with this handle. Since it fills "*desc" with the up-to-date
83   // information, this call might internally lock and release DB mutex to
84   // access the up-to-date CF options.  In addition, all the pointer-typed
85   // options cannot be referenced any longer than the original options exist.
86   //
87   // Note that this function is not supported in RocksDBLite.
88   virtual Status GetDescriptor(ColumnFamilyDescriptor* desc) = 0;
89   // Returns the comparator of the column family associated with the
90   // current handle.
91   virtual const Comparator* GetComparator() const = 0;
92 };
93 
94 static const int kMajorVersion = __ROCKSDB_MAJOR__;
95 static const int kMinorVersion = __ROCKSDB_MINOR__;
96 
97 // A range of keys
98 struct Range {
99   Slice start;
100   Slice limit;
101 
RangeRange102   Range() {}
RangeRange103   Range(const Slice& s, const Slice& l) : start(s), limit(l) {}
104 };
105 
106 struct RangePtr {
107   const Slice* start;
108   const Slice* limit;
109 
RangePtrRangePtr110   RangePtr() : start(nullptr), limit(nullptr) {}
RangePtrRangePtr111   RangePtr(const Slice* s, const Slice* l) : start(s), limit(l) {}
112 };
113 
114 struct IngestExternalFileArg {
115   ColumnFamilyHandle* column_family = nullptr;
116   std::vector<std::string> external_files;
117   IngestExternalFileOptions options;
118 };
119 
120 struct GetMergeOperandsOptions {
121   int expected_max_number_of_operands = 0;
122 };
123 
124 // A collections of table properties objects, where
125 //  key: is the table's file name.
126 //  value: the table properties object of the given table.
127 typedef std::unordered_map<std::string, std::shared_ptr<const TableProperties>>
128     TablePropertiesCollection;
129 
130 // A DB is a persistent ordered map from keys to values.
131 // A DB is safe for concurrent access from multiple threads without
132 // any external synchronization.
133 class DB {
134  public:
135   // Open the database with the specified "name".
136   // Stores a pointer to a heap-allocated database in *dbptr and returns
137   // OK on success.
138   // Stores nullptr in *dbptr and returns a non-OK status on error.
139   // Caller should delete *dbptr when it is no longer needed.
140   static Status Open(const Options& options, const std::string& name,
141                      DB** dbptr);
142 
143   // Open the database for read only. All DB interfaces
144   // that modify data, like put/delete, will return error.
145   // If the db is opened in read only mode, then no compactions
146   // will happen.
147   //
148   // Not supported in ROCKSDB_LITE, in which case the function will
149   // return Status::NotSupported.
150   static Status OpenForReadOnly(const Options& options, const std::string& name,
151                                 DB** dbptr,
152                                 bool error_if_log_file_exist = false);
153 
154   // Open the database for read only with column families. When opening DB with
155   // read only, you can specify only a subset of column families in the
156   // database that should be opened. However, you always need to specify default
157   // column family. The default column family name is 'default' and it's stored
158   // in ROCKSDB_NAMESPACE::kDefaultColumnFamilyName
159   //
160   // Not supported in ROCKSDB_LITE, in which case the function will
161   // return Status::NotSupported.
162   static Status OpenForReadOnly(
163       const DBOptions& db_options, const std::string& name,
164       const std::vector<ColumnFamilyDescriptor>& column_families,
165       std::vector<ColumnFamilyHandle*>* handles, DB** dbptr,
166       bool error_if_log_file_exist = false);
167 
168   // The following OpenAsSecondary functions create a secondary instance that
169   // can dynamically tail the MANIFEST of a primary that must have already been
170   // created. User can call TryCatchUpWithPrimary to make the secondary
171   // instance catch up with primary (WAL tailing is NOT supported now) whenever
172   // the user feels necessary. Column families created by the primary after the
173   // secondary instance starts are currently ignored by the secondary instance.
174   // Column families opened by secondary and dropped by the primary will be
175   // dropped by secondary as well. However the user of the secondary instance
176   // can still access the data of such dropped column family as long as they
177   // do not destroy the corresponding column family handle.
178   // WAL tailing is not supported at present, but will arrive soon.
179   //
180   // The options argument specifies the options to open the secondary instance.
181   // The name argument specifies the name of the primary db that you have used
182   // to open the primary instance.
183   // The secondary_path argument points to a directory where the secondary
184   // instance stores its info log.
185   // The dbptr is an out-arg corresponding to the opened secondary instance.
186   // The pointer points to a heap-allocated database, and the user should
187   // delete it after use.
188   // Open DB as secondary instance with only the default column family.
189   // Return OK on success, non-OK on failures.
190   static Status OpenAsSecondary(const Options& options, const std::string& name,
191                                 const std::string& secondary_path, DB** dbptr);
192 
193   // Open DB as secondary instance with column families. You can open a subset
194   // of column families in secondary mode.
195   // The db_options specify the database specific options.
196   // The name argument specifies the name of the primary db that you have used
197   // to open the primary instance.
198   // The secondary_path argument points to a directory where the secondary
199   // instance stores its info log.
200   // The column_families argument specifieds a list of column families to open.
201   // If any of the column families does not exist, the function returns non-OK
202   // status.
203   // The handles is an out-arg corresponding to the opened database column
204   // familiy handles.
205   // The dbptr is an out-arg corresponding to the opened secondary instance.
206   // The pointer points to a heap-allocated database, and the caller should
207   // delete it after use. Before deleting the dbptr, the user should also
208   // delete the pointers stored in handles vector.
209   // Return OK on success, on-OK on failures.
210   static Status OpenAsSecondary(
211       const DBOptions& db_options, const std::string& name,
212       const std::string& secondary_path,
213       const std::vector<ColumnFamilyDescriptor>& column_families,
214       std::vector<ColumnFamilyHandle*>* handles, DB** dbptr);
215 
216   // Open DB with column families.
217   // db_options specify database specific options
218   // column_families is the vector of all column families in the database,
219   // containing column family name and options. You need to open ALL column
220   // families in the database. To get the list of column families, you can use
221   // ListColumnFamilies(). Also, you can open only a subset of column families
222   // for read-only access.
223   // The default column family name is 'default' and it's stored
224   // in ROCKSDB_NAMESPACE::kDefaultColumnFamilyName.
225   // If everything is OK, handles will on return be the same size
226   // as column_families --- handles[i] will be a handle that you
227   // will use to operate on column family column_family[i].
228   // Before delete DB, you have to close All column families by calling
229   // DestroyColumnFamilyHandle() with all the handles.
230   static Status Open(const DBOptions& db_options, const std::string& name,
231                      const std::vector<ColumnFamilyDescriptor>& column_families,
232                      std::vector<ColumnFamilyHandle*>* handles, DB** dbptr);
233 
Resume()234   virtual Status Resume() { return Status::NotSupported(); }
235 
236   // Close the DB by releasing resources, closing files etc. This should be
237   // called before calling the destructor so that the caller can get back a
238   // status in case there are any errors. This will not fsync the WAL files.
239   // If syncing is required, the caller must first call SyncWAL(), or Write()
240   // using an empty write batch with WriteOptions.sync=true.
241   // Regardless of the return status, the DB must be freed.
242   // If the return status is Aborted(), closing fails because there is
243   // unreleased snapshot in the system. In this case, users can release
244   // the unreleased snapshots and try again and expect it to succeed. For
245   // other status, recalling Close() will be no-op.
246   // If the return status is NotSupported(), then the DB implementation does
247   // cleanup in the destructor
Close()248   virtual Status Close() { return Status::NotSupported(); }
249 
250   // ListColumnFamilies will open the DB specified by argument name
251   // and return the list of all column families in that DB
252   // through column_families argument. The ordering of
253   // column families in column_families is unspecified.
254   static Status ListColumnFamilies(const DBOptions& db_options,
255                                    const std::string& name,
256                                    std::vector<std::string>* column_families);
257 
DB()258   DB() {}
259   // No copying allowed
260   DB(const DB&) = delete;
261   void operator=(const DB&) = delete;
262 
263   virtual ~DB();
264 
265   // Create a column_family and return the handle of column family
266   // through the argument handle.
267   virtual Status CreateColumnFamily(const ColumnFamilyOptions& options,
268                                     const std::string& column_family_name,
269                                     ColumnFamilyHandle** handle);
270 
271   // Bulk create column families with the same column family options.
272   // Return the handles of the column families through the argument handles.
273   // In case of error, the request may succeed partially, and handles will
274   // contain column family handles that it managed to create, and have size
275   // equal to the number of created column families.
276   virtual Status CreateColumnFamilies(
277       const ColumnFamilyOptions& options,
278       const std::vector<std::string>& column_family_names,
279       std::vector<ColumnFamilyHandle*>* handles);
280 
281   // Bulk create column families.
282   // Return the handles of the column families through the argument handles.
283   // In case of error, the request may succeed partially, and handles will
284   // contain column family handles that it managed to create, and have size
285   // equal to the number of created column families.
286   virtual Status CreateColumnFamilies(
287       const std::vector<ColumnFamilyDescriptor>& column_families,
288       std::vector<ColumnFamilyHandle*>* handles);
289 
290   // Drop a column family specified by column_family handle. This call
291   // only records a drop record in the manifest and prevents the column
292   // family from flushing and compacting.
293   virtual Status DropColumnFamily(ColumnFamilyHandle* column_family);
294 
295   // Bulk drop column families. This call only records drop records in the
296   // manifest and prevents the column families from flushing and compacting.
297   // In case of error, the request may succeed partially. User may call
298   // ListColumnFamilies to check the result.
299   virtual Status DropColumnFamilies(
300       const std::vector<ColumnFamilyHandle*>& column_families);
301 
302   // Close a column family specified by column_family handle and destroy
303   // the column family handle specified to avoid double deletion. This call
304   // deletes the column family handle by default. Use this method to
305   // close column family instead of deleting column family handle directly
306   virtual Status DestroyColumnFamilyHandle(ColumnFamilyHandle* column_family);
307 
308   // Set the database entry for "key" to "value".
309   // If "key" already exists, it will be overwritten.
310   // Returns OK on success, and a non-OK status on error.
311   // Note: consider setting options.sync = true.
312   virtual Status Put(const WriteOptions& options,
313                      ColumnFamilyHandle* column_family, const Slice& key,
314                      const Slice& value) = 0;
Put(const WriteOptions & options,const Slice & key,const Slice & value)315   virtual Status Put(const WriteOptions& options, const Slice& key,
316                      const Slice& value) {
317     return Put(options, DefaultColumnFamily(), key, value);
318   }
319 
320   // Remove the database entry (if any) for "key".  Returns OK on
321   // success, and a non-OK status on error.  It is not an error if "key"
322   // did not exist in the database.
323   // Note: consider setting options.sync = true.
324   virtual Status Delete(const WriteOptions& options,
325                         ColumnFamilyHandle* column_family,
326                         const Slice& key) = 0;
Delete(const WriteOptions & options,const Slice & key)327   virtual Status Delete(const WriteOptions& options, const Slice& key) {
328     return Delete(options, DefaultColumnFamily(), key);
329   }
330 
331   // Remove the database entry for "key". Requires that the key exists
332   // and was not overwritten. Returns OK on success, and a non-OK status
333   // on error.  It is not an error if "key" did not exist in the database.
334   //
335   // If a key is overwritten (by calling Put() multiple times), then the result
336   // of calling SingleDelete() on this key is undefined.  SingleDelete() only
337   // behaves correctly if there has been only one Put() for this key since the
338   // previous call to SingleDelete() for this key.
339   //
340   // This feature is currently an experimental performance optimization
341   // for a very specific workload.  It is up to the caller to ensure that
342   // SingleDelete is only used for a key that is not deleted using Delete() or
343   // written using Merge().  Mixing SingleDelete operations with Deletes and
344   // Merges can result in undefined behavior.
345   //
346   // Note: consider setting options.sync = true.
347   virtual Status SingleDelete(const WriteOptions& options,
348                               ColumnFamilyHandle* column_family,
349                               const Slice& key) = 0;
SingleDelete(const WriteOptions & options,const Slice & key)350   virtual Status SingleDelete(const WriteOptions& options, const Slice& key) {
351     return SingleDelete(options, DefaultColumnFamily(), key);
352   }
353 
354   // Removes the database entries in the range ["begin_key", "end_key"), i.e.,
355   // including "begin_key" and excluding "end_key". Returns OK on success, and
356   // a non-OK status on error. It is not an error if no keys exist in the range
357   // ["begin_key", "end_key").
358   //
359   // This feature is now usable in production, with the following caveats:
360   // 1) Accumulating many range tombstones in the memtable will degrade read
361   // performance; this can be avoided by manually flushing occasionally.
362   // 2) Limiting the maximum number of open files in the presence of range
363   // tombstones can degrade read performance. To avoid this problem, set
364   // max_open_files to -1 whenever possible.
365   virtual Status DeleteRange(const WriteOptions& options,
366                              ColumnFamilyHandle* column_family,
367                              const Slice& begin_key, const Slice& end_key);
368 
369   // Merge the database entry for "key" with "value".  Returns OK on success,
370   // and a non-OK status on error. The semantics of this operation is
371   // determined by the user provided merge_operator when opening DB.
372   // Note: consider setting options.sync = true.
373   virtual Status Merge(const WriteOptions& options,
374                        ColumnFamilyHandle* column_family, const Slice& key,
375                        const Slice& value) = 0;
Merge(const WriteOptions & options,const Slice & key,const Slice & value)376   virtual Status Merge(const WriteOptions& options, const Slice& key,
377                        const Slice& value) {
378     return Merge(options, DefaultColumnFamily(), key, value);
379   }
380 
381   // Apply the specified updates to the database.
382   // If `updates` contains no update, WAL will still be synced if
383   // options.sync=true.
384   // Returns OK on success, non-OK on failure.
385   // Note: consider setting options.sync = true.
386   virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0;
387 
388   // If the database contains an entry for "key" store the
389   // corresponding value in *value and return OK.
390   //
391   // If timestamp is enabled and a non-null timestamp pointer is passed in,
392   // timestamp is returned.
393   //
394   // If there is no entry for "key" leave *value unchanged and return
395   // a status for which Status::IsNotFound() returns true.
396   //
397   // May return some other Status on an error.
Get(const ReadOptions & options,ColumnFamilyHandle * column_family,const Slice & key,std::string * value)398   virtual inline Status Get(const ReadOptions& options,
399                             ColumnFamilyHandle* column_family, const Slice& key,
400                             std::string* value) {
401     assert(value != nullptr);
402     PinnableSlice pinnable_val(value);
403     assert(!pinnable_val.IsPinned());
404     auto s = Get(options, column_family, key, &pinnable_val);
405     if (s.ok() && pinnable_val.IsPinned()) {
406       value->assign(pinnable_val.data(), pinnable_val.size());
407     }  // else value is already assigned
408     return s;
409   }
410   virtual Status Get(const ReadOptions& options,
411                      ColumnFamilyHandle* column_family, const Slice& key,
412                      PinnableSlice* value) = 0;
Get(const ReadOptions & options,const Slice & key,std::string * value)413   virtual Status Get(const ReadOptions& options, const Slice& key,
414                      std::string* value) {
415     return Get(options, DefaultColumnFamily(), key, value);
416   }
417 
418   // Get() methods that return timestamp. Derived DB classes don't need to worry
419   // about this group of methods if they don't care about timestamp feature.
Get(const ReadOptions & options,ColumnFamilyHandle * column_family,const Slice & key,std::string * value,std::string * timestamp)420   virtual inline Status Get(const ReadOptions& options,
421                             ColumnFamilyHandle* column_family, const Slice& key,
422                             std::string* value, std::string* timestamp) {
423     assert(value != nullptr);
424     PinnableSlice pinnable_val(value);
425     assert(!pinnable_val.IsPinned());
426     auto s = Get(options, column_family, key, &pinnable_val, timestamp);
427     if (s.ok() && pinnable_val.IsPinned()) {
428       value->assign(pinnable_val.data(), pinnable_val.size());
429     }  // else value is already assigned
430     return s;
431   }
Get(const ReadOptions &,ColumnFamilyHandle *,const Slice &,PinnableSlice *,std::string *)432   virtual Status Get(const ReadOptions& /*options*/,
433                      ColumnFamilyHandle* /*column_family*/,
434                      const Slice& /*key*/, PinnableSlice* /*value*/,
435                      std::string* /*timestamp*/) {
436     return Status::NotSupported(
437         "Get() that returns timestamp is not implemented.");
438   }
Get(const ReadOptions & options,const Slice & key,std::string * value,std::string * timestamp)439   virtual Status Get(const ReadOptions& options, const Slice& key,
440                      std::string* value, std::string* timestamp) {
441     return Get(options, DefaultColumnFamily(), key, value, timestamp);
442   }
443 
444   // Returns all the merge operands corresponding to the key. If the
445   // number of merge operands in DB is greater than
446   // merge_operands_options.expected_max_number_of_operands
447   // no merge operands are returned and status is Incomplete. Merge operands
448   // returned are in the order of insertion.
449   // merge_operands- Points to an array of at-least
450   //             merge_operands_options.expected_max_number_of_operands and the
451   //             caller is responsible for allocating it. If the status
452   //             returned is Incomplete then number_of_operands will contain
453   //             the total number of merge operands found in DB for key.
454   virtual Status GetMergeOperands(
455       const ReadOptions& options, ColumnFamilyHandle* column_family,
456       const Slice& key, PinnableSlice* merge_operands,
457       GetMergeOperandsOptions* get_merge_operands_options,
458       int* number_of_operands) = 0;
459 
460   // If keys[i] does not exist in the database, then the i'th returned
461   // status will be one for which Status::IsNotFound() is true, and
462   // (*values)[i] will be set to some arbitrary value (often ""). Otherwise,
463   // the i'th returned status will have Status::ok() true, and (*values)[i]
464   // will store the value associated with keys[i].
465   //
466   // (*values) will always be resized to be the same size as (keys).
467   // Similarly, the number of returned statuses will be the number of keys.
468   // Note: keys will not be "de-duplicated". Duplicate keys will return
469   // duplicate values in order.
470   virtual std::vector<Status> MultiGet(
471       const ReadOptions& options,
472       const std::vector<ColumnFamilyHandle*>& column_family,
473       const std::vector<Slice>& keys, std::vector<std::string>* values) = 0;
MultiGet(const ReadOptions & options,const std::vector<Slice> & keys,std::vector<std::string> * values)474   virtual std::vector<Status> MultiGet(const ReadOptions& options,
475                                        const std::vector<Slice>& keys,
476                                        std::vector<std::string>* values) {
477     return MultiGet(
478         options,
479         std::vector<ColumnFamilyHandle*>(keys.size(), DefaultColumnFamily()),
480         keys, values);
481   }
482 
MultiGet(const ReadOptions &,const std::vector<ColumnFamilyHandle * > &,const std::vector<Slice> & keys,std::vector<std::string> *,std::vector<std::string> *)483   virtual std::vector<Status> MultiGet(
484       const ReadOptions& /*options*/,
485       const std::vector<ColumnFamilyHandle*>& /*column_family*/,
486       const std::vector<Slice>& keys, std::vector<std::string>* /*values*/,
487       std::vector<std::string>* /*timestamps*/) {
488     return std::vector<Status>(
489         keys.size(), Status::NotSupported(
490                          "MultiGet() returning timestamps not implemented."));
491   }
MultiGet(const ReadOptions & options,const std::vector<Slice> & keys,std::vector<std::string> * values,std::vector<std::string> * timestamps)492   virtual std::vector<Status> MultiGet(const ReadOptions& options,
493                                        const std::vector<Slice>& keys,
494                                        std::vector<std::string>* values,
495                                        std::vector<std::string>* timestamps) {
496     return MultiGet(
497         options,
498         std::vector<ColumnFamilyHandle*>(keys.size(), DefaultColumnFamily()),
499         keys, values, timestamps);
500   }
501 
502   // Overloaded MultiGet API that improves performance by batching operations
503   // in the read path for greater efficiency. Currently, only the block based
504   // table format with full filters are supported. Other table formats such
505   // as plain table, block based table with block based filters and
506   // partitioned indexes will still work, but will not get any performance
507   // benefits.
508   // Parameters -
509   // options - ReadOptions
510   // column_family - ColumnFamilyHandle* that the keys belong to. All the keys
511   //                 passed to the API are restricted to a single column family
512   // num_keys - Number of keys to lookup
513   // keys - Pointer to C style array of key Slices with num_keys elements
514   // values - Pointer to C style array of PinnableSlices with num_keys elements
515   // statuses - Pointer to C style array of Status with num_keys elements
516   // sorted_input - If true, it means the input keys are already sorted by key
517   //                order, so the MultiGet() API doesn't have to sort them
518   //                again. If false, the keys will be copied and sorted
519   //                internally by the API - the input array will not be
520   //                modified
521   virtual void MultiGet(const ReadOptions& options,
522                         ColumnFamilyHandle* column_family,
523                         const size_t num_keys, const Slice* keys,
524                         PinnableSlice* values, Status* statuses,
525                         const bool /*sorted_input*/ = false) {
526     std::vector<ColumnFamilyHandle*> cf;
527     std::vector<Slice> user_keys;
528     std::vector<Status> status;
529     std::vector<std::string> vals;
530 
531     for (size_t i = 0; i < num_keys; ++i) {
532       cf.emplace_back(column_family);
533       user_keys.emplace_back(keys[i]);
534     }
535     status = MultiGet(options, cf, user_keys, &vals);
536     std::copy(status.begin(), status.end(), statuses);
537     for (auto& value : vals) {
538       values->PinSelf(value);
539       values++;
540     }
541   }
542 
543   virtual void MultiGet(const ReadOptions& options,
544                         ColumnFamilyHandle* column_family,
545                         const size_t num_keys, const Slice* keys,
546                         PinnableSlice* values, std::string* timestamps,
547                         Status* statuses, const bool /*sorted_input*/ = false) {
548     std::vector<ColumnFamilyHandle*> cf;
549     std::vector<Slice> user_keys;
550     std::vector<Status> status;
551     std::vector<std::string> vals;
552     std::vector<std::string> tss;
553 
554     for (size_t i = 0; i < num_keys; ++i) {
555       cf.emplace_back(column_family);
556       user_keys.emplace_back(keys[i]);
557     }
558     status = MultiGet(options, cf, user_keys, &vals, &tss);
559     std::copy(status.begin(), status.end(), statuses);
560     std::copy(tss.begin(), tss.end(), timestamps);
561     for (auto& value : vals) {
562       values->PinSelf(value);
563       values++;
564     }
565   }
566 
567   // Overloaded MultiGet API that improves performance by batching operations
568   // in the read path for greater efficiency. Currently, only the block based
569   // table format with full filters are supported. Other table formats such
570   // as plain table, block based table with block based filters and
571   // partitioned indexes will still work, but will not get any performance
572   // benefits.
573   // Parameters -
574   // options - ReadOptions
575   // column_family - ColumnFamilyHandle* that the keys belong to. All the keys
576   //                 passed to the API are restricted to a single column family
577   // num_keys - Number of keys to lookup
578   // keys - Pointer to C style array of key Slices with num_keys elements
579   // values - Pointer to C style array of PinnableSlices with num_keys elements
580   // statuses - Pointer to C style array of Status with num_keys elements
581   // sorted_input - If true, it means the input keys are already sorted by key
582   //                order, so the MultiGet() API doesn't have to sort them
583   //                again. If false, the keys will be copied and sorted
584   //                internally by the API - the input array will not be
585   //                modified
586   virtual void MultiGet(const ReadOptions& options, const size_t num_keys,
587                         ColumnFamilyHandle** column_families, const Slice* keys,
588                         PinnableSlice* values, Status* statuses,
589                         const bool /*sorted_input*/ = false) {
590     std::vector<ColumnFamilyHandle*> cf;
591     std::vector<Slice> user_keys;
592     std::vector<Status> status;
593     std::vector<std::string> vals;
594 
595     for (size_t i = 0; i < num_keys; ++i) {
596       cf.emplace_back(column_families[i]);
597       user_keys.emplace_back(keys[i]);
598     }
599     status = MultiGet(options, cf, user_keys, &vals);
600     std::copy(status.begin(), status.end(), statuses);
601     for (auto& value : vals) {
602       values->PinSelf(value);
603       values++;
604     }
605   }
606   virtual void MultiGet(const ReadOptions& options, const size_t num_keys,
607                         ColumnFamilyHandle** column_families, const Slice* keys,
608                         PinnableSlice* values, std::string* timestamps,
609                         Status* statuses, const bool /*sorted_input*/ = false) {
610     std::vector<ColumnFamilyHandle*> cf;
611     std::vector<Slice> user_keys;
612     std::vector<Status> status;
613     std::vector<std::string> vals;
614     std::vector<std::string> tss;
615 
616     for (size_t i = 0; i < num_keys; ++i) {
617       cf.emplace_back(column_families[i]);
618       user_keys.emplace_back(keys[i]);
619     }
620     status = MultiGet(options, cf, user_keys, &vals, &tss);
621     std::copy(status.begin(), status.end(), statuses);
622     std::copy(tss.begin(), tss.end(), timestamps);
623     for (auto& value : vals) {
624       values->PinSelf(value);
625       values++;
626     }
627   }
628 
629   // If the key definitely does not exist in the database, then this method
630   // returns false, else true. If the caller wants to obtain value when the key
631   // is found in memory, a bool for 'value_found' must be passed. 'value_found'
632   // will be true on return if value has been set properly.
633   // This check is potentially lighter-weight than invoking DB::Get(). One way
634   // to make this lighter weight is to avoid doing any IOs.
635   // Default implementation here returns true and sets 'value_found' to false
636   virtual bool KeyMayExist(const ReadOptions& /*options*/,
637                            ColumnFamilyHandle* /*column_family*/,
638                            const Slice& /*key*/, std::string* /*value*/,
639                            std::string* /*timestamp*/,
640                            bool* value_found = nullptr) {
641     if (value_found != nullptr) {
642       *value_found = false;
643     }
644     return true;
645   }
646 
647   virtual bool KeyMayExist(const ReadOptions& options,
648                            ColumnFamilyHandle* column_family, const Slice& key,
649                            std::string* value, bool* value_found = nullptr) {
650     return KeyMayExist(options, column_family, key, value,
651                        /*timestamp=*/nullptr, value_found);
652   }
653 
654   virtual bool KeyMayExist(const ReadOptions& options, const Slice& key,
655                            std::string* value, bool* value_found = nullptr) {
656     return KeyMayExist(options, DefaultColumnFamily(), key, value, value_found);
657   }
658 
659   virtual bool KeyMayExist(const ReadOptions& options, const Slice& key,
660                            std::string* value, std::string* timestamp,
661                            bool* value_found = nullptr) {
662     return KeyMayExist(options, DefaultColumnFamily(), key, value, timestamp,
663                        value_found);
664   }
665 
666   // Return a heap-allocated iterator over the contents of the database.
667   // The result of NewIterator() is initially invalid (caller must
668   // call one of the Seek methods on the iterator before using it).
669   //
670   // Caller should delete the iterator when it is no longer needed.
671   // The returned iterator should be deleted before this db is deleted.
672   virtual Iterator* NewIterator(const ReadOptions& options,
673                                 ColumnFamilyHandle* column_family) = 0;
NewIterator(const ReadOptions & options)674   virtual Iterator* NewIterator(const ReadOptions& options) {
675     return NewIterator(options, DefaultColumnFamily());
676   }
677   // Returns iterators from a consistent database state across multiple
678   // column families. Iterators are heap allocated and need to be deleted
679   // before the db is deleted
680   virtual Status NewIterators(
681       const ReadOptions& options,
682       const std::vector<ColumnFamilyHandle*>& column_families,
683       std::vector<Iterator*>* iterators) = 0;
684 
685   // Return a handle to the current DB state.  Iterators created with
686   // this handle will all observe a stable snapshot of the current DB
687   // state.  The caller must call ReleaseSnapshot(result) when the
688   // snapshot is no longer needed.
689   //
690   // nullptr will be returned if the DB fails to take a snapshot or does
691   // not support snapshot.
692   virtual const Snapshot* GetSnapshot() = 0;
693 
694   // Release a previously acquired snapshot.  The caller must not
695   // use "snapshot" after this call.
696   virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0;
697 
698 #ifndef ROCKSDB_LITE
699   // Contains all valid property arguments for GetProperty().
700   //
701   // NOTE: Property names cannot end in numbers since those are interpreted as
702   //       arguments, e.g., see kNumFilesAtLevelPrefix.
703   struct Properties {
704     //  "rocksdb.num-files-at-level<N>" - returns string containing the number
705     //      of files at level <N>, where <N> is an ASCII representation of a
706     //      level number (e.g., "0").
707     static const std::string kNumFilesAtLevelPrefix;
708 
709     //  "rocksdb.compression-ratio-at-level<N>" - returns string containing the
710     //      compression ratio of data at level <N>, where <N> is an ASCII
711     //      representation of a level number (e.g., "0"). Here, compression
712     //      ratio is defined as uncompressed data size / compressed file size.
713     //      Returns "-1.0" if no open files at level <N>.
714     static const std::string kCompressionRatioAtLevelPrefix;
715 
716     //  "rocksdb.stats" - returns a multi-line string containing the data
717     //      described by kCFStats followed by the data described by kDBStats.
718     static const std::string kStats;
719 
720     //  "rocksdb.sstables" - returns a multi-line string summarizing current
721     //      SST files.
722     static const std::string kSSTables;
723 
724     //  "rocksdb.cfstats" - Both of "rocksdb.cfstats-no-file-histogram" and
725     //      "rocksdb.cf-file-histogram" together. See below for description
726     //      of the two.
727     static const std::string kCFStats;
728 
729     //  "rocksdb.cfstats-no-file-histogram" - returns a multi-line string with
730     //      general columm family stats per-level over db's lifetime ("L<n>"),
731     //      aggregated over db's lifetime ("Sum"), and aggregated over the
732     //      interval since the last retrieval ("Int").
733     //  It could also be used to return the stats in the format of the map.
734     //  In this case there will a pair of string to array of double for
735     //  each level as well as for "Sum". "Int" stats will not be affected
736     //  when this form of stats are retrieved.
737     static const std::string kCFStatsNoFileHistogram;
738 
739     //  "rocksdb.cf-file-histogram" - print out how many file reads to every
740     //      level, as well as the histogram of latency of single requests.
741     static const std::string kCFFileHistogram;
742 
743     //  "rocksdb.dbstats" - returns a multi-line string with general database
744     //      stats, both cumulative (over the db's lifetime) and interval (since
745     //      the last retrieval of kDBStats).
746     static const std::string kDBStats;
747 
748     //  "rocksdb.levelstats" - returns multi-line string containing the number
749     //      of files per level and total size of each level (MB).
750     static const std::string kLevelStats;
751 
752     //  "rocksdb.num-immutable-mem-table" - returns number of immutable
753     //      memtables that have not yet been flushed.
754     static const std::string kNumImmutableMemTable;
755 
756     //  "rocksdb.num-immutable-mem-table-flushed" - returns number of immutable
757     //      memtables that have already been flushed.
758     static const std::string kNumImmutableMemTableFlushed;
759 
760     //  "rocksdb.mem-table-flush-pending" - returns 1 if a memtable flush is
761     //      pending; otherwise, returns 0.
762     static const std::string kMemTableFlushPending;
763 
764     //  "rocksdb.num-running-flushes" - returns the number of currently running
765     //      flushes.
766     static const std::string kNumRunningFlushes;
767 
768     //  "rocksdb.compaction-pending" - returns 1 if at least one compaction is
769     //      pending; otherwise, returns 0.
770     static const std::string kCompactionPending;
771 
772     //  "rocksdb.num-running-compactions" - returns the number of currently
773     //      running compactions.
774     static const std::string kNumRunningCompactions;
775 
776     //  "rocksdb.background-errors" - returns accumulated number of background
777     //      errors.
778     static const std::string kBackgroundErrors;
779 
780     //  "rocksdb.cur-size-active-mem-table" - returns approximate size of active
781     //      memtable (bytes).
782     static const std::string kCurSizeActiveMemTable;
783 
784     //  "rocksdb.cur-size-all-mem-tables" - returns approximate size of active
785     //      and unflushed immutable memtables (bytes).
786     static const std::string kCurSizeAllMemTables;
787 
788     //  "rocksdb.size-all-mem-tables" - returns approximate size of active,
789     //      unflushed immutable, and pinned immutable memtables (bytes).
790     static const std::string kSizeAllMemTables;
791 
792     //  "rocksdb.num-entries-active-mem-table" - returns total number of entries
793     //      in the active memtable.
794     static const std::string kNumEntriesActiveMemTable;
795 
796     //  "rocksdb.num-entries-imm-mem-tables" - returns total number of entries
797     //      in the unflushed immutable memtables.
798     static const std::string kNumEntriesImmMemTables;
799 
800     //  "rocksdb.num-deletes-active-mem-table" - returns total number of delete
801     //      entries in the active memtable.
802     static const std::string kNumDeletesActiveMemTable;
803 
804     //  "rocksdb.num-deletes-imm-mem-tables" - returns total number of delete
805     //      entries in the unflushed immutable memtables.
806     static const std::string kNumDeletesImmMemTables;
807 
808     //  "rocksdb.estimate-num-keys" - returns estimated number of total keys in
809     //      the active and unflushed immutable memtables and storage.
810     static const std::string kEstimateNumKeys;
811 
812     //  "rocksdb.estimate-table-readers-mem" - returns estimated memory used for
813     //      reading SST tables, excluding memory used in block cache (e.g.,
814     //      filter and index blocks).
815     static const std::string kEstimateTableReadersMem;
816 
817     //  "rocksdb.is-file-deletions-enabled" - returns 0 if deletion of obsolete
818     //      files is enabled; otherwise, returns a non-zero number.
819     static const std::string kIsFileDeletionsEnabled;
820 
821     //  "rocksdb.num-snapshots" - returns number of unreleased snapshots of the
822     //      database.
823     static const std::string kNumSnapshots;
824 
825     //  "rocksdb.oldest-snapshot-time" - returns number representing unix
826     //      timestamp of oldest unreleased snapshot.
827     static const std::string kOldestSnapshotTime;
828 
829     //  "rocksdb.oldest-snapshot-sequence" - returns number representing
830     //      sequence number of oldest unreleased snapshot.
831     static const std::string kOldestSnapshotSequence;
832 
833     //  "rocksdb.num-live-versions" - returns number of live versions. `Version`
834     //      is an internal data structure. See version_set.h for details. More
835     //      live versions often mean more SST files are held from being deleted,
836     //      by iterators or unfinished compactions.
837     static const std::string kNumLiveVersions;
838 
839     //  "rocksdb.current-super-version-number" - returns number of current LSM
840     //  version. It is a uint64_t integer number, incremented after there is
841     //  any change to the LSM tree. The number is not preserved after restarting
842     //  the DB. After DB restart, it will start from 0 again.
843     static const std::string kCurrentSuperVersionNumber;
844 
845     //  "rocksdb.estimate-live-data-size" - returns an estimate of the amount of
846     //      live data in bytes.
847     static const std::string kEstimateLiveDataSize;
848 
849     //  "rocksdb.min-log-number-to-keep" - return the minimum log number of the
850     //      log files that should be kept.
851     static const std::string kMinLogNumberToKeep;
852 
853     //  "rocksdb.min-obsolete-sst-number-to-keep" - return the minimum file
854     //      number for an obsolete SST to be kept. The max value of `uint64_t`
855     //      will be returned if all obsolete files can be deleted.
856     static const std::string kMinObsoleteSstNumberToKeep;
857 
858     //  "rocksdb.total-sst-files-size" - returns total size (bytes) of all SST
859     //      files.
860     //  WARNING: may slow down online queries if there are too many files.
861     static const std::string kTotalSstFilesSize;
862 
863     //  "rocksdb.live-sst-files-size" - returns total size (bytes) of all SST
864     //      files belong to the latest LSM tree.
865     static const std::string kLiveSstFilesSize;
866 
867     //  "rocksdb.base-level" - returns number of level to which L0 data will be
868     //      compacted.
869     static const std::string kBaseLevel;
870 
871     //  "rocksdb.estimate-pending-compaction-bytes" - returns estimated total
872     //      number of bytes compaction needs to rewrite to get all levels down
873     //      to under target size. Not valid for other compactions than level-
874     //      based.
875     static const std::string kEstimatePendingCompactionBytes;
876 
877     //  "rocksdb.aggregated-table-properties" - returns a string representation
878     //      of the aggregated table properties of the target column family.
879     static const std::string kAggregatedTableProperties;
880 
881     //  "rocksdb.aggregated-table-properties-at-level<N>", same as the previous
882     //      one but only returns the aggregated table properties of the
883     //      specified level "N" at the target column family.
884     static const std::string kAggregatedTablePropertiesAtLevel;
885 
886     //  "rocksdb.actual-delayed-write-rate" - returns the current actual delayed
887     //      write rate. 0 means no delay.
888     static const std::string kActualDelayedWriteRate;
889 
890     //  "rocksdb.is-write-stopped" - Return 1 if write has been stopped.
891     static const std::string kIsWriteStopped;
892 
893     //  "rocksdb.estimate-oldest-key-time" - returns an estimation of
894     //      oldest key timestamp in the DB. Currently only available for
895     //      FIFO compaction with
896     //      compaction_options_fifo.allow_compaction = false.
897     static const std::string kEstimateOldestKeyTime;
898 
899     //  "rocksdb.block-cache-capacity" - returns block cache capacity.
900     static const std::string kBlockCacheCapacity;
901 
902     //  "rocksdb.block-cache-usage" - returns the memory size for the entries
903     //      residing in block cache.
904     static const std::string kBlockCacheUsage;
905 
906     // "rocksdb.block-cache-pinned-usage" - returns the memory size for the
907     //      entries being pinned.
908     static const std::string kBlockCachePinnedUsage;
909 
910     // "rocksdb.options-statistics" - returns multi-line string
911     //      of options.statistics
912     static const std::string kOptionsStatistics;
913   };
914 #endif /* ROCKSDB_LITE */
915 
916   // DB implementations can export properties about their state via this method.
917   // If "property" is a valid property understood by this DB implementation (see
918   // Properties struct above for valid options), fills "*value" with its current
919   // value and returns true.  Otherwise, returns false.
920   virtual bool GetProperty(ColumnFamilyHandle* column_family,
921                            const Slice& property, std::string* value) = 0;
GetProperty(const Slice & property,std::string * value)922   virtual bool GetProperty(const Slice& property, std::string* value) {
923     return GetProperty(DefaultColumnFamily(), property, value);
924   }
925   virtual bool GetMapProperty(ColumnFamilyHandle* column_family,
926                               const Slice& property,
927                               std::map<std::string, std::string>* value) = 0;
GetMapProperty(const Slice & property,std::map<std::string,std::string> * value)928   virtual bool GetMapProperty(const Slice& property,
929                               std::map<std::string, std::string>* value) {
930     return GetMapProperty(DefaultColumnFamily(), property, value);
931   }
932 
933   // Similar to GetProperty(), but only works for a subset of properties whose
934   // return value is an integer. Return the value by integer. Supported
935   // properties:
936   //  "rocksdb.num-immutable-mem-table"
937   //  "rocksdb.mem-table-flush-pending"
938   //  "rocksdb.compaction-pending"
939   //  "rocksdb.background-errors"
940   //  "rocksdb.cur-size-active-mem-table"
941   //  "rocksdb.cur-size-all-mem-tables"
942   //  "rocksdb.size-all-mem-tables"
943   //  "rocksdb.num-entries-active-mem-table"
944   //  "rocksdb.num-entries-imm-mem-tables"
945   //  "rocksdb.num-deletes-active-mem-table"
946   //  "rocksdb.num-deletes-imm-mem-tables"
947   //  "rocksdb.estimate-num-keys"
948   //  "rocksdb.estimate-table-readers-mem"
949   //  "rocksdb.is-file-deletions-enabled"
950   //  "rocksdb.num-snapshots"
951   //  "rocksdb.oldest-snapshot-time"
952   //  "rocksdb.num-live-versions"
953   //  "rocksdb.current-super-version-number"
954   //  "rocksdb.estimate-live-data-size"
955   //  "rocksdb.min-log-number-to-keep"
956   //  "rocksdb.min-obsolete-sst-number-to-keep"
957   //  "rocksdb.total-sst-files-size"
958   //  "rocksdb.live-sst-files-size"
959   //  "rocksdb.base-level"
960   //  "rocksdb.estimate-pending-compaction-bytes"
961   //  "rocksdb.num-running-compactions"
962   //  "rocksdb.num-running-flushes"
963   //  "rocksdb.actual-delayed-write-rate"
964   //  "rocksdb.is-write-stopped"
965   //  "rocksdb.estimate-oldest-key-time"
966   //  "rocksdb.block-cache-capacity"
967   //  "rocksdb.block-cache-usage"
968   //  "rocksdb.block-cache-pinned-usage"
969   virtual bool GetIntProperty(ColumnFamilyHandle* column_family,
970                               const Slice& property, uint64_t* value) = 0;
GetIntProperty(const Slice & property,uint64_t * value)971   virtual bool GetIntProperty(const Slice& property, uint64_t* value) {
972     return GetIntProperty(DefaultColumnFamily(), property, value);
973   }
974 
975   // Reset internal stats for DB and all column families.
976   // Note this doesn't reset options.statistics as it is not owned by
977   // DB.
ResetStats()978   virtual Status ResetStats() {
979     return Status::NotSupported("Not implemented");
980   }
981 
982   // Same as GetIntProperty(), but this one returns the aggregated int
983   // property from all column families.
984   virtual bool GetAggregatedIntProperty(const Slice& property,
985                                         uint64_t* value) = 0;
986 
987   // Flags for DB::GetSizeApproximation that specify whether memtable
988   // stats should be included, or file stats approximation or both
989   enum SizeApproximationFlags : uint8_t {
990     NONE = 0,
991     INCLUDE_MEMTABLES = 1 << 0,
992     INCLUDE_FILES = 1 << 1
993   };
994 
995   // For each i in [0,n-1], store in "sizes[i]", the approximate
996   // file system space used by keys in "[range[i].start .. range[i].limit)".
997   //
998   // Note that the returned sizes measure file system space usage, so
999   // if the user data compresses by a factor of ten, the returned
1000   // sizes will be one-tenth the size of the corresponding user data size.
1001   virtual Status GetApproximateSizes(const SizeApproximationOptions& options,
1002                                      ColumnFamilyHandle* column_family,
1003                                      const Range* range, int n,
1004                                      uint64_t* sizes) = 0;
1005 
1006   // Simpler versions of the GetApproximateSizes() method above.
1007   // The include_flags argumenbt must of type DB::SizeApproximationFlags
1008   // and can not be NONE.
1009   virtual void GetApproximateSizes(ColumnFamilyHandle* column_family,
1010                                    const Range* range, int n, uint64_t* sizes,
1011                                    uint8_t include_flags = INCLUDE_FILES) {
1012     SizeApproximationOptions options;
1013     options.include_memtabtles =
1014         (include_flags & SizeApproximationFlags::INCLUDE_MEMTABLES) != 0;
1015     options.include_files =
1016         (include_flags & SizeApproximationFlags::INCLUDE_FILES) != 0;
1017     GetApproximateSizes(options, column_family, range, n, sizes);
1018   }
1019   virtual void GetApproximateSizes(const Range* range, int n, uint64_t* sizes,
1020                                    uint8_t include_flags = INCLUDE_FILES) {
1021     GetApproximateSizes(DefaultColumnFamily(), range, n, sizes, include_flags);
1022   }
1023 
1024   // The method is similar to GetApproximateSizes, except it
1025   // returns approximate number of records in memtables.
1026   virtual void GetApproximateMemTableStats(ColumnFamilyHandle* column_family,
1027                                            const Range& range,
1028                                            uint64_t* const count,
1029                                            uint64_t* const size) = 0;
GetApproximateMemTableStats(const Range & range,uint64_t * const count,uint64_t * const size)1030   virtual void GetApproximateMemTableStats(const Range& range,
1031                                            uint64_t* const count,
1032                                            uint64_t* const size) {
1033     GetApproximateMemTableStats(DefaultColumnFamily(), range, count, size);
1034   }
1035 
1036   // Deprecated versions of GetApproximateSizes
GetApproximateSizes(const Range * range,int n,uint64_t * sizes,bool include_memtable)1037   ROCKSDB_DEPRECATED_FUNC virtual void GetApproximateSizes(
1038       const Range* range, int n, uint64_t* sizes, bool include_memtable) {
1039     uint8_t include_flags = SizeApproximationFlags::INCLUDE_FILES;
1040     if (include_memtable) {
1041       include_flags |= SizeApproximationFlags::INCLUDE_MEMTABLES;
1042     }
1043     GetApproximateSizes(DefaultColumnFamily(), range, n, sizes, include_flags);
1044   }
GetApproximateSizes(ColumnFamilyHandle * column_family,const Range * range,int n,uint64_t * sizes,bool include_memtable)1045   ROCKSDB_DEPRECATED_FUNC virtual void GetApproximateSizes(
1046       ColumnFamilyHandle* column_family, const Range* range, int n,
1047       uint64_t* sizes, bool include_memtable) {
1048     uint8_t include_flags = SizeApproximationFlags::INCLUDE_FILES;
1049     if (include_memtable) {
1050       include_flags |= SizeApproximationFlags::INCLUDE_MEMTABLES;
1051     }
1052     GetApproximateSizes(column_family, range, n, sizes, include_flags);
1053   }
1054 
1055   // Compact the underlying storage for the key range [*begin,*end].
1056   // The actual compaction interval might be superset of [*begin, *end].
1057   // In particular, deleted and overwritten versions are discarded,
1058   // and the data is rearranged to reduce the cost of operations
1059   // needed to access the data.  This operation should typically only
1060   // be invoked by users who understand the underlying implementation.
1061   //
1062   // begin==nullptr is treated as a key before all keys in the database.
1063   // end==nullptr is treated as a key after all keys in the database.
1064   // Therefore the following call will compact the entire database:
1065   //    db->CompactRange(options, nullptr, nullptr);
1066   // Note that after the entire database is compacted, all data are pushed
1067   // down to the last level containing any data. If the total data size after
1068   // compaction is reduced, that level might not be appropriate for hosting all
1069   // the files. In this case, client could set options.change_level to true, to
1070   // move the files back to the minimum level capable of holding the data set
1071   // or a given level (specified by non-negative options.target_level).
1072   virtual Status CompactRange(const CompactRangeOptions& options,
1073                               ColumnFamilyHandle* column_family,
1074                               const Slice* begin, const Slice* end) = 0;
CompactRange(const CompactRangeOptions & options,const Slice * begin,const Slice * end)1075   virtual Status CompactRange(const CompactRangeOptions& options,
1076                               const Slice* begin, const Slice* end) {
1077     return CompactRange(options, DefaultColumnFamily(), begin, end);
1078   }
1079 
1080   ROCKSDB_DEPRECATED_FUNC virtual Status CompactRange(
1081       ColumnFamilyHandle* column_family, const Slice* begin, const Slice* end,
1082       bool change_level = false, int target_level = -1,
1083       uint32_t target_path_id = 0) {
1084     CompactRangeOptions options;
1085     options.change_level = change_level;
1086     options.target_level = target_level;
1087     options.target_path_id = target_path_id;
1088     return CompactRange(options, column_family, begin, end);
1089   }
1090 
1091   ROCKSDB_DEPRECATED_FUNC virtual Status CompactRange(
1092       const Slice* begin, const Slice* end, bool change_level = false,
1093       int target_level = -1, uint32_t target_path_id = 0) {
1094     CompactRangeOptions options;
1095     options.change_level = change_level;
1096     options.target_level = target_level;
1097     options.target_path_id = target_path_id;
1098     return CompactRange(options, DefaultColumnFamily(), begin, end);
1099   }
1100 
SetOptions(ColumnFamilyHandle *,const std::unordered_map<std::string,std::string> &)1101   virtual Status SetOptions(
1102       ColumnFamilyHandle* /*column_family*/,
1103       const std::unordered_map<std::string, std::string>& /*new_options*/) {
1104     return Status::NotSupported("Not implemented");
1105   }
SetOptions(const std::unordered_map<std::string,std::string> & new_options)1106   virtual Status SetOptions(
1107       const std::unordered_map<std::string, std::string>& new_options) {
1108     return SetOptions(DefaultColumnFamily(), new_options);
1109   }
1110 
1111   virtual Status SetDBOptions(
1112       const std::unordered_map<std::string, std::string>& new_options) = 0;
1113 
1114   // CompactFiles() inputs a list of files specified by file numbers and
1115   // compacts them to the specified level. Note that the behavior is different
1116   // from CompactRange() in that CompactFiles() performs the compaction job
1117   // using the CURRENT thread.
1118   //
1119   // @see GetDataBaseMetaData
1120   // @see GetColumnFamilyMetaData
1121   virtual Status CompactFiles(
1122       const CompactionOptions& compact_options,
1123       ColumnFamilyHandle* column_family,
1124       const std::vector<std::string>& input_file_names, const int output_level,
1125       const int output_path_id = -1,
1126       std::vector<std::string>* const output_file_names = nullptr,
1127       CompactionJobInfo* compaction_job_info = nullptr) = 0;
1128 
1129   virtual Status CompactFiles(
1130       const CompactionOptions& compact_options,
1131       const std::vector<std::string>& input_file_names, const int output_level,
1132       const int output_path_id = -1,
1133       std::vector<std::string>* const output_file_names = nullptr,
1134       CompactionJobInfo* compaction_job_info = nullptr) {
1135     return CompactFiles(compact_options, DefaultColumnFamily(),
1136                         input_file_names, output_level, output_path_id,
1137                         output_file_names, compaction_job_info);
1138   }
1139 
1140   // This function will wait until all currently running background processes
1141   // finish. After it returns, no background process will be run until
1142   // ContinueBackgroundWork is called
1143   virtual Status PauseBackgroundWork() = 0;
1144   virtual Status ContinueBackgroundWork() = 0;
1145 
1146   // This function will enable automatic compactions for the given column
1147   // families if they were previously disabled. The function will first set the
1148   // disable_auto_compactions option for each column family to 'false', after
1149   // which it will schedule a flush/compaction.
1150   //
1151   // NOTE: Setting disable_auto_compactions to 'false' through SetOptions() API
1152   // does NOT schedule a flush/compaction afterwards, and only changes the
1153   // parameter itself within the column family option.
1154   //
1155   virtual Status EnableAutoCompaction(
1156       const std::vector<ColumnFamilyHandle*>& column_family_handles) = 0;
1157 
1158   virtual void DisableManualCompaction() = 0;
1159   virtual void EnableManualCompaction() = 0;
1160 
1161   // Number of levels used for this DB.
1162   virtual int NumberLevels(ColumnFamilyHandle* column_family) = 0;
NumberLevels()1163   virtual int NumberLevels() { return NumberLevels(DefaultColumnFamily()); }
1164 
1165   // Maximum level to which a new compacted memtable is pushed if it
1166   // does not create overlap.
1167   virtual int MaxMemCompactionLevel(ColumnFamilyHandle* column_family) = 0;
MaxMemCompactionLevel()1168   virtual int MaxMemCompactionLevel() {
1169     return MaxMemCompactionLevel(DefaultColumnFamily());
1170   }
1171 
1172   // Number of files in level-0 that would stop writes.
1173   virtual int Level0StopWriteTrigger(ColumnFamilyHandle* column_family) = 0;
Level0StopWriteTrigger()1174   virtual int Level0StopWriteTrigger() {
1175     return Level0StopWriteTrigger(DefaultColumnFamily());
1176   }
1177 
1178   // Get DB name -- the exact same name that was provided as an argument to
1179   // DB::Open()
1180   virtual const std::string& GetName() const = 0;
1181 
1182   // Get Env object from the DB
1183   virtual Env* GetEnv() const = 0;
1184 
1185   virtual FileSystem* GetFileSystem() const;
1186 
1187   // Get DB Options that we use.  During the process of opening the
1188   // column family, the options provided when calling DB::Open() or
1189   // DB::CreateColumnFamily() will have been "sanitized" and transformed
1190   // in an implementation-defined manner.
1191   virtual Options GetOptions(ColumnFamilyHandle* column_family) const = 0;
GetOptions()1192   virtual Options GetOptions() const {
1193     return GetOptions(DefaultColumnFamily());
1194   }
1195 
1196   virtual DBOptions GetDBOptions() const = 0;
1197 
1198   // Flush all mem-table data.
1199   // Flush a single column family, even when atomic flush is enabled. To flush
1200   // multiple column families, use Flush(options, column_families).
1201   virtual Status Flush(const FlushOptions& options,
1202                        ColumnFamilyHandle* column_family) = 0;
Flush(const FlushOptions & options)1203   virtual Status Flush(const FlushOptions& options) {
1204     return Flush(options, DefaultColumnFamily());
1205   }
1206   // Flushes multiple column families.
1207   // If atomic flush is not enabled, Flush(options, column_families) is
1208   // equivalent to calling Flush(options, column_family) multiple times.
1209   // If atomic flush is enabled, Flush(options, column_families) will flush all
1210   // column families specified in 'column_families' up to the latest sequence
1211   // number at the time when flush is requested.
1212   // Note that RocksDB 5.15 and earlier may not be able to open later versions
1213   // with atomic flush enabled.
1214   virtual Status Flush(
1215       const FlushOptions& options,
1216       const std::vector<ColumnFamilyHandle*>& column_families) = 0;
1217 
1218   // Flush the WAL memory buffer to the file. If sync is true, it calls SyncWAL
1219   // afterwards.
FlushWAL(bool)1220   virtual Status FlushWAL(bool /*sync*/) {
1221     return Status::NotSupported("FlushWAL not implemented");
1222   }
1223   // Sync the wal. Note that Write() followed by SyncWAL() is not exactly the
1224   // same as Write() with sync=true: in the latter case the changes won't be
1225   // visible until the sync is done.
1226   // Currently only works if allow_mmap_writes = false in Options.
1227   virtual Status SyncWAL() = 0;
1228 
1229   // Lock the WAL. Also flushes the WAL after locking.
LockWAL()1230   virtual Status LockWAL() {
1231     return Status::NotSupported("LockWAL not implemented");
1232   }
1233 
1234   // Unlock the WAL.
UnlockWAL()1235   virtual Status UnlockWAL() {
1236     return Status::NotSupported("UnlockWAL not implemented");
1237   }
1238 
1239   // The sequence number of the most recent transaction.
1240   virtual SequenceNumber GetLatestSequenceNumber() const = 0;
1241 
1242   // Instructs DB to preserve deletes with sequence numbers >= passed seqnum.
1243   // Has no effect if DBOptions.preserve_deletes is set to false.
1244   // This function assumes that user calls this function with monotonically
1245   // increasing seqnums (otherwise we can't guarantee that a particular delete
1246   // hasn't been already processed); returns true if the value was successfully
1247   // updated, false if user attempted to call if with seqnum <= current value.
1248   virtual bool SetPreserveDeletesSequenceNumber(SequenceNumber seqnum) = 0;
1249 
1250 #ifndef ROCKSDB_LITE
1251 
1252   // Prevent file deletions. Compactions will continue to occur,
1253   // but no obsolete files will be deleted. Calling this multiple
1254   // times have the same effect as calling it once.
1255   virtual Status DisableFileDeletions() = 0;
1256 
1257   // Allow compactions to delete obsolete files.
1258   // If force == true, the call to EnableFileDeletions() will guarantee that
1259   // file deletions are enabled after the call, even if DisableFileDeletions()
1260   // was called multiple times before.
1261   // If force == false, EnableFileDeletions will only enable file deletion
1262   // after it's been called at least as many times as DisableFileDeletions(),
1263   // enabling the two methods to be called by two threads concurrently without
1264   // synchronization -- i.e., file deletions will be enabled only after both
1265   // threads call EnableFileDeletions()
1266   virtual Status EnableFileDeletions(bool force = true) = 0;
1267 
1268   // GetLiveFiles followed by GetSortedWalFiles can generate a lossless backup
1269 
1270   // Retrieve the list of all files in the database. The files are
1271   // relative to the dbname and are not absolute paths. Despite being relative
1272   // paths, the file names begin with "/". The valid size of the manifest file
1273   // is returned in manifest_file_size. The manifest file is an ever growing
1274   // file, but only the portion specified by manifest_file_size is valid for
1275   // this snapshot. Setting flush_memtable to true does Flush before recording
1276   // the live files. Setting flush_memtable to false is useful when we don't
1277   // want to wait for flush which may have to wait for compaction to complete
1278   // taking an indeterminate time.
1279   //
1280   // In case you have multiple column families, even if flush_memtable is true,
1281   // you still need to call GetSortedWalFiles after GetLiveFiles to compensate
1282   // for new data that arrived to already-flushed column families while other
1283   // column families were flushing
1284   virtual Status GetLiveFiles(std::vector<std::string>&,
1285                               uint64_t* manifest_file_size,
1286                               bool flush_memtable = true) = 0;
1287 
1288   // Retrieve the sorted list of all wal files with earliest file first
1289   virtual Status GetSortedWalFiles(VectorLogPtr& files) = 0;
1290 
1291   // Retrieve information about the current wal file
1292   //
1293   // Note that the log might have rolled after this call in which case
1294   // the current_log_file would not point to the current log file.
1295   //
1296   // Additionally, for the sake of optimization current_log_file->StartSequence
1297   // would always be set to 0
1298   virtual Status GetCurrentWalFile(
1299       std::unique_ptr<LogFile>* current_log_file) = 0;
1300 
1301   // Retrieves the creation time of the oldest file in the DB.
1302   // This API only works if max_open_files = -1, if it is not then
1303   // Status returned is Status::NotSupported()
1304   // The file creation time is set using the env provided to the DB.
1305   // If the DB was created from a very old release then its possible that
1306   // the SST files might not have file_creation_time property and even after
1307   // moving to a newer release its possible that some files never got compacted
1308   // and may not have file_creation_time property. In both the cases
1309   // file_creation_time is considered 0 which means this API will return
1310   // creation_time = 0 as there wouldn't be a timestamp lower than 0.
1311   virtual Status GetCreationTimeOfOldestFile(uint64_t* creation_time) = 0;
1312 
1313   // Note: this API is not yet consistent with WritePrepared transactions.
1314   // Sets iter to an iterator that is positioned at a write-batch containing
1315   // seq_number. If the sequence number is non existent, it returns an iterator
1316   // at the first available seq_no after the requested seq_no
1317   // Returns Status::OK if iterator is valid
1318   // Must set WAL_ttl_seconds or WAL_size_limit_MB to large values to
1319   // use this api, else the WAL files will get
1320   // cleared aggressively and the iterator might keep getting invalid before
1321   // an update is read.
1322   virtual Status GetUpdatesSince(
1323       SequenceNumber seq_number, std::unique_ptr<TransactionLogIterator>* iter,
1324       const TransactionLogIterator::ReadOptions& read_options =
1325           TransactionLogIterator::ReadOptions()) = 0;
1326 
1327 // Windows API macro interference
1328 #undef DeleteFile
1329   // Delete the file name from the db directory and update the internal state to
1330   // reflect that. Supports deletion of sst and log files only. 'name' must be
1331   // path relative to the db directory. eg. 000001.sst, /archive/000003.log
1332   virtual Status DeleteFile(std::string name) = 0;
1333 
1334   // Returns a list of all table files with their level, start key
1335   // and end key
GetLiveFilesMetaData(std::vector<LiveFileMetaData> *)1336   virtual void GetLiveFilesMetaData(
1337       std::vector<LiveFileMetaData>* /*metadata*/) {}
1338 
1339   // Obtains the meta data of the specified column family of the DB.
GetColumnFamilyMetaData(ColumnFamilyHandle *,ColumnFamilyMetaData *)1340   virtual void GetColumnFamilyMetaData(ColumnFamilyHandle* /*column_family*/,
1341                                        ColumnFamilyMetaData* /*metadata*/) {}
1342 
1343   // Get the metadata of the default column family.
GetColumnFamilyMetaData(ColumnFamilyMetaData * metadata)1344   void GetColumnFamilyMetaData(ColumnFamilyMetaData* metadata) {
1345     GetColumnFamilyMetaData(DefaultColumnFamily(), metadata);
1346   }
1347 
1348   // IngestExternalFile() will load a list of external SST files (1) into the DB
1349   // Two primary modes are supported:
1350   // - Duplicate keys in the new files will overwrite exiting keys (default)
1351   // - Duplicate keys will be skipped (set ingest_behind=true)
1352   // In the first mode we will try to find the lowest possible level that
1353   // the file can fit in, and ingest the file into this level (2). A file that
1354   // have a key range that overlap with the memtable key range will require us
1355   // to Flush the memtable first before ingesting the file.
1356   // In the second mode we will always ingest in the bottom most level (see
1357   // docs to IngestExternalFileOptions::ingest_behind).
1358   //
1359   // (1) External SST files can be created using SstFileWriter
1360   // (2) We will try to ingest the files to the lowest possible level
1361   //     even if the file compression doesn't match the level compression
1362   // (3) If IngestExternalFileOptions->ingest_behind is set to true,
1363   //     we always ingest at the bottommost level, which should be reserved
1364   //     for this purpose (see DBOPtions::allow_ingest_behind flag).
1365   virtual Status IngestExternalFile(
1366       ColumnFamilyHandle* column_family,
1367       const std::vector<std::string>& external_files,
1368       const IngestExternalFileOptions& options) = 0;
1369 
IngestExternalFile(const std::vector<std::string> & external_files,const IngestExternalFileOptions & options)1370   virtual Status IngestExternalFile(
1371       const std::vector<std::string>& external_files,
1372       const IngestExternalFileOptions& options) {
1373     return IngestExternalFile(DefaultColumnFamily(), external_files, options);
1374   }
1375 
1376   // IngestExternalFiles() will ingest files for multiple column families, and
1377   // record the result atomically to the MANIFEST.
1378   // If this function returns OK, all column families' ingestion must succeed.
1379   // If this function returns NOK, or the process crashes, then non-of the
1380   // files will be ingested into the database after recovery.
1381   // Note that it is possible for application to observe a mixed state during
1382   // the execution of this function. If the user performs range scan over the
1383   // column families with iterators, iterator on one column family may return
1384   // ingested data, while iterator on other column family returns old data.
1385   // Users can use snapshot for a consistent view of data.
1386   // If your db ingests multiple SST files using this API, i.e. args.size()
1387   // > 1, then RocksDB 5.15 and earlier will not be able to open it.
1388   //
1389   // REQUIRES: each arg corresponds to a different column family: namely, for
1390   // 0 <= i < j < len(args), args[i].column_family != args[j].column_family.
1391   virtual Status IngestExternalFiles(
1392       const std::vector<IngestExternalFileArg>& args) = 0;
1393 
1394   // CreateColumnFamilyWithImport() will create a new column family with
1395   // column_family_name and import external SST files specified in metadata into
1396   // this column family.
1397   // (1) External SST files can be created using SstFileWriter.
1398   // (2) External SST files can be exported from a particular column family in
1399   //     an existing DB.
1400   // Option in import_options specifies whether the external files are copied or
1401   // moved (default is copy). When option specifies copy, managing files at
1402   // external_file_path is caller's responsibility. When option specifies a
1403   // move, the call ensures that the specified files at external_file_path are
1404   // deleted on successful return and files are not modified on any error
1405   // return.
1406   // On error return, column family handle returned will be nullptr.
1407   // ColumnFamily will be present on successful return and will not be present
1408   // on error return. ColumnFamily may be present on any crash during this call.
1409   virtual Status CreateColumnFamilyWithImport(
1410       const ColumnFamilyOptions& options, const std::string& column_family_name,
1411       const ImportColumnFamilyOptions& import_options,
1412       const ExportImportFilesMetaData& metadata,
1413       ColumnFamilyHandle** handle) = 0;
1414 
1415   virtual Status VerifyChecksum(const ReadOptions& read_options) = 0;
1416 
VerifyChecksum()1417   virtual Status VerifyChecksum() { return VerifyChecksum(ReadOptions()); }
1418 
1419   // AddFile() is deprecated, please use IngestExternalFile()
1420   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1421       ColumnFamilyHandle* column_family,
1422       const std::vector<std::string>& file_path_list, bool move_file = false,
1423       bool skip_snapshot_check = false) {
1424     IngestExternalFileOptions ifo;
1425     ifo.move_files = move_file;
1426     ifo.snapshot_consistency = !skip_snapshot_check;
1427     ifo.allow_global_seqno = false;
1428     ifo.allow_blocking_flush = false;
1429     return IngestExternalFile(column_family, file_path_list, ifo);
1430   }
1431 
1432   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1433       const std::vector<std::string>& file_path_list, bool move_file = false,
1434       bool skip_snapshot_check = false) {
1435     IngestExternalFileOptions ifo;
1436     ifo.move_files = move_file;
1437     ifo.snapshot_consistency = !skip_snapshot_check;
1438     ifo.allow_global_seqno = false;
1439     ifo.allow_blocking_flush = false;
1440     return IngestExternalFile(DefaultColumnFamily(), file_path_list, ifo);
1441   }
1442 
1443   // AddFile() is deprecated, please use IngestExternalFile()
1444   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1445       ColumnFamilyHandle* column_family, const std::string& file_path,
1446       bool move_file = false, bool skip_snapshot_check = false) {
1447     IngestExternalFileOptions ifo;
1448     ifo.move_files = move_file;
1449     ifo.snapshot_consistency = !skip_snapshot_check;
1450     ifo.allow_global_seqno = false;
1451     ifo.allow_blocking_flush = false;
1452     return IngestExternalFile(column_family, {file_path}, ifo);
1453   }
1454 
1455   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1456       const std::string& file_path, bool move_file = false,
1457       bool skip_snapshot_check = false) {
1458     IngestExternalFileOptions ifo;
1459     ifo.move_files = move_file;
1460     ifo.snapshot_consistency = !skip_snapshot_check;
1461     ifo.allow_global_seqno = false;
1462     ifo.allow_blocking_flush = false;
1463     return IngestExternalFile(DefaultColumnFamily(), {file_path}, ifo);
1464   }
1465 
1466   // Load table file with information "file_info" into "column_family"
1467   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1468       ColumnFamilyHandle* column_family,
1469       const std::vector<ExternalSstFileInfo>& file_info_list,
1470       bool move_file = false, bool skip_snapshot_check = false) {
1471     std::vector<std::string> external_files;
1472     for (const ExternalSstFileInfo& file_info : file_info_list) {
1473       external_files.push_back(file_info.file_path);
1474     }
1475     IngestExternalFileOptions ifo;
1476     ifo.move_files = move_file;
1477     ifo.snapshot_consistency = !skip_snapshot_check;
1478     ifo.allow_global_seqno = false;
1479     ifo.allow_blocking_flush = false;
1480     return IngestExternalFile(column_family, external_files, ifo);
1481   }
1482 
1483   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1484       const std::vector<ExternalSstFileInfo>& file_info_list,
1485       bool move_file = false, bool skip_snapshot_check = false) {
1486     std::vector<std::string> external_files;
1487     for (const ExternalSstFileInfo& file_info : file_info_list) {
1488       external_files.push_back(file_info.file_path);
1489     }
1490     IngestExternalFileOptions ifo;
1491     ifo.move_files = move_file;
1492     ifo.snapshot_consistency = !skip_snapshot_check;
1493     ifo.allow_global_seqno = false;
1494     ifo.allow_blocking_flush = false;
1495     return IngestExternalFile(DefaultColumnFamily(), external_files, ifo);
1496   }
1497 
1498   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1499       ColumnFamilyHandle* column_family, const ExternalSstFileInfo* file_info,
1500       bool move_file = false, bool skip_snapshot_check = false) {
1501     IngestExternalFileOptions ifo;
1502     ifo.move_files = move_file;
1503     ifo.snapshot_consistency = !skip_snapshot_check;
1504     ifo.allow_global_seqno = false;
1505     ifo.allow_blocking_flush = false;
1506     return IngestExternalFile(column_family, {file_info->file_path}, ifo);
1507   }
1508 
1509   ROCKSDB_DEPRECATED_FUNC virtual Status AddFile(
1510       const ExternalSstFileInfo* file_info, bool move_file = false,
1511       bool skip_snapshot_check = false) {
1512     IngestExternalFileOptions ifo;
1513     ifo.move_files = move_file;
1514     ifo.snapshot_consistency = !skip_snapshot_check;
1515     ifo.allow_global_seqno = false;
1516     ifo.allow_blocking_flush = false;
1517     return IngestExternalFile(DefaultColumnFamily(), {file_info->file_path},
1518                               ifo);
1519   }
1520 
1521 #endif  // ROCKSDB_LITE
1522 
1523   // Returns the unique ID which is read from IDENTITY file during the opening
1524   // of database by setting in the identity variable
1525   // Returns Status::OK if identity could be set properly
1526   virtual Status GetDbIdentity(std::string& identity) const = 0;
1527 
1528   // Returns default column family handle
1529   virtual ColumnFamilyHandle* DefaultColumnFamily() const = 0;
1530 
1531 #ifndef ROCKSDB_LITE
1532   virtual Status GetPropertiesOfAllTables(ColumnFamilyHandle* column_family,
1533                                           TablePropertiesCollection* props) = 0;
GetPropertiesOfAllTables(TablePropertiesCollection * props)1534   virtual Status GetPropertiesOfAllTables(TablePropertiesCollection* props) {
1535     return GetPropertiesOfAllTables(DefaultColumnFamily(), props);
1536   }
1537   virtual Status GetPropertiesOfTablesInRange(
1538       ColumnFamilyHandle* column_family, const Range* range, std::size_t n,
1539       TablePropertiesCollection* props) = 0;
1540 
SuggestCompactRange(ColumnFamilyHandle *,const Slice *,const Slice *)1541   virtual Status SuggestCompactRange(ColumnFamilyHandle* /*column_family*/,
1542                                      const Slice* /*begin*/,
1543                                      const Slice* /*end*/) {
1544     return Status::NotSupported("SuggestCompactRange() is not implemented.");
1545   }
1546 
PromoteL0(ColumnFamilyHandle *,int)1547   virtual Status PromoteL0(ColumnFamilyHandle* /*column_family*/,
1548                            int /*target_level*/) {
1549     return Status::NotSupported("PromoteL0() is not implemented.");
1550   }
1551 
1552   // Trace DB operations. Use EndTrace() to stop tracing.
StartTrace(const TraceOptions &,std::unique_ptr<TraceWriter> &&)1553   virtual Status StartTrace(const TraceOptions& /*options*/,
1554                             std::unique_ptr<TraceWriter>&& /*trace_writer*/) {
1555     return Status::NotSupported("StartTrace() is not implemented.");
1556   }
1557 
EndTrace()1558   virtual Status EndTrace() {
1559     return Status::NotSupported("EndTrace() is not implemented.");
1560   }
1561 
1562   // Trace block cache accesses. Use EndBlockCacheTrace() to stop tracing.
StartBlockCacheTrace(const TraceOptions &,std::unique_ptr<TraceWriter> &&)1563   virtual Status StartBlockCacheTrace(
1564       const TraceOptions& /*options*/,
1565       std::unique_ptr<TraceWriter>&& /*trace_writer*/) {
1566     return Status::NotSupported("StartBlockCacheTrace() is not implemented.");
1567   }
1568 
EndBlockCacheTrace()1569   virtual Status EndBlockCacheTrace() {
1570     return Status::NotSupported("EndBlockCacheTrace() is not implemented.");
1571   }
1572 #endif  // ROCKSDB_LITE
1573 
1574   // Needed for StackableDB
GetRootDB()1575   virtual DB* GetRootDB() { return this; }
1576 
1577   // Given a window [start_time, end_time), setup a StatsHistoryIterator
1578   // to access stats history. Note the start_time and end_time are epoch
1579   // time measured in seconds, and end_time is an exclusive bound.
GetStatsHistory(uint64_t,uint64_t,std::unique_ptr<StatsHistoryIterator> *)1580   virtual Status GetStatsHistory(
1581       uint64_t /*start_time*/, uint64_t /*end_time*/,
1582       std::unique_ptr<StatsHistoryIterator>* /*stats_iterator*/) {
1583     return Status::NotSupported("GetStatsHistory() is not implemented.");
1584   }
1585 
1586 #ifndef ROCKSDB_LITE
1587   // Make the secondary instance catch up with the primary by tailing and
1588   // replaying the MANIFEST and WAL of the primary.
1589   // Column families created by the primary after the secondary instance starts
1590   // will be ignored unless the secondary instance closes and restarts with the
1591   // newly created column families.
1592   // Column families that exist before secondary instance starts and dropped by
1593   // the primary afterwards will be marked as dropped. However, as long as the
1594   // secondary instance does not delete the corresponding column family
1595   // handles, the data of the column family is still accessible to the
1596   // secondary.
1597   // TODO: we will support WAL tailing soon.
TryCatchUpWithPrimary()1598   virtual Status TryCatchUpWithPrimary() {
1599     return Status::NotSupported("Supported only by secondary instance");
1600   }
1601 #endif  // !ROCKSDB_LITE
1602 };
1603 
1604 // Destroy the contents of the specified database.
1605 // Be very careful using this method.
1606 Status DestroyDB(const std::string& name, const Options& options,
1607                  const std::vector<ColumnFamilyDescriptor>& column_families =
1608                      std::vector<ColumnFamilyDescriptor>());
1609 
1610 #ifndef ROCKSDB_LITE
1611 // If a DB cannot be opened, you may attempt to call this method to
1612 // resurrect as much of the contents of the database as possible.
1613 // Some data may be lost, so be careful when calling this function
1614 // on a database that contains important information.
1615 //
1616 // With this API, we will warn and skip data associated with column families not
1617 // specified in column_families.
1618 //
1619 // @param column_families Descriptors for known column families
1620 Status RepairDB(const std::string& dbname, const DBOptions& db_options,
1621                 const std::vector<ColumnFamilyDescriptor>& column_families);
1622 
1623 // @param unknown_cf_opts Options for column families encountered during the
1624 //                        repair that were not specified in column_families.
1625 Status RepairDB(const std::string& dbname, const DBOptions& db_options,
1626                 const std::vector<ColumnFamilyDescriptor>& column_families,
1627                 const ColumnFamilyOptions& unknown_cf_opts);
1628 
1629 // @param options These options will be used for the database and for ALL column
1630 //                families encountered during the repair
1631 Status RepairDB(const std::string& dbname, const Options& options);
1632 
1633 #endif
1634 
1635 }  // namespace ROCKSDB_NAMESPACE
1636