forked from hdevalence/rust-rocksdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_options.rs
3399 lines (3149 loc) · 117 KB
/
db_options.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Tyler Neely
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::{CStr, CString};
use std::mem;
use std::path::Path;
use libc::{self, c_char, c_int, c_uchar, c_uint, c_void, size_t};
use crate::{
compaction_filter::{self, CompactionFilterCallback, CompactionFilterFn},
compaction_filter_factory::{self, CompactionFilterFactory},
comparator::{self, ComparatorCallback, CompareFn},
ffi,
merge_operator::{
self, full_merge_callback, partial_merge_callback, MergeFn, MergeOperatorCallback,
},
slice_transform::SliceTransform,
Error, Snapshot,
};
fn new_cache(capacity: size_t) -> *mut ffi::rocksdb_cache_t {
unsafe { ffi::rocksdb_cache_create_lru(capacity) }
}
pub struct Cache {
pub(crate) inner: *mut ffi::rocksdb_cache_t,
}
impl Cache {
/// Create a lru cache with capacity
pub fn new_lru_cache(capacity: size_t) -> Result<Cache, Error> {
let cache = new_cache(capacity);
if cache.is_null() {
Err(Error::new("Could not create Cache".to_owned()))
} else {
Ok(Cache { inner: cache })
}
}
/// Returns the Cache memory usage
pub fn get_usage(&self) -> usize {
unsafe { ffi::rocksdb_cache_get_usage(self.inner) }
}
/// Returns pinned memory usage
pub fn get_pinned_usage(&self) -> usize {
unsafe { ffi::rocksdb_cache_get_pinned_usage(self.inner) }
}
/// Sets cache capacity
pub fn set_capacity(&mut self, capacity: size_t) {
unsafe {
ffi::rocksdb_cache_set_capacity(self.inner, capacity);
}
}
}
impl Drop for Cache {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_cache_destroy(self.inner);
}
}
}
/// An Env is an interface used by the rocksdb implementation to access
/// operating system functionality like the filesystem etc. Callers
/// may wish to provide a custom Env object when opening a database to
/// get fine gain control; e.g., to rate limit file system operations.
///
/// All Env implementations are safe for concurrent access from
/// multiple threads without any external synchronization.
///
/// Note: currently, C API behinds C++ API for various settings.
/// See also: `rocksdb/include/env.h`
pub struct Env {
pub(crate) inner: *mut ffi::rocksdb_env_t,
}
impl Drop for Env {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_env_destroy(self.inner);
}
}
}
impl Env {
/// Returns default env
pub fn default() -> Result<Env, Error> {
let env = unsafe { ffi::rocksdb_create_default_env() };
if env.is_null() {
Err(Error::new("Could not create mem env".to_owned()))
} else {
Ok(Env { inner: env })
}
}
/// Returns a new environment that stores its data in memory and delegates
/// all non-file-storage tasks to base_env.
pub fn mem_env() -> Result<Env, Error> {
let env = unsafe { ffi::rocksdb_create_mem_env() };
if env.is_null() {
Err(Error::new("Could not create mem env".to_owned()))
} else {
Ok(Env { inner: env })
}
}
/// Sets the number of background worker threads of a specific thread pool for this environment.
/// `LOW` is the default pool.
///
/// Default: 1
pub fn set_background_threads(&mut self, num_threads: c_int) {
unsafe {
ffi::rocksdb_env_set_background_threads(self.inner, num_threads);
}
}
/// Sets the size of the high priority thread pool that can be used to
/// prevent compactions from stalling memtable flushes.
pub fn set_high_priority_background_threads(&mut self, n: c_int) {
unsafe {
ffi::rocksdb_env_set_high_priority_background_threads(self.inner, n);
}
}
/// Wait for all threads started by StartThread to terminate.
pub fn join_all_threads(&mut self) {
unsafe {
ffi::rocksdb_env_join_all_threads(self.inner);
}
}
/// Lowering IO priority for threads from the specified pool.
pub fn lower_thread_pool_io_priority(&mut self) {
unsafe {
ffi::rocksdb_env_lower_thread_pool_io_priority(self.inner);
}
}
/// Lowering IO priority for high priority thread pool.
pub fn lower_high_priority_thread_pool_io_priority(&mut self) {
unsafe {
ffi::rocksdb_env_lower_high_priority_thread_pool_io_priority(self.inner);
}
}
/// Lowering CPU priority for threads from the specified pool.
pub fn lower_thread_pool_cpu_priority(&mut self) {
unsafe {
ffi::rocksdb_env_lower_thread_pool_cpu_priority(self.inner);
}
}
/// Lowering CPU priority for high priority thread pool.
pub fn lower_high_priority_thread_pool_cpu_priority(&mut self) {
unsafe {
ffi::rocksdb_env_lower_high_priority_thread_pool_cpu_priority(self.inner);
}
}
}
/// Database-wide options around performance and behavior.
///
/// Please read the official tuning [guide](https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide)
/// and most importantly, measure performance under realistic workloads with realistic hardware.
///
/// # Examples
///
/// ```
/// 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_max_background_compactions(4);
/// opts.set_max_background_flushes(4);
/// opts.set_disable_auto_compactions(true);
///
/// DB::open(&opts, path).unwrap()
/// }
/// ```
pub struct Options {
pub(crate) inner: *mut ffi::rocksdb_options_t,
}
/// Optionally disable WAL or sync for this write.
///
/// # Examples
///
/// Making an unsafe write of a batch:
///
/// ```
/// use rocksdb::{DB, Options, WriteBatch, WriteOptions};
///
/// let path = "_path_for_rocksdb_storageY1";
/// {
/// let db = DB::open_default(path).unwrap();
/// let mut batch = WriteBatch::default();
/// batch.put(b"my key", b"my value");
/// batch.put(b"key2", b"value2");
/// batch.put(b"key3", b"value3");
///
/// let mut write_options = WriteOptions::default();
/// write_options.set_sync(false);
/// write_options.disable_wal(true);
///
/// db.write_opt(batch, &write_options);
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct WriteOptions {
pub(crate) inner: *mut ffi::rocksdb_writeoptions_t,
}
/// Optionally wait for the memtable flush to be performed.
///
/// # Examples
///
/// Manually flushing the memtable:
///
/// ```
/// use rocksdb::{DB, Options, FlushOptions};
///
/// let path = "_path_for_rocksdb_storageY2";
/// {
/// let db = DB::open_default(path).unwrap();
///
/// let mut flush_options = FlushOptions::default();
/// flush_options.set_wait(true);
///
/// db.flush_opt(&flush_options);
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct FlushOptions {
pub(crate) inner: *mut ffi::rocksdb_flushoptions_t,
}
/// For configuring block-based file storage.
pub struct BlockBasedOptions {
pub(crate) inner: *mut ffi::rocksdb_block_based_table_options_t,
}
pub struct ReadOptions {
pub(crate) inner: *mut ffi::rocksdb_readoptions_t,
iterate_upper_bound: Option<Vec<u8>>,
iterate_lower_bound: Option<Vec<u8>>,
}
/// For configuring external files ingestion.
///
/// # Examples
///
/// Move files instead of copying them:
///
/// ```
/// use rocksdb::{DB, IngestExternalFileOptions, SstFileWriter, Options};
///
/// let writer_opts = Options::default();
/// let mut writer = SstFileWriter::create(&writer_opts);
/// writer.open("_path_for_sst_file").unwrap();
/// writer.put(b"k1", b"v1").unwrap();
/// writer.finish().unwrap();
///
/// let path = "_path_for_rocksdb_storageY3";
/// {
/// let db = DB::open_default(&path).unwrap();
/// let mut ingest_opts = IngestExternalFileOptions::default();
/// ingest_opts.set_move_files(true);
/// db.ingest_external_file_opts(&ingest_opts, vec!["_path_for_sst_file"]).unwrap();
/// }
/// let _ = DB::destroy(&Options::default(), path);
/// ```
pub struct IngestExternalFileOptions {
pub(crate) inner: *mut ffi::rocksdb_ingestexternalfileoptions_t,
}
// Safety note: auto-implementing Send on most db-related types is prevented by the inner FFI
// pointer. In most cases, however, this pointer is Send-safe because it is never aliased and
// rocksdb internally does not rely on thread-local information for its user-exposed types.
unsafe impl Send for Options {}
unsafe impl Send for WriteOptions {}
unsafe impl Send for BlockBasedOptions {}
unsafe impl Send for ReadOptions {}
unsafe impl Send for IngestExternalFileOptions {}
// Sync is similarly safe for many types because they do not expose interior mutability, and their
// use within the rocksdb library is generally behind a const reference
unsafe impl Sync for Options {}
unsafe impl Sync for WriteOptions {}
unsafe impl Sync for BlockBasedOptions {}
unsafe impl Sync for ReadOptions {}
unsafe impl Sync for IngestExternalFileOptions {}
impl Drop for Options {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_options_destroy(self.inner);
}
}
}
impl Clone for Options {
fn clone(&self) -> Self {
let inner = unsafe { ffi::rocksdb_options_create_copy(self.inner) };
if inner.is_null() {
panic!("Could not copy RocksDB options");
}
Self { inner }
}
}
impl Drop for BlockBasedOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_block_based_options_destroy(self.inner);
}
}
}
impl Drop for FlushOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_flushoptions_destroy(self.inner);
}
}
}
impl Drop for WriteOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_writeoptions_destroy(self.inner);
}
}
}
impl Drop for ReadOptions {
fn drop(&mut self) {
unsafe { ffi::rocksdb_readoptions_destroy(self.inner) }
}
}
impl Drop for IngestExternalFileOptions {
fn drop(&mut self) {
unsafe { ffi::rocksdb_ingestexternalfileoptions_destroy(self.inner) }
}
}
impl BlockBasedOptions {
/// Approximate size of user data packed per block. Note that the
/// block size specified here corresponds to uncompressed data. The
/// actual size of the unit read from disk may be smaller if
/// compression is enabled. This parameter can be changed dynamically.
pub fn set_block_size(&mut self, size: usize) {
unsafe {
ffi::rocksdb_block_based_options_set_block_size(self.inner, size);
}
}
/// Block size for partitioned metadata. Currently applied to indexes when
/// kTwoLevelIndexSearch is used and to filters when partition_filters is used.
/// Note: Since in the current implementation the filters and index partitions
/// are aligned, an index/filter block is created when either index or filter
/// block size reaches the specified limit.
///
/// Note: this limit is currently applied to only index blocks; a filter
/// partition is cut right after an index block is cut.
pub fn set_metadata_block_size(&mut self, size: usize) {
unsafe {
ffi::rocksdb_block_based_options_set_metadata_block_size(self.inner, size as u64);
}
}
/// Note: currently this option requires kTwoLevelIndexSearch to be set as
/// well.
///
/// Use partitioned full filters for each SST file. This option is
/// incompatible with block-based filters.
pub fn set_partition_filters(&mut self, size: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_partition_filters(self.inner, size as c_uchar);
}
}
/// When provided: use the specified cache for blocks.
/// Otherwise rocksdb will automatically create and use an 8MB internal cache.
#[deprecated(
since = "0.15.0",
note = "This function will be removed in next release. Use set_block_cache instead"
)]
pub fn set_lru_cache(&mut self, size: size_t) {
let cache = new_cache(size);
unsafe {
// Since cache is wrapped in shared_ptr, we don't need to
// call rocksdb_cache_destroy explicitly.
ffi::rocksdb_block_based_options_set_block_cache(self.inner, cache);
}
}
/// When configured: use the specified cache for compressed blocks.
/// Otherwise rocksdb will not use a compressed block cache.
///
/// Note: though it looks similar to `block_cache`, RocksDB doesn't put the
/// same type of object there.
#[deprecated(
since = "0.15.0",
note = "This function will be removed in next release. Use set_block_cache_compressed instead"
)]
pub fn set_lru_cache_compressed(&mut self, size: size_t) {
let cache = new_cache(size);
unsafe {
// Since cache is wrapped in shared_ptr, we don't need to
// call rocksdb_cache_destroy explicitly.
ffi::rocksdb_block_based_options_set_block_cache_compressed(self.inner, cache);
}
}
/// Sets global cache for blocks (user data is stored in a set of blocks, and
/// a block is the unit of reading from disk). Cache must outlive DB instance which uses it.
///
/// If set, use the specified cache for blocks.
/// By default, rocksdb will automatically create and use an 8MB internal cache.
pub fn set_block_cache(&mut self, cache: &Cache) {
unsafe {
ffi::rocksdb_block_based_options_set_block_cache(self.inner, cache.inner);
}
}
/// Sets global cache for compressed blocks. Cache must outlive DB instance which uses it.
///
/// By default, rocksdb will not use a compressed block cache.
pub fn set_block_cache_compressed(&mut self, cache: &Cache) {
unsafe {
ffi::rocksdb_block_based_options_set_block_cache_compressed(self.inner, cache.inner);
}
}
/// Disable block cache
pub fn disable_cache(&mut self) {
unsafe {
ffi::rocksdb_block_based_options_set_no_block_cache(self.inner, true as c_uchar);
}
}
/// Sets the filter policy to reduce disk reads
pub fn set_bloom_filter(&mut self, bits_per_key: c_int, block_based: bool) {
unsafe {
let bloom = if block_based {
ffi::rocksdb_filterpolicy_create_bloom(bits_per_key)
} else {
ffi::rocksdb_filterpolicy_create_bloom_full(bits_per_key)
};
ffi::rocksdb_block_based_options_set_filter_policy(self.inner, bloom);
}
}
pub fn set_cache_index_and_filter_blocks(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_cache_index_and_filter_blocks(self.inner, v as u8);
}
}
/// Defines the index type to be used for SS-table lookups.
///
/// # Examples
///
/// ```
/// use rocksdb::{BlockBasedOptions, BlockBasedIndexType, Options};
///
/// let mut opts = Options::default();
/// let mut block_opts = BlockBasedOptions::default();
/// block_opts.set_index_type(BlockBasedIndexType::HashSearch);
/// ```
pub fn set_index_type(&mut self, index_type: BlockBasedIndexType) {
let index = index_type as i32;
unsafe {
ffi::rocksdb_block_based_options_set_index_type(self.inner, index);
}
}
/// If cache_index_and_filter_blocks is true and the below is true, then
/// filter and index blocks are stored in the cache, but a reference is
/// held in the "table reader" object so the blocks are pinned and only
/// evicted from cache when the table reader is freed.
///
/// Default: false.
pub fn set_pin_l0_filter_and_index_blocks_in_cache(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_pin_l0_filter_and_index_blocks_in_cache(
self.inner,
v as c_uchar,
);
}
}
/// If cache_index_and_filter_blocks is true and the below is true, then
/// the top-level index of partitioned filter and index blocks are stored in
/// the cache, but a reference is held in the "table reader" object so the
/// blocks are pinned and only evicted from cache when the table reader is
/// freed. This is not limited to l0 in LSM tree.
///
/// Default: false.
pub fn set_pin_top_level_index_and_filter(&mut self, v: bool) {
unsafe {
ffi::rocksdb_block_based_options_set_pin_top_level_index_and_filter(
self.inner,
v as c_uchar,
);
}
}
/// Format version, reserved for backward compatibility.
///
/// See full [list](https://github.com/facebook/rocksdb/blob/f059c7d9b96300091e07429a60f4ad55dac84859/include/rocksdb/table.h#L249-L274)
/// of the supported versions.
///
/// Default: 2.
pub fn set_format_version(&mut self, version: i32) {
unsafe {
ffi::rocksdb_block_based_options_set_format_version(self.inner, version);
}
}
/// Number of keys between restart points for delta encoding of keys.
/// This parameter can be changed dynamically. Most clients should
/// leave this parameter alone. The minimum value allowed is 1. Any smaller
/// value will be silently overwritten with 1.
///
/// Default: 16.
pub fn set_block_restart_interval(&mut self, interval: i32) {
unsafe {
ffi::rocksdb_block_based_options_set_block_restart_interval(self.inner, interval);
}
}
/// Same as block_restart_interval but used for the index block.
/// If you don't plan to run RocksDB before version 5.16 and you are
/// using `index_block_restart_interval` > 1, you should
/// probably set the `format_version` to >= 4 as it would reduce the index size.
///
/// Default: 1.
pub fn set_index_block_restart_interval(&mut self, interval: i32) {
unsafe {
ffi::rocksdb_block_based_options_set_index_block_restart_interval(self.inner, interval);
}
}
/// Set the data block index type for point lookups:
/// `DataBlockIndexType::BinarySearch` to use binary search within the data block.
/// `DataBlockIndexType::BinaryAndHash` to use the data block hash index in combination with
/// the normal binary search.
///
/// The hash table utilization ratio is adjustable using [`set_data_block_hash_ratio`](#method.set_data_block_hash_ratio), which is
/// valid only when using `DataBlockIndexType::BinaryAndHash`.
///
/// Default: `BinarySearch`
/// # Examples
///
/// ```
/// use rocksdb::{BlockBasedOptions, DataBlockIndexType, Options};
///
/// let mut opts = Options::default();
/// let mut block_opts = BlockBasedOptions::default();
/// block_opts.set_data_block_index_type(DataBlockIndexType::BinaryAndHash);
/// block_opts.set_data_block_hash_ratio(0.85);
/// ```
pub fn set_data_block_index_type(&mut self, index_type: DataBlockIndexType) {
let index_t = index_type as i32;
unsafe { ffi::rocksdb_block_based_options_set_data_block_index_type(self.inner, index_t) }
}
/// Set the data block hash index utilization ratio.
///
/// The smaller the utilization ratio, the less hash collisions happen, and so reduce the risk for a
/// point lookup to fall back to binary search due to the collisions. A small ratio means faster
/// lookup at the price of more space overhead.
///
/// Default: 0.75
pub fn set_data_block_hash_ratio(&mut self, ratio: f64) {
unsafe { ffi::rocksdb_block_based_options_set_data_block_hash_ratio(self.inner, ratio) }
}
}
impl Default for BlockBasedOptions {
fn default() -> BlockBasedOptions {
let block_opts = unsafe { ffi::rocksdb_block_based_options_create() };
if block_opts.is_null() {
panic!("Could not create RocksDB block based options");
}
BlockBasedOptions { inner: block_opts }
}
}
impl Options {
/// By default, RocksDB uses only one background thread for flush and
/// compaction. Calling this function will set it up such that total of
/// `total_threads` is used. Good value for `total_threads` is the number of
/// cores. You almost definitely want to call this function if your system is
/// bottlenecked by RocksDB.
///
/// # Examples
///
/// ```
/// use rocksdb::Options;
///
/// let mut opts = Options::default();
/// opts.increase_parallelism(3);
/// ```
pub fn increase_parallelism(&mut self, parallelism: i32) {
unsafe {
ffi::rocksdb_options_increase_parallelism(self.inner, parallelism);
}
}
/// Optimize level style compaction.
///
/// Default values for some parameters in `Options` are not optimized for heavy
/// workloads and big datasets, which means you might observe write stalls under
/// some conditions.
///
/// This can be used as one of the starting points for tuning RocksDB options in
/// such cases.
///
/// Internally, it sets `write_buffer_size`, `min_write_buffer_number_to_merge`,
/// `max_write_buffer_number`, `level0_file_num_compaction_trigger`,
/// `target_file_size_base`, `max_bytes_for_level_base`, so it can override if those
/// parameters were set before.
///
/// It sets buffer sizes so that memory consumption would be constrained by
/// `memtable_memory_budget`.
pub fn optimize_level_style_compaction(&mut self, memtable_memory_budget: usize) {
unsafe {
ffi::rocksdb_options_optimize_level_style_compaction(
self.inner,
memtable_memory_budget as u64,
);
}
}
/// Optimize universal style compaction.
///
/// Default values for some parameters in `Options` are not optimized for heavy
/// workloads and big datasets, which means you might observe write stalls under
/// some conditions.
///
/// This can be used as one of the starting points for tuning RocksDB options in
/// such cases.
///
/// Internally, it sets `write_buffer_size`, `min_write_buffer_number_to_merge`,
/// `max_write_buffer_number`, `level0_file_num_compaction_trigger`,
/// `target_file_size_base`, `max_bytes_for_level_base`, so it can override if those
/// parameters were set before.
///
/// It sets buffer sizes so that memory consumption would be constrained by
/// `memtable_memory_budget`.
pub fn optimize_universal_style_compaction(&mut self, memtable_memory_budget: usize) {
unsafe {
ffi::rocksdb_options_optimize_universal_style_compaction(
self.inner,
memtable_memory_budget as u64,
);
}
}
/// If true, the database will be created if it is missing.
///
/// Default: `false`
///
/// # Examples
///
/// ```
/// use rocksdb::Options;
///
/// let mut opts = Options::default();
/// opts.create_if_missing(true);
/// ```
pub fn create_if_missing(&mut self, create_if_missing: bool) {
unsafe {
ffi::rocksdb_options_set_create_if_missing(self.inner, create_if_missing as c_uchar);
}
}
/// If true, any column families that didn't exist when opening the database
/// will be created.
///
/// Default: `false`
///
/// # Examples
///
/// ```
/// use rocksdb::Options;
///
/// let mut opts = Options::default();
/// opts.create_missing_column_families(true);
/// ```
pub fn create_missing_column_families(&mut self, create_missing_cfs: bool) {
unsafe {
ffi::rocksdb_options_set_create_missing_column_families(
self.inner,
create_missing_cfs as c_uchar,
);
}
}
/// Specifies whether an error should be raised if the database already exists.
///
/// Default: false
pub fn set_error_if_exists(&mut self, enabled: bool) {
unsafe {
ffi::rocksdb_options_set_error_if_exists(self.inner, enabled as c_uchar);
}
}
/// Enable/disable paranoid checks.
///
/// If true, the implementation will do aggressive checking of the
/// data it is processing and will stop early if it detects any
/// errors. This may have unforeseen ramifications: for example, a
/// corruption of one DB entry may cause a large number of entries to
/// become unreadable or for the entire DB to become unopenable.
/// If any of the writes to the database fails (Put, Delete, Merge, Write),
/// the database will switch to read-only mode and fail all other
/// Write operations.
///
/// Default: false
pub fn set_paranoid_checks(&mut self, enabled: bool) {
unsafe {
ffi::rocksdb_options_set_paranoid_checks(self.inner, enabled as c_uchar);
}
}
/// A list of paths where SST files can be put into, with its target size.
/// Newer data is placed into paths specified earlier in the vector while
/// older data gradually moves to paths specified later in the vector.
///
/// For example, you have a flash device with 10GB allocated for the DB,
/// as well as a hard drive of 2TB, you should config it to be:
/// [{"/flash_path", 10GB}, {"/hard_drive", 2TB}]
///
/// The system will try to guarantee data under each path is close to but
/// not larger than the target size. But current and future file sizes used
/// by determining where to place a file are based on best-effort estimation,
/// which means there is a chance that the actual size under the directory
/// is slightly more than target size under some workloads. User should give
/// some buffer room for those cases.
///
/// If none of the paths has sufficient room to place a file, the file will
/// be placed to the last path anyway, despite to the target size.
///
/// Placing newer data to earlier paths is also best-efforts. User should
/// expect user files to be placed in higher levels in some extreme cases.
///
/// If left empty, only one path will be used, which is `path` passed when
/// opening the DB.
///
/// Default: empty
pub fn set_db_paths(&mut self, paths: &[DBPath]) {
let mut paths: Vec<_> = paths
.iter()
.map(|path| path.inner as *const ffi::rocksdb_dbpath_t)
.collect();
let num_paths = paths.len();
unsafe {
ffi::rocksdb_options_set_db_paths(self.inner, paths.as_mut_ptr(), num_paths);
}
}
/// Use the specified object to interact with the environment,
/// e.g. to read/write files, schedule background work, etc. In the near
/// future, support for doing storage operations such as read/write files
/// through env will be deprecated in favor of file_system.
///
/// Default: Env::default()
pub fn set_env(&mut self, env: &Env) {
unsafe {
ffi::rocksdb_options_set_env(self.inner, env.inner);
}
}
/// Sets the compression algorithm that will be used for compressing blocks.
///
/// Default: `DBCompressionType::Snappy` (`DBCompressionType::None` if
/// snappy feature is not enabled).
///
/// # Examples
///
/// ```
/// use rocksdb::{Options, DBCompressionType};
///
/// let mut opts = Options::default();
/// opts.set_compression_type(DBCompressionType::Snappy);
/// ```
pub fn set_compression_type(&mut self, t: DBCompressionType) {
unsafe {
ffi::rocksdb_options_set_compression(self.inner, t as c_int);
}
}
/// Different levels can have different compression policies. There
/// are cases where most lower levels would like to use quick compression
/// algorithms while the higher levels (which have more data) use
/// compression algorithms that have better compression but could
/// be slower. This array, if non-empty, should have an entry for
/// each level of the database; these override the value specified in
/// the previous field 'compression'.
///
/// # Examples
///
/// ```
/// use rocksdb::{Options, DBCompressionType};
///
/// let mut opts = Options::default();
/// opts.set_compression_per_level(&[
/// DBCompressionType::None,
/// DBCompressionType::None,
/// DBCompressionType::Snappy,
/// DBCompressionType::Snappy,
/// DBCompressionType::Snappy
/// ]);
/// ```
pub fn set_compression_per_level(&mut self, level_types: &[DBCompressionType]) {
unsafe {
let mut level_types: Vec<_> = level_types.iter().map(|&t| t as c_int).collect();
ffi::rocksdb_options_set_compression_per_level(
self.inner,
level_types.as_mut_ptr(),
level_types.len() as size_t,
)
}
}
/// Maximum size of dictionaries used to prime the compression library.
/// Enabling dictionary can improve compression ratios when there are
/// repetitions across data blocks.
///
/// The dictionary is created by sampling the SST file data. If
/// `zstd_max_train_bytes` is nonzero, the samples are passed through zstd's
/// dictionary generator. Otherwise, the random samples are used directly as
/// the dictionary.
///
/// When compression dictionary is disabled, we compress and write each block
/// before buffering data for the next one. When compression dictionary is
/// enabled, we buffer all SST file data in-memory so we can sample it, as data
/// can only be compressed and written after the dictionary has been finalized.
/// So users of this feature may see increased memory usage.
///
/// Default: `0`
///
/// # Examples
///
/// ```
/// use rocksdb::Options;
///
/// let mut opts = Options::default();
/// opts.set_compression_options(4, 5, 6, 7);
/// ```
pub fn set_compression_options(
&mut self,
w_bits: c_int,
level: c_int,
strategy: c_int,
max_dict_bytes: c_int,
) {
unsafe {
ffi::rocksdb_options_set_compression_options(
self.inner,
w_bits,
level,
strategy,
max_dict_bytes,
);
}
}
/// If non-zero, we perform bigger reads when doing compaction. If you're
/// running RocksDB on spinning disks, you should set this to at least 2MB.
/// That way RocksDB's compaction is doing sequential instead of random reads.
///
/// When non-zero, we also force new_table_reader_for_compaction_inputs to
/// true.
///
/// Default: `0`
pub fn set_compaction_readahead_size(&mut self, compaction_readahead_size: usize) {
unsafe {
ffi::rocksdb_options_compaction_readahead_size(
self.inner,
compaction_readahead_size as usize,
);
}
}
/// Allow RocksDB to pick dynamic base of bytes for levels.
/// With this feature turned on, RocksDB will automatically adjust max bytes for each level.
/// The goal of this feature is to have lower bound on size amplification.
///
/// Default: false.
pub fn set_level_compaction_dynamic_level_bytes(&mut self, v: bool) {
unsafe {
ffi::rocksdb_options_set_level_compaction_dynamic_level_bytes(self.inner, v as c_uchar);
}
}
pub fn set_merge_operator(
&mut self,
name: &str,
full_merge_fn: MergeFn,
partial_merge_fn: Option<MergeFn>,
) {
let cb = Box::new(MergeOperatorCallback {
name: CString::new(name.as_bytes()).unwrap(),
full_merge_fn,
partial_merge_fn: partial_merge_fn.unwrap_or(full_merge_fn),
});
unsafe {
let mo = ffi::rocksdb_mergeoperator_create(
mem::transmute(cb),
Some(merge_operator::destructor_callback),
Some(full_merge_callback),
Some(partial_merge_callback),
Some(merge_operator::delete_callback),
Some(merge_operator::name_callback),
);
ffi::rocksdb_options_set_merge_operator(self.inner, mo);
}
}
#[deprecated(
since = "0.5.0",
note = "add_merge_operator has been renamed to set_merge_operator"
)]
pub fn add_merge_operator(&mut self, name: &str, merge_fn: MergeFn) {
self.set_merge_operator(name, merge_fn, None);
}
/// Sets a compaction filter used to determine if entries should be kept, changed,
/// or removed during compaction.
///
/// An example use case is to remove entries with an expired TTL.
///
/// If you take a snapshot of the database, only values written since the last
/// snapshot will be passed through the compaction filter.
///
/// If multi-threaded compaction is used, `filter_fn` may be called multiple times
/// simultaneously.
pub fn set_compaction_filter<F>(&mut self, name: &str, filter_fn: F)
where
F: CompactionFilterFn + Send + 'static,
{
let cb = Box::new(CompactionFilterCallback {
name: CString::new(name.as_bytes()).unwrap(),
filter_fn,
});
unsafe {
let cf = ffi::rocksdb_compactionfilter_create(
mem::transmute(cb),
Some(compaction_filter::destructor_callback::<CompactionFilterCallback<F>>),
Some(compaction_filter::filter_callback::<CompactionFilterCallback<F>>),
Some(compaction_filter::name_callback::<CompactionFilterCallback<F>>),
);
ffi::rocksdb_options_set_compaction_filter(self.inner, cf);
}
}
/// This is a factory that provides compaction filter objects which allow
/// an application to modify/delete a key-value during background compaction.
///
/// A new filter will be created on each compaction run. If multithreaded
/// compaction is being used, each created CompactionFilter will only be used
/// from a single thread and so does not need to be thread-safe.