Skip to main content

rust_rocksdb/
column_family.rs

1// Copyright 2020 Tyler Neely
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::ffi_util::raw_data_and_free;
16use crate::{Options, db::MultiThreaded, ffi};
17
18use std::sync::Arc;
19use std::time::Duration;
20
21/// The name of the default column family.
22///
23/// The column family with this name is created implicitly whenever column
24/// families are used.
25pub const DEFAULT_COLUMN_FAMILY_NAME: &str = "default";
26
27/// A descriptor for a RocksDB column family.
28///
29/// A description of the column family, containing the name and `Options`.
30pub struct ColumnFamilyDescriptor {
31    pub(crate) name: String,
32    pub(crate) options: Options,
33    pub(crate) ttl: ColumnFamilyTtl,
34}
35
36impl ColumnFamilyDescriptor {
37    /// Create a new column family descriptor with the specified name and options.
38    /// *WARNING*:
39    /// Will use [`ColumnFamilyTtl::SameAsDb`] as ttl.
40    pub fn new<S>(name: S, options: Options) -> Self
41    where
42        S: Into<String>,
43    {
44        Self {
45            name: name.into(),
46            options,
47            ttl: ColumnFamilyTtl::SameAsDb,
48        }
49    }
50
51    /// Create a new column family descriptor with the specified name, options, and ttl.
52    /// *WARNING*:
53    /// The ttl is applied only when DB is opened with [`crate::db::DB::open_with_ttl()`].
54    pub fn new_with_ttl<S>(name: S, options: Options, ttl: ColumnFamilyTtl) -> Self
55    where
56        S: Into<String>,
57    {
58        Self {
59            name: name.into(),
60            options,
61            ttl,
62        }
63    }
64
65    /// Sets ttl for the column family. It's applied only when DB is opened with
66    /// [`crate::db::DB::open_with_ttl()`]. Changing ttl after DB is opened has no effect.
67    pub fn set_ttl(&mut self, ttl: ColumnFamilyTtl) {
68        self.ttl = ttl;
69    }
70
71    /// Get the name of the ColumnFamilyDescriptor.
72    pub fn name(&self) -> &str {
73        &self.name
74    }
75
76    pub fn ttl(&self) -> ColumnFamilyTtl {
77        self.ttl
78    }
79}
80
81#[derive(Debug, Clone, Copy, Default)]
82/// Specifies the TTL behavior for a column family.
83/// <https://github.com/facebook/rocksdb/blob/18cecb9c46b4c2a8b148659dac2fcab5a843d32b/include/rocksdb/utilities/db_ttl.h#L16-L46>
84pub enum ColumnFamilyTtl {
85    /// Entries are kept, using the longest TTL the C API can express.
86    ///
87    /// That is `i32::MAX` seconds, about 68 years, not RocksDB's never-expire
88    /// sentinel.
89    #[default]
90    Disabled,
91    /// Will set ttl to the specified duration
92    Duration(Duration),
93    /// Will use ttl specified at db open time
94    SameAsDb,
95}
96
97/// An opaque type used to represent a column family. Returned from some functions, and used
98/// in others
99pub struct ColumnFamily {
100    pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t,
101}
102
103/// A specialized opaque type used to represent a column family by the [`MultiThreaded`]
104/// mode. Clone (and Copy) is derived to behave like `&ColumnFamily` (this is used for
105/// single-threaded mode). `Clone`/`Copy` is safe because this lifetime is bound to DB like
106/// iterators/snapshots. On top of it, this is as cheap and small as `&ColumnFamily` because
107/// this only has a single pointer-wide field.
108pub struct BoundColumnFamily<'a> {
109    pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t,
110    pub(crate) multi_threaded_cfs: std::marker::PhantomData<&'a MultiThreaded>,
111}
112
113// internal struct which isn't exposed to public api.
114// but its memory will be exposed after transmute()-ing to BoundColumnFamily.
115// ColumnFamily's lifetime should be bound to DB. But, db holds cfs and cfs can't easily
116// self-reference DB as its lifetime due to rust's type system
117pub(crate) struct UnboundColumnFamily {
118    pub(crate) inner: *mut ffi::rocksdb_column_family_handle_t,
119}
120
121impl UnboundColumnFamily {
122    pub(crate) fn bound_column_family<'a>(self: Arc<Self>) -> Arc<BoundColumnFamily<'a>> {
123        // SAFETY: the new BoundColumnFamily here just adding lifetime,
124        // so that column family handle won't outlive db.
125        unsafe { Arc::from_raw(Arc::into_raw(self).cast()) }
126    }
127}
128
129fn destroy_handle(handle: *mut ffi::rocksdb_column_family_handle_t) {
130    // SAFETY: This should be called only from various Drop::drop(), strictly keeping a 1-to-1
131    // ownership to avoid double invocation to the rocksdb function with same handle.
132    unsafe {
133        ffi::rocksdb_column_family_handle_destroy(handle);
134    }
135}
136
137impl Drop for ColumnFamily {
138    fn drop(&mut self) {
139        destroy_handle(self.inner);
140    }
141}
142
143// these behaviors must be identical between BoundColumnFamily and UnboundColumnFamily
144// due to the unsafe transmute() in bound_column_family()!
145impl Drop for BoundColumnFamily<'_> {
146    fn drop(&mut self) {
147        destroy_handle(self.inner);
148    }
149}
150
151impl Drop for UnboundColumnFamily {
152    fn drop(&mut self) {
153        destroy_handle(self.inner);
154    }
155}
156
157/// Handy type alias to hide actual type difference to reference [`ColumnFamily`]
158/// depending on the `multi-threaded-cf` crate feature.
159#[cfg(not(feature = "multi-threaded-cf"))]
160pub type ColumnFamilyRef<'a> = &'a ColumnFamily;
161
162#[cfg(feature = "multi-threaded-cf")]
163pub type ColumnFamilyRef<'a> = Arc<BoundColumnFamily<'a>>;
164
165/// Utility trait to accept both supported references to `ColumnFamily`
166/// (`&ColumnFamily` and `BoundColumnFamily`)
167pub trait AsColumnFamilyRef {
168    fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t;
169
170    /// The id RocksDB assigned this column family.
171    ///
172    /// Assigned in creation order and stable for the life of the column family, so
173    /// it is what shows up as `cf_id` in listener callbacks. Reusing it after the
174    /// column family is dropped is up to RocksDB.
175    fn id(&self) -> u32 {
176        // SAFETY: `inner` is a live handle for as long as this reference is, and the
177        // C call only reads the name out of it.
178        unsafe { ffi::rocksdb_column_family_handle_get_id(self.inner()) }
179    }
180
181    /// The name this column family was created with.
182    ///
183    /// Bytes rather than a `String` because RocksDB stores the name as given and
184    /// does not require it to be UTF-8. Names created through this crate always are,
185    /// since the constructors take `&str`.
186    fn name(&self) -> Vec<u8> {
187        let mut len: usize = 0;
188        // SAFETY: `inner` is a live handle, and the returned buffer is a `malloc`ed
189        // copy of the name with its length written through `len`. It carries no NUL
190        // terminator, `CopyString` at c.cc:1069 only copies the bytes, so it has to
191        // be read by length and then freed, which is what `raw_data_and_free` does.
192        unsafe {
193            let ptr = ffi::rocksdb_column_family_handle_get_name(self.inner(), &raw mut len);
194            raw_data_and_free(ptr, len).unwrap_or_default()
195        }
196    }
197}
198
199impl AsColumnFamilyRef for ColumnFamily {
200    #[inline]
201    fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t {
202        self.inner
203    }
204}
205
206impl AsColumnFamilyRef for &'_ ColumnFamily {
207    #[inline]
208    fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t {
209        self.inner
210    }
211}
212
213// Only implement for Arc-ed BoundColumnFamily as this tightly coupled and
214// implementation detail, considering use of std::mem::transmute. BoundColumnFamily
215// isn't expected to be used as naked.
216// Also, ColumnFamilyRef might not be Arc<BoundColumnFamily<'a>> depending crate
217// feature flags so, we can't use the type alias here.
218impl AsColumnFamilyRef for Arc<BoundColumnFamily<'_>> {
219    #[inline]
220    fn inner(&self) -> *mut ffi::rocksdb_column_family_handle_t {
221        self.inner
222    }
223}
224
225unsafe impl Send for ColumnFamily {}
226unsafe impl Sync for ColumnFamily {}
227unsafe impl Send for UnboundColumnFamily {}
228unsafe impl Sync for UnboundColumnFamily {}
229unsafe impl Send for BoundColumnFamily<'_> {}
230unsafe impl Sync for BoundColumnFamily<'_> {}