### Example: Set Optimize Filters for Hits Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Options.html Demonstrates how to enable the `optimize_filters_for_hits` option in RocksDB. ```rust use rocksdb::Options; let mut opts = Options::default(); opts.set_optimize_filters_for_hits(true); ``` -------------------------------- ### Examples for is_empty Source: https://docs.rs/rocksdb/0.24.0/rocksdb/properties/struct.PropName.html?search= Demonstrates the usage of the is_empty method for non-empty and empty C strings. ```rust assert!(!c"foo".is_empty()); assert!(c"".is_empty()); ``` -------------------------------- ### Initialize TransactionOptions Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.TransactionOptions.html Creates a new TransactionOptions instance. This is the starting point for configuring transaction behavior. ```rust pub fn new() -> TransactionOptions ``` -------------------------------- ### Options::default Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Options.html Returns the default configuration for the Options struct. This is a convenient way to get a starting point for custom configurations. ```APIDOC ## fn default() -> Self ### Description Returns the “default value” for a type. ### Method `default` ``` -------------------------------- ### Options Configuration Example Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html?search= Demonstrates how to configure general database options for performance tuning and behavior. This includes setting maximum open files, sync behavior, write buffer sizes, and compaction styles. ```APIDOC ## Options Configuration ### Description This section provides an example of how to configure general database-wide options that affect performance and behavior. It covers various tuning parameters. ### Usage ```rust use rocksdb::{Options, DB}; use rocksdb::DBCompactionStyle; fn badly_tuned_for_somebody_elses_disk() -> DB { let path = "path/for/rocksdb/storageX"; let mut opts = Options::default(); opts.create_if_missing(true); opts.set_max_open_files(10000); opts.set_use_fsync(false); opts.set_bytes_per_sync(8388608); opts.optimize_for_point_lookup(1024); opts.set_table_cache_num_shard_bits(6); opts.set_max_write_buffer_number(32); opts.set_write_buffer_size(536870912); opts.set_target_file_size_base(1073741824); opts.set_min_write_buffer_number_to_merge(4); opts.set_level_zero_stop_writes_trigger(2000); opts.set_level_zero_slowdown_writes_trigger(0); opts.set_compaction_style(DBCompactionStyle::Universal); opts.set_disable_auto_compactions(true); DB::open(&opts, path).unwrap() } ``` ``` -------------------------------- ### Get Prepared Transactions Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction_db.rs.html?search= Retrieves all currently prepared transactions. Users must commit or rollback these transactions before starting new ones. ```rust pub fn prepared_transactions(&self) -> Vec> { self.prepared .lock() .unwrap() .drain(0..) .map(|inner| Transaction { inner, _marker: PhantomData, }) .collect() } ``` -------------------------------- ### Open and Use TransactionDB Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.TransactionDB.html Demonstrates how to open a TransactionDB, perform a put operation, and then create, populate, and commit a transaction. Ensure to clean up the database afterwards. ```rust use rocksdb::{DB, Options, TransactionDB, SingleThreaded}; let tempdir = tempfile::Builder::new() .prefix("_path_for_transaction_db") .tempdir() .expect("Failed to create temporary path for the _path_for_transaction_db"); let path = tempdir.path(); { let db: TransactionDB = TransactionDB::open_default(path).unwrap(); db.put(b"my key", b"my value").unwrap(); // create transaction let txn = db.transaction(); txn.put(b"key2", b"value2"); txn.put(b"key3", b"value3"); txn.commit().unwrap(); } let _ = DB::destroy(&Options::default(), path); ``` -------------------------------- ### BackupEngine::open Source: https://docs.rs/rocksdb/0.24.0/rocksdb/backup/struct.BackupEngine.html Opens a BackupEngine instance with the specified options and environment. This is the entry point for all backup operations. ```APIDOC ## BackupEngine::open ### Description Opens a backup engine with the specified options and RocksDB Env. ### Method `pub fn open(opts: &BackupEngineOptions, env: &Env) -> Result` ### Parameters * `opts` (*`BackupEngineOptions`*) - The options for the backup engine. * `env` (*`Env`*) - The RocksDB environment. ### Returns A `Result` containing the `BackupEngine` instance on success, or an `Error` on failure. ``` -------------------------------- ### Iterating Chunks from the End of a Slice Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBPinnableSlice.html Use `rchunks` to get an iterator over chunks of a specified size starting from the end of the slice. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### FlushOptions Default Example Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html Demonstrates creating a `FlushOptions` object with default settings. This is typically used to configure flush operations. ```rust impl FlushOptions { pub fn new() -> FlushOptions { FlushOptions::default() } /// Waits until the flush is done. /// /// Default: true /// /// # Examples /// /// ``` /// use rocksdb::FlushOptions; /// /// let mut options = FlushOptions::default(); /// ``` -------------------------------- ### DBIteratorWithThreadMode Usage Examples Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_iterator.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates various ways to use the `DBIteratorWithThreadMode` to iterate through the database. This includes iterating from the start, from the end, from a specific key in forward or reverse direction, and changing the mode of an existing iterator. ```APIDOC ## Iterator Modes and Directions This section illustrates the usage of `DBIteratorWithThreadMode` with different `IteratorMode` and `Direction` settings. ### Iterating from the Start (Forward) ```rust let mut iter = db.iterator(IteratorMode::Start); // Always iterates forward for item in iter { let (key, value) = item.unwrap(); println!("Saw {:?}", key); } ``` ### Iterating from the End (Backward) ```rust let mut iter = db.iterator(IteratorMode::End); // Always iterates backward for item in iter { let (key, value) = item.unwrap(); println!("Saw {:?}", key); } ``` ### Iterating from a Specific Key This demonstrates iterating from a specified key with a chosen direction. ```rust // From a key in Direction::Forward let mut iter = db.iterator(IteratorMode::From(b"my key", Direction::Forward)); for item in iter { let (key, value) = item.unwrap(); println!("Saw {:?}", key); } // From a key in Direction::Reverse let mut iter = db.iterator(IteratorMode::From(b"another key", Direction::Reverse)); for item in iter { let (key, value) = item.unwrap(); println!("Saw {:?}", key); } ``` ### Changing Iterator Mode An existing iterator's mode can be updated using `set_mode`. ```rust // You can seek with an existing Iterator instance, too let mut iter = db.iterator(IteratorMode::Start); iter.set_mode(IteratorMode::From(b"another key", Direction::Reverse)); for item in iter { let (key, value) = item.unwrap(); println!("Saw {:?}", key); } ``` ### `IteratorMode` Enum Defines the different modes for iterating through the database. - **Start**: Start iteration from the first key. - **End**: Start iteration from the last key. - **From(key, direction)**: Start iteration from the specified `key` with the given `direction`. ### `Direction` Enum Specifies the iteration direction. - **Forward**: Iterate from lower keys to higher keys. - **Reverse**: Iterate from higher keys to lower keys. ``` -------------------------------- ### Get Element Index from Reference Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBPinnableSlice.html Use `element_offset` to find the index of an element within a slice given a reference to it. This method uses pointer arithmetic and does not compare elements. Returns `None` if the reference does not point to the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### TransactionDB Usage Example Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction_db.rs.html?search=std%3A%3Avec Demonstrates how to open a TransactionDB, perform basic put operations, create a transaction, and commit changes. ```APIDOC ## TransactionDB Open and Basic Operations ### Description This example shows how to initialize a `TransactionDB` using `open_default`, perform a simple `put` operation directly on the DB, and then demonstrates the creation and commitment of a transaction. ### Method `TransactionDB::open_default(path)` `db.put(key, value)` `db.transaction()` `txn.put(key, value)` `txn.commit()` ### Endpoint N/A (SDK Method Calls) ### Parameters N/A (SDK Method Calls) ### Request Example ```rust use rocksdb::{DB, Options, TransactionDB, SingleThreaded}; let tempdir = tempfile::Builder::new() .prefix("_path_for_transaction_db") .tempdir() .expect("Failed to create temporary path for the _path_for_transaction_db"); let path = tempdir.path(); { let db: TransactionDB = TransactionDB::open_default(path).unwrap(); db.put(b"my key", b"my value").unwrap(); // create transaction let txn = db.transaction(); txn.put(b"key2", b"value2"); txn.put(b"key3", b"value3"); txn.commit().unwrap(); } let _ = DB::destroy(&Options::default(), path); ``` ### Response N/A (SDK Method Calls - operations return `Result` types) ``` -------------------------------- ### Range::new Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Range.html?search= Constructs a new Range with specified start and end keys. The start key is inclusive, and the end key is exclusive. Ensure that the end key is not less than the start key. ```APIDOC ## Range::new ### Description Constructs a new `Range` with specified start and end keys. The start key is inclusive, and the end key is exclusive. Ensure that the end key is not less than the start key. ### Signature `pub fn new(start_key: &'a [u8], end_key: &'a [u8]) -> Range<'a>` ### Parameters * `start_key` (&'a [u8]): The inclusive start key of the range. * `end_key` (&'a [u8]): The exclusive end key of the range. ``` -------------------------------- ### Create and Default UniversalCompactionOptions Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html Demonstrates how to create and initialize UniversalCompactOptions to their default values. This is typically the first step before configuring specific options. ```rust impl Default for UniversalCompactOptions { fn default() -> Self { let opts = unsafe { ffi::rocksdb_universal_compaction_options_create() }; assert!( !opts.is_null(), "Could not create RocksDB Universal Compaction Options" ); Self { inner: opts } } } ``` -------------------------------- ### Initialize BackupEngineOptions Source: https://docs.rs/rocksdb/0.24.0/rocksdb/backup/struct.BackupEngineOptions.html?search= Initializes BackupEngineOptions with a specified directory for backup storage. This is the first step in configuring backup operations. ```rust pub struct BackupEngineOptions { /* private fields */ } ``` -------------------------------- ### Set Iterator Start Timestamp Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html Configures the starting timestamp for iterators within ReadOptions. ```rust unsafe { ffi::rocksdb_readoptions_set_iter_start_ts(self.inner, ptr, len); } ``` -------------------------------- ### BackupEngineOptions::new Source: https://docs.rs/rocksdb/0.24.0/rocksdb/backup/struct.BackupEngineOptions.html?search=u32+-%3E+bool Initializes BackupEngineOptions with the directory for backup files. ```APIDOC ## BackupEngineOptions::new ### Description Initializes `BackupEngineOptions` with the directory to be used for storing/accessing the backup files. ### Method `new>(backup_dir: P) -> Result` ### Parameters #### Path Parameters - **backup_dir** (P: AsRef) - Required - The directory path for backup files. ### Response #### Success Response - **Self** (BackupEngineOptions) - An initialized BackupEngineOptions instance. - **Error** - If initialization fails. ``` -------------------------------- ### Get Type ID Source: https://docs.rs/rocksdb/0.24.0/rocksdb/backup/struct.BackupEngine.html Gets the `TypeId` of the `BackupEngine` instance. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### SstFileWriter::create Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.SstFileWriter.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new SstFileWriter instance with the provided database options. This is the entry point for creating SST files. ```APIDOC ## SstFileWriter::create ### Description Initializes SstFileWriter with given DB options. ### Method `pub fn create(opts: &'a Options) -> Self` ### Parameters * `opts` ('a Options): A reference to the database options to configure the file writer. ``` -------------------------------- ### CStr Is Empty Examples Source: https://docs.rs/rocksdb/0.24.0/rocksdb/properties/struct.PropName.html Examples showing how to use `is_empty` to check if a C string is empty or not. ```rust assert!(!c"foo".is_empty()); assert!(c"".is_empty()); ``` -------------------------------- ### CStr Bytes Iterator Example (Nightly) Source: https://docs.rs/rocksdb/0.24.0/rocksdb/properties/struct.PropName.html Example usage of the experimental `bytes` iterator for C strings. ```rust #![feature(cstr_bytes)] assert!(c"foo".bytes().eq(*b"foo")); ``` -------------------------------- ### TransactionDB Usage Example Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction_db.rs.html?search=u32+-%3E+bool Demonstrates how to open a TransactionDB, perform a basic put operation, create a transaction, and commit changes within that transaction. ```APIDOC ## TransactionDB ### Description RocksDB TransactionDB allows for ACID transactions. This example shows basic usage. ### Method `TransactionDB::open_default(path)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **path** (*PathBuf*) - The file system path where the database will be opened or created. ### Request Example ```rust use rocksdb::{DB, Options, TransactionDB, SingleThreaded}; let tempdir = tempfile::Builder::new() .prefix("_path_for_transaction_db") .tempdir() .expect("Failed to create temporary path for the _path_for_transaction_db"); let path = tempdir.path(); { let db: TransactionDB = TransactionDB::open_default(path).unwrap(); db.put(b"my key", b"my value").unwrap(); // create transaction let txn = db.transaction(); txn.put(b"key2", b"value2"); txn.put(b"key3", b"value3"); txn.commit().unwrap(); } let _ = DB::destroy(&Options::default(), path); ``` ### Response #### Success Response - The `TransactionDB` is opened successfully, and operations within the transaction are committed. #### Response Example N/A (Illustrative code example) ``` -------------------------------- ### CStr Byte Count Examples Source: https://docs.rs/rocksdb/0.24.0/rocksdb/properties/struct.PropName.html Examples demonstrating the usage of `count_bytes` for non-empty and empty C strings. ```rust assert_eq!(c"foo".count_bytes(), 3); assert_eq!(c"".count_bytes(), 0); ``` -------------------------------- ### Open Database with Options Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBCommon.html?search=u32+-%3E+bool Opens the database with specified options. Use this to customize database behavior. ```rust pub fn open>(opts: &Options, path: P) -> Result ``` -------------------------------- ### Example: Set Max Open Files Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Options.html Demonstrates how to set the maximum number of open files for RocksDB. ```rust use rocksdb::Options; let mut opts = Options::default(); opts.set_max_open_files(10); ``` -------------------------------- ### Iterate All Keys from Start Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBRawIteratorWithThreadMode.html Demonstrates how to iterate through all keys in a RocksDB database in lexicographical order starting from the first key. Ensures the iterator is valid before processing. ```rust use rocksdb::{DB, Options}; let tempdir = tempfile::Builder::new() .prefix("_path_for_rocksdb_storage5") .tempdir() .expect("Failed to create temporary path for the _path_for_rocksdb_storage5."); let path = tempdir.path(); { let db = DB::open_default(path).unwrap(); let mut iter = db.raw_iterator(); // Iterate all keys from the start in lexicographic order iter.seek_to_first(); while iter.valid() { println!("{:?} {:?}", iter.key(), iter.value()); iter.next(); } // Read just the first key iter.seek_to_first(); if iter.valid() { println!("{:?} {:?}", iter.key(), iter.value()); } else { // There are no keys in the database } } let _ = DB::destroy(&Options::default(), path); ``` -------------------------------- ### RocksDB Range Struct Definition Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Range.html?search= Defines a range of keys where the start key is included, but the end key is not. Ensure the end key is not less than the start key. ```rust pub struct Range<'a> { /* private fields */ } ``` -------------------------------- ### TransactionDB Usage Example Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction_db.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to open a TransactionDB, perform a simple put operation, create a transaction, add key-value pairs within the transaction, and commit the transaction. It also shows how to clean up the database afterwards. ```APIDOC ## TransactionDB Example ### Description This example shows the basic usage of `TransactionDB` for transactional operations. It covers opening the database, performing a direct `put`, creating a new transaction, modifying data within the transaction, committing the transaction, and finally closing and destroying the database. ### Method ```rust TransactionDB::open_default(path: &Path) -> Result ``` ### Endpoint N/A (This is an SDK example, not an HTTP endpoint) ### Parameters - **path** (`&Path`): The file system path where the database is located. ### Request Example ```rust use rocksdb::{DB, Options, TransactionDB, SingleThreaded}; let tempdir = tempfile::Builder::new() .prefix("_path_for_transaction_db") .tempdir() .expect("Failed to create temporary path for the _path_for_transaction_db"); let path = tempdir.path(); { let db: TransactionDB = TransactionDB::open_default(path).unwrap(); db.put(b"my key", b"my value").unwrap(); // create transaction let txn = db.transaction(); txn.put(b"key2", b"value2"); txn.put(b"key3", b"value3"); txn.commit().unwrap(); } let _ = DB::destroy(&Options::default(), path); ``` ### Response - **Success Response**: The code executes without returning an `Error`. ### Response Example N/A (This is an SDK example, not an HTTP endpoint) ``` -------------------------------- ### Example: Set Use Fsync Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Options.html Demonstrates how to configure RocksDB to use `fsync` instead of `fdatasync` for data persistence. ```rust use rocksdb::Options; let mut opts = Options::default(); opts.set_use_fsync(true); ``` -------------------------------- ### Range struct definition Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db.rs.html?search= Defines a key range for operations, where the start key is inclusive and the end key is exclusive. Ensure the end key is not less than the start key. ```rust pub struct Range<'a> { start_key: &'a [u8], end_key: &'a [u8>, } impl<'a> Range<'a> { pub fn new(start_key: &'a [u8], end_key: &'a [u8>) -> Range<'a> { Range { start_key, end_key } } } ``` -------------------------------- ### Range Implementation for IterateBounds Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/iter_range.rs.html?search=std%3A%3Avec Implements `IterateBounds` for `std::ops::Range` (representing `start..end`), converting the start and end keys into optional byte vectors. ```rust impl>> IterateBounds for std::ops::Range { fn into_bounds(self) -> (Option>, Option>) { (Some(self.start.into()), Some(self.end.into())) } } ``` -------------------------------- ### Open and Use OptimisticTransactionDB Source: https://docs.rs/rocksdb/0.24.0/rocksdb/type.OptimisticTransactionDB.html?search= Demonstrates how to open an OptimisticTransactionDB with default options, perform a put operation, and then create and commit a transaction with multiple put operations. ```rust use rocksdb::{DB, Options, OptimisticTransactionDB, SingleThreaded}; let tempdir = tempfile::Builder::new() .prefix("_path_for_optimistic_transaction_db") .tempdir() .expect("Failed to create temporary path for the _path_for_optimistic_transaction_db"); let path = tempdir.path(); { let db: OptimisticTransactionDB = OptimisticTransactionDB::open_default(path).unwrap(); db.put(b"my key", b"my value").unwrap(); // create transaction let txn = db.transaction(); txn.put(b"key2", b"value2"); txn.put(b"key3", b"value3"); txn.commit().unwrap(); } let _ = DB::destroy(&Options::default(), path); ``` -------------------------------- ### CompactOptions Default Implementation Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.CompactOptions.html?search=std%3A%3Avec Provides documentation for the default implementation of CompactOptions, allowing creation of a default instance. ```APIDOC ## fn default() -> Self ### Description Returns the “default value” for a type. ### Method `default` ### Returns `Self` - The default CompactOptions instance. ``` -------------------------------- ### Test Compaction Filter Logic Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/compaction_filter.rs.html?search= A simple test filter function that demonstrates the Decision types. It removes keys starting with '_', changes values for keys starting with '%', and keeps others. ```rust fn test_filter(level: u32, key: &[u8], value: &[u8]) -> Decision { use self::Decision::{Change, Keep, Remove}; match key.first() { Some(&b'_') => Remove, Some(&b'%') => Change(b"secret"), _ => Keep, } } ``` -------------------------------- ### Iterating from a Specific Key with DBIterator Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_iterator.rs.html?search=std%3A%3Avec Shows how to create a DBIterator that starts iterating from a specific key, allowing for targeted data retrieval. You can specify the starting key and the direction (Forward or Reverse). ```rust iter = db.iterator(IteratorMode::From(b"my key", Direction::Forward)); // From a key in Direction::{forward,reverse} for item in iter { let (key, value) = item.unwrap(); println!("Saw {:?" {:?}, key, value); } ``` -------------------------------- ### Initialize SstFileWriter Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.SstFileWriter.html Initializes an SstFileWriter instance with the provided database options. This is the first step before opening a file for writing. ```rust pub fn create(opts: &'a Options) -> Self ``` -------------------------------- ### Get Pinned Value by Key with Read Options Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction_db.rs.html?search= Retrieves a pinned reference to the value associated with a key, using specified read options. This is the underlying method for many other get operations. ```rust pub fn get_pinned_opt>( &self, key: K, readopts: &ReadOptions, ) -> Result, Error> { let key = key.as_ref(); unsafe { let val = ffi_try!(ffi::rocksdb_transactiondb_get_pinned( self.inner, readopts.inner, key.as_ptr() as *const c_char, key.len() as size_t, )); if val.is_null() { Ok(None) } else { Ok(Some(DBPinnableSlice::from_c(val))) } } } ``` -------------------------------- ### Create Default CompactOptions Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html Creates a new `CompactOptions` instance with default settings. This is the starting point for configuring manual compaction. ```rust let opts = unsafe { ffi::rocksdb_compactoptions_create() }; assert!(!opts.is_null(), "Could not create RocksDB Compact Options"); Self { inner: opts, full_history_ts_low: None, } ``` -------------------------------- ### DBRawIteratorWithThreadMode Example Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBRawIteratorWithThreadMode.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates forward, reverse, and seeking iteration using DBRawIteratorWithThreadMode. Includes opening a database, iterating, and seeking to specific keys. ```rust use rocksdb::{DB, Options}; let tempdir = tempfile::Builder::new() .prefix("_path_for_rocksdb_storage4") .tempdir() .expect("Failed to create temporary path for the _path_for_rocksdb_storage4."); let path = tempdir.path(); { let db = DB::open_default(path).unwrap(); let mut iter = db.raw_iterator(); // Forwards iteration iter.seek_to_first(); while iter.valid() { println!("Saw {:?}"", iter.key(), iter.value()); iter.next(); } // Reverse iteration iter.seek_to_last(); while iter.valid() { println!("Saw {:?}"", iter.key(), iter.value()); iter.prev(); } // Seeking iter.seek(b"my key"); while iter.valid() { println!("Saw {:?}"", iter.key(), iter.value()); iter.next(); } // Reverse iteration from key // Note, use seek_for_prev when reversing because if this key doesn't exist, // this will make the iterator start from the previous key rather than the next. iter.seek_for_prev(b"my key"); while iter.valid() { println!("Saw {:?}"", iter.key(), iter.value()); iter.prev(); } } let _ = DB::destroy(&Options::default(), path); ``` -------------------------------- ### RangeFrom Implementation for IterateBounds Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/iter_range.rs.html?search=std%3A%3Avec Implements `IterateBounds` for `std::ops::RangeFrom` (representing `start..`), converting the start key into an optional byte vector and leaving the upper bound as None. ```rust impl>> IterateBounds for std::ops::RangeFrom { fn into_bounds(self) -> (Option>, Option>) { (Some(self.start.into()), None) } } ``` -------------------------------- ### IteratorMode Enum Definition Source: https://docs.rs/rocksdb/0.24.0/rocksdb/enum.IteratorMode.html?search=u32+-%3E+bool Defines the possible modes for iterating over a RocksDB database. Use Start for forward iteration from the beginning, End for backward iteration from the end, or From to specify a starting key and direction. ```rust pub enum IteratorMode<'a> { Start, End, From(&'a [u8], Direction), } ``` -------------------------------- ### Enable Create If Missing Option Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html?search=u32+-%3E+bool Sets the option to automatically create the database if it does not exist when opening. Use this when you want to ensure the database is available without manual pre-creation. ```rust pub fn create_if_missing(&mut self, create_if_missing: bool) { unsafe { ffi::rocksdb_options_set_create_if_missing( self.inner, c_uchar::from(create_if_missing), ); } } ``` ```rust use rocksdb::Options; let mut opts = Options::default(); opts.create_if_missing(true); ``` -------------------------------- ### Open RocksDB with Custom Column Families Source: https://docs.rs/rocksdb/0.24.0/index.html Shows how to open a RocksDB database with a single custom column family and specific options for that family and the database itself. Requires `tempfile` for temporary storage. ```rust use rocksdb::{DB, ColumnFamilyDescriptor, Options}; let tempdir = tempfile::Builder::new() .prefix("_path_for_rocksdb_storage_with_cfs") .tempdir() .expect("Failed to create temporary path for the _path_for_rocksdb_storage_with_cfs."); let path = tempdir.path(); let mut cf_opts = Options::default(); cf_opts.set_max_write_buffer_number(16); let cf = ColumnFamilyDescriptor::new("cf1", cf_opts); let mut db_opts = Options::default(); db_opts.create_missing_column_families(true); db_opts.create_if_missing(true); { let db = DB::open_cf_descriptors(&db_opts, path, vec![cf]).unwrap(); } let _ = DB::destroy(&db_opts, path); ``` -------------------------------- ### IterateBounds Trait Definition Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/iter_range.rs.html?search=u32+-%3E+bool Defines the contract for types that can be converted into iteration bounds (lower and upper). Implementations determine how ranges like 'all', 'start..end', 'start..', and '..end' are represented. ```rust pub trait IterateBounds { /// Converts object into lower and upper bounds pair. /// /// If this object represents range with one of the bounds unset, /// corresponding element is returned as `None`. For example, `..upper` /// range would be converted into `(None, Some(upper))` pair. fn into_bounds(self) -> (Option>, Option>); } ``` -------------------------------- ### Open Database with Column Families and Options Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBCommon.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Opens a database with specified column family names and their associated options. Provides custom configurations for each column family. ```rust pub fn open_cf_with_opts( opts: &Options, path: P, cfs: I, ) -> Result where P: AsRef, I: IntoIterator, N: AsRef ``` -------------------------------- ### Compaction Filter Integration Test Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/compaction_filter.rs.html?search= This test sets up a RocksDB instance with a custom compaction filter and verifies its behavior by inserting, compacting, and retrieving data. It checks that keys starting with '_' are removed and keys starting with '%' are changed. ```rust use crate::{Options, DB}; let tempdir = tempfile::Builder::new() .prefix("_rust_rocksdb_filter_test") .tempdir() .expect("Failed to create temporary path for the _rust_rocksdb_filter_test"); let path = tempdir.path(); let mut opts = Options::default(); opts.create_if_missing(true); opts.set_compaction_filter("test", test_filter); { let db = DB::open(&opts, path).unwrap(); let _r = db.put(b"k1", b"a"); let _r = db.put(b"_k", b"b"); let _r = db.put(b"%k", b"c"); db.compact_range(None::<&[u8]>, None::<&[u8]>); assert_eq!(&*db.get(b"k1").unwrap().unwrap(), b"a"); assert!(db.get(b"_k").unwrap().is_none()); assert_eq!(&*db.get(b"%k").unwrap().unwrap(), b"secret"); } let result = DB::destroy(&opts, path); assert!(result.is_ok()); ``` -------------------------------- ### Basic RocksDB Operations Source: https://docs.rs/rocksdb/0.24.0/index.html Demonstrates opening a default RocksDB database, putting, getting, and deleting a key-value pair. Ensure the `tempfile` crate is available for temporary directory creation. ```rust use rocksdb::{DB, Options}; // NB: db is automatically closed at end of lifetime let tempdir = tempfile::Builder::new() .prefix("_path_for_rocksdb_storage") .tempdir() .expect("Failed to create temporary path for the _path_for_rocksdb_storage"); let path = tempdir.path(); { let db = DB::open_default(path).unwrap(); db.put(b"my key", b"my value").unwrap(); match db.get(b"my key") { Ok(Some(value)) => println!("retrieved value {}", String::from_utf8(value).unwrap()), Ok(None) => println!("value not found"), Err(e) => println!("operational problem encountered: {}", e), } db.delete(b"my key").unwrap(); } let _ = DB::destroy(&Options::default(), path); ``` -------------------------------- ### Rust Example: String Concatenation Merge Operator Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/merge_operator.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to implement a custom merge operator in Rust that concatenates string values. This example shows the function signature, how to handle existing values and operands, and how to use it with RocksDB options. ```rust use rocksdb::{Options, DB, MergeOperands}; fn concat_merge(new_key: &[u8], existing_val: Option<&[u8]>, operands: &MergeOperands) -> Option> { let mut result: Vec = Vec::with_capacity(operands.len()); existing_val.map(|v| { for e in v { result.push(*e) } }); for op in operands { for e in op { result.push(*e) } } Some(result) } let tempdir = tempfile::Builder::new() .prefix("_rust_path_to_rocksdb") .tempdir() .expect("Failed to create temporary path for the _rust_path_to_rocksdb"); let path = tempdir.path(); let mut opts = Options::default(); opts.create_if_missing(true); opts.set_merge_operator_associative("test operator", concat_merge); { let db = DB::open(&opts, path).unwrap(); let p = db.put(b"k1", b"a"); db.merge(b"k1", b"b"); db.merge(b"k1", b"c"); db.merge(b"k1", b"d"); db.merge(b"k1", b"efg"); let r = db.get(b"k1"); assert_eq!(r.unwrap().unwrap(), b"abcdefg"); } let _ = DB::destroy(&opts, path); ``` -------------------------------- ### Open Database with Column Families and Options Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBCommon.html?search=u32+-%3E+bool Opens a database with specified database options and column family names, each with its own Options. ```rust pub fn open_cf_with_opts( opts: &Options, path: P, cfs: I, ) -> Result where P: AsRef, I: IntoIterator, N: AsRef, ``` -------------------------------- ### set_min_level_to_compress Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Options.html?search=std%3A%3Avec Sets the start level to use compression. ```APIDOC ## set_min_level_to_compress ### Description Sets the start level to use compression. ### Method `set_min_level_to_compress` ### Parameters - `lvl` (c_int) - The minimum level to start compression from. ### Example (No example provided in source) ``` -------------------------------- ### FlushOptions::new Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.FlushOptions.html?search=std%3A%3Avec Creates a new FlushOptions instance with default settings. ```APIDOC ## FlushOptions::new ### Description Creates a new `FlushOptions` instance with default settings. ### Returns A new `FlushOptions` instance. ``` -------------------------------- ### Get Transaction Name Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the name of the transaction. ```APIDOC ## get_name ### Description Retrieves the name of the transaction. ### Method `get_name(&self) -> Option>` ### Returns - `Some(Vec)` containing the transaction name if it exists. - `None` if the transaction does not have a name. ``` -------------------------------- ### Open Default Database Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBCommon.html?search=u32+-%3E+bool Opens a database with default options. Use this for a simple database setup. ```rust pub fn open_default>(path: P) -> Result ``` -------------------------------- ### Get TTL of ColumnFamilyDescriptor Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.ColumnFamilyDescriptor.html Retrieves the TTL of the ColumnFamilyDescriptor. ```rust pub fn ttl(&self) -> ColumnFamilyTtl ``` -------------------------------- ### Prepare for Bulk Load Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.Options.html Prepares the database for bulk loading by placing all data in level 0 without automatic compaction. Manual compaction is recommended before reading. ```rust pub fn prepare_for_bulk_load(&mut self) ``` -------------------------------- ### Get Name of ColumnFamilyDescriptor Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.ColumnFamilyDescriptor.html Retrieves the name of the ColumnFamilyDescriptor. ```rust pub fn name(&self) -> &str ``` -------------------------------- ### starts_with Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBPinnableSlice.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Checks if a slice starts with a given prefix slice. ```APIDOC ## starts_with ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Signature ```rust pub fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq, ``` ### Parameters * `needle`: `&[T]` - The slice to check if it's a prefix. ### Returns `true` if the slice starts with `needle`, `false` otherwise. ### Examples ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); // Always returns `true` if `needle` is an empty slice: let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` ``` -------------------------------- ### Example for to_bytes Source: https://docs.rs/rocksdb/0.24.0/rocksdb/properties/struct.PropName.html?search= Shows how to convert a C string to a byte slice using the to_bytes method. ```rust assert_eq!(c"foo".to_bytes(), b"foo"); ``` -------------------------------- ### strip_prefix Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBPinnableSlice.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## strip_prefix

(&self, prefix: &P) -> Option<&[T]> ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - **prefix** (&P) - Required - The prefix pattern to remove. ### Returns - **Option<&[T]>** - The subslice after the prefix if found, otherwise None. ``` -------------------------------- ### Prepare for Bulk Load Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html?search= Prepares the database for bulk loading by placing all data in level 0 without automatic compaction. Manual compaction is recommended before reading to avoid slow reads. ```rust pub fn prepare_for_bulk_load(&mut self) { unsafe { ffi::rocksdb_options_prepare_for_bulk_load(self.inner); } } ``` -------------------------------- ### Env::join_all_threads Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/env.rs.html Waits for all threads started by `Env::StartThread` to terminate. ```APIDOC ## Env::join_all_threads ### Description Waits for all threads started by `Env::StartThread` to terminate. This ensures that all background operations are completed before proceeding. ``` -------------------------------- ### Open TransactionDB with Options Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/transactions/transaction_db.rs.html?search= Opens a TransactionDB using specified database and transaction options. This is a foundational method for database initialization. ```rust pub fn open>( opts: &Options, txn_db_opts: &TransactionDBOptions, path: P, ) -> Result { Self::open_cf(opts, txn_db_opts, path, None::<&str>) } ``` -------------------------------- ### iter Source: https://docs.rs/rocksdb/0.24.0/rocksdb/struct.DBPinnableSlice.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Create Universal Compaction Options Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_options.rs.html?search=u32+-%3E+bool Initializes new universal compaction options. Ensure that the returned pointer is not null. ```rust let opts = unsafe { ffi::rocksdb_universal_compaction_options_create() }; assert!( !opts.is_null(), "Could not create RocksDB Universal Compaction Options" ); ``` -------------------------------- ### Open Backup Engine Source: https://docs.rs/rocksdb/0.24.0/rocksdb/backup/struct.BackupEngine.html Opens a backup engine with specified options and environment. Ensure BackupEngineOptions and Env are correctly configured. ```rust pub fn open(opts: &BackupEngineOptions, env: &Env) -> Result ``` -------------------------------- ### MemoryUsage::approximate_cache_total Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/perf.rs.html Gets the approximate total memory usage by the cache. ```APIDOC ## MemoryUsage::approximate_cache_total ### Description Gets the approximate total memory usage by the cache. ### Method `approximate_cache_total` ### Parameters None ### Request Example ```rust // Assuming memory_usage is an instance of MemoryUsage let total_cache_usage = memory_usage.approximate_cache_total(); ``` ### Response #### Success Response - **u64** - The approximate memory usage in bytes for the cache. ``` -------------------------------- ### DBRawIterator Usage Example Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/db_iterator.rs.html?search=std%3A%3Avec Demonstrates how to use DBRawIterator for forward and reverse iteration, seeking to specific keys, and seeking for previous keys. ```APIDOC ## DBRawIterator Usage Example ### Description This example showcases the fundamental operations of `DBRawIterator`, including iterating forwards and backwards through the database, seeking to the first or last element, and seeking to a specific key or the key immediately preceding it. ### Method `DB::raw_iterator()` and `DB::raw_iterator_cf()` are used to create instances of `DBRawIterator`. ### Endpoint N/A (This is an SDK example, not an HTTP endpoint) ### Parameters N/A ### Request Example ```rust use rocksdb::{DB, Options}; let tempdir = tempfile::Builder::new() .prefix("_path_for_rocksdb_storage4") .tempdir() .expect("Failed to create temporary path for the _path_for_rocksdb_storage4."); let path = tempdir.path(); { let db = DB::open_default(path).unwrap(); let mut iter = db.raw_iterator(); // Forwards iteration iter.seek_to_first(); while iter.valid() { println!("Saw {:?} {:?}", iter.key(), iter.value()); iter.next(); } // Reverse iteration iter.seek_to_last(); while iter.valid() { println!("Saw {:?} {:?}", iter.key(), iter.value()); iter.prev(); } // Seeking iter.seek(b"my key"); while iter.valid() { println!("Saw {:?} {:?}", iter.key(), iter.value()); iter.next(); } // Reverse iteration from key // Note, use seek_for_prev when reversing because if this key doesn't exist, // this will make the iterator start from the previous key rather than the next. iter.seek_for_prev(b"my key"); while iter.valid() { println!("Saw {:?} {:?}", iter.key(), iter.value()); iter.prev(); } } let _ = DB::destroy(&Options::default(), path); ``` ### Response N/A (This is an SDK example, not an HTTP endpoint) ### Error Handling N/A ``` -------------------------------- ### MemoryUsage::approximate_mem_table_readers_total Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/perf.rs.html Gets the approximate memory usage of all table readers. ```APIDOC ## MemoryUsage::approximate_mem_table_readers_total ### Description Gets the approximate memory usage of all table readers. ### Method `approximate_mem_table_readers_total` ### Parameters None ### Request Example ```rust // Assuming memory_usage is an instance of MemoryUsage let total_table_reader_usage = memory_usage.approximate_mem_table_readers_total(); ``` ### Response #### Success Response - **u64** - The approximate memory usage in bytes for table readers. ``` -------------------------------- ### MemoryUsage::approximate_mem_table_unflushed Source: https://docs.rs/rocksdb/0.24.0/src/rocksdb/perf.rs.html Gets the approximate memory usage of un-flushed mem-tables. ```APIDOC ## MemoryUsage::approximate_mem_table_unflushed ### Description Gets the approximate memory usage of un-flushed mem-tables. ### Method `approximate_mem_table_unflushed` ### Parameters None ### Request Example ```rust // Assuming memory_usage is an instance of MemoryUsage let unflushed_mem_table_usage = memory_usage.approximate_mem_table_unflushed(); ``` ### Response #### Success Response - **u64** - The approximate memory usage in bytes for unflushed mem-tables. ```