rocksdb/
db_iterator.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::{
16    db::{DBAccess, DB},
17    ffi, Error, ReadOptions, WriteBatch,
18};
19use libc::{c_char, c_uchar, size_t};
20use std::{marker::PhantomData, slice};
21
22/// A type alias to keep compatibility. See [`DBRawIteratorWithThreadMode`] for details
23pub type DBRawIterator<'a> = DBRawIteratorWithThreadMode<'a, DB>;
24
25/// An iterator over a database or column family, with specifiable
26/// ranges and direction.
27///
28/// This iterator is different to the standard ``DBIteratorWithThreadMode`` as it aims Into
29/// replicate the underlying iterator API within RocksDB itself. This should
30/// give access to more performance and flexibility but departs from the
31/// widely recognised Rust idioms.
32///
33/// ```
34/// use rocksdb::{DB, Options};
35///
36/// let path = "_path_for_rocksdb_storage4";
37/// {
38///     let db = DB::open_default(path).unwrap();
39///     let mut iter = db.raw_iterator();
40///
41///     // Forwards iteration
42///     iter.seek_to_first();
43///     while iter.valid() {
44///         println!("Saw {:?} {:?}", iter.key(), iter.value());
45///         iter.next();
46///     }
47///
48///     // Reverse iteration
49///     iter.seek_to_last();
50///     while iter.valid() {
51///         println!("Saw {:?} {:?}", iter.key(), iter.value());
52///         iter.prev();
53///     }
54///
55///     // Seeking
56///     iter.seek(b"my key");
57///     while iter.valid() {
58///         println!("Saw {:?} {:?}", iter.key(), iter.value());
59///         iter.next();
60///     }
61///
62///     // Reverse iteration from key
63///     // Note, use seek_for_prev when reversing because if this key doesn't exist,
64///     // this will make the iterator start from the previous key rather than the next.
65///     iter.seek_for_prev(b"my key");
66///     while iter.valid() {
67///         println!("Saw {:?} {:?}", iter.key(), iter.value());
68///         iter.prev();
69///     }
70/// }
71/// let _ = DB::destroy(&Options::default(), path);
72/// ```
73pub struct DBRawIteratorWithThreadMode<'a, D: DBAccess> {
74    inner: std::ptr::NonNull<ffi::rocksdb_iterator_t>,
75
76    /// When iterate_lower_bound or iterate_upper_bound are set, the inner
77    /// C iterator keeps a pointer to the upper bound inside `_readopts`.
78    /// Storing this makes sure the upper bound is always alive when the
79    /// iterator is being used.
80    ///
81    /// And yes, we need to store the entire ReadOptions structure since C++
82    /// ReadOptions keep reference to C rocksdb_readoptions_t wrapper which
83    /// point to vectors we own.  See issue #660.
84    _readopts: ReadOptions,
85
86    db: PhantomData<&'a D>,
87}
88
89impl<'a, D: DBAccess> DBRawIteratorWithThreadMode<'a, D> {
90    pub(crate) fn new(db: &D, readopts: ReadOptions) -> Self {
91        let inner = unsafe { db.create_iterator(&readopts) };
92        Self::from_inner(inner, readopts)
93    }
94
95    pub(crate) fn new_cf(
96        db: &'a D,
97        cf_handle: *mut ffi::rocksdb_column_family_handle_t,
98        readopts: ReadOptions,
99    ) -> Self {
100        let inner = unsafe { db.create_iterator_cf(cf_handle, &readopts) };
101        Self::from_inner(inner, readopts)
102    }
103
104    fn from_inner(inner: *mut ffi::rocksdb_iterator_t, readopts: ReadOptions) -> Self {
105        // This unwrap will never fail since rocksdb_create_iterator and
106        // rocksdb_create_iterator_cf functions always return non-null. They
107        // use new and deference the result so any nulls would end up with SIGSEGV
108        // there and we would have a bigger issue.
109        let inner = std::ptr::NonNull::new(inner).unwrap();
110        Self {
111            inner,
112            _readopts: readopts,
113            db: PhantomData,
114        }
115    }
116
117    /// Returns `true` if the iterator is valid. An iterator is invalidated when
118    /// it reaches the end of its defined range, or when it encounters an error.
119    ///
120    /// To check whether the iterator encountered an error after `valid` has
121    /// returned `false`, use the [`status`](DBRawIteratorWithThreadMode::status) method. `status` will never
122    /// return an error when `valid` is `true`.
123    pub fn valid(&self) -> bool {
124        unsafe { ffi::rocksdb_iter_valid(self.inner.as_ptr()) != 0 }
125    }
126
127    /// Returns an error `Result` if the iterator has encountered an error
128    /// during operation. When an error is encountered, the iterator is
129    /// invalidated and [`valid`](DBRawIteratorWithThreadMode::valid) will return `false` when called.
130    ///
131    /// Performing a seek will discard the current status.
132    pub fn status(&self) -> Result<(), Error> {
133        unsafe {
134            ffi_try!(ffi::rocksdb_iter_get_error(self.inner.as_ptr()));
135        }
136        Ok(())
137    }
138
139    /// Seeks to the first key in the database.
140    ///
141    /// # Examples
142    ///
143    /// ```rust
144    /// use rocksdb::{DB, Options};
145    ///
146    /// let path = "_path_for_rocksdb_storage5";
147    /// {
148    ///     let db = DB::open_default(path).unwrap();
149    ///     let mut iter = db.raw_iterator();
150    ///
151    ///     // Iterate all keys from the start in lexicographic order
152    ///     iter.seek_to_first();
153    ///
154    ///     while iter.valid() {
155    ///         println!("{:?} {:?}", iter.key(), iter.value());
156    ///         iter.next();
157    ///     }
158    ///
159    ///     // Read just the first key
160    ///     iter.seek_to_first();
161    ///
162    ///     if iter.valid() {
163    ///         println!("{:?} {:?}", iter.key(), iter.value());
164    ///     } else {
165    ///         // There are no keys in the database
166    ///     }
167    /// }
168    /// let _ = DB::destroy(&Options::default(), path);
169    /// ```
170    pub fn seek_to_first(&mut self) {
171        unsafe {
172            ffi::rocksdb_iter_seek_to_first(self.inner.as_ptr());
173        }
174    }
175
176    /// Seeks to the last key in the database.
177    ///
178    /// # Examples
179    ///
180    /// ```rust
181    /// use rocksdb::{DB, Options};
182    ///
183    /// let path = "_path_for_rocksdb_storage6";
184    /// {
185    ///     let db = DB::open_default(path).unwrap();
186    ///     let mut iter = db.raw_iterator();
187    ///
188    ///     // Iterate all keys from the end in reverse lexicographic order
189    ///     iter.seek_to_last();
190    ///
191    ///     while iter.valid() {
192    ///         println!("{:?} {:?}", iter.key(), iter.value());
193    ///         iter.prev();
194    ///     }
195    ///
196    ///     // Read just the last key
197    ///     iter.seek_to_last();
198    ///
199    ///     if iter.valid() {
200    ///         println!("{:?} {:?}", iter.key(), iter.value());
201    ///     } else {
202    ///         // There are no keys in the database
203    ///     }
204    /// }
205    /// let _ = DB::destroy(&Options::default(), path);
206    /// ```
207    pub fn seek_to_last(&mut self) {
208        unsafe {
209            ffi::rocksdb_iter_seek_to_last(self.inner.as_ptr());
210        }
211    }
212
213    /// Seeks to the specified key or the first key that lexicographically follows it.
214    ///
215    /// This method will attempt to seek to the specified key. If that key does not exist, it will
216    /// find and seek to the key that lexicographically follows it instead.
217    ///
218    /// # Examples
219    ///
220    /// ```rust
221    /// use rocksdb::{DB, Options};
222    ///
223    /// let path = "_path_for_rocksdb_storage7";
224    /// {
225    ///     let db = DB::open_default(path).unwrap();
226    ///     let mut iter = db.raw_iterator();
227    ///
228    ///     // Read the first key that starts with 'a'
229    ///     iter.seek(b"a");
230    ///
231    ///     if iter.valid() {
232    ///         println!("{:?} {:?}", iter.key(), iter.value());
233    ///     } else {
234    ///         // There are no keys in the database
235    ///     }
236    /// }
237    /// let _ = DB::destroy(&Options::default(), path);
238    /// ```
239    pub fn seek<K: AsRef<[u8]>>(&mut self, key: K) {
240        let key = key.as_ref();
241
242        unsafe {
243            ffi::rocksdb_iter_seek(
244                self.inner.as_ptr(),
245                key.as_ptr() as *const c_char,
246                key.len() as size_t,
247            );
248        }
249    }
250
251    /// Seeks to the specified key, or the first key that lexicographically precedes it.
252    ///
253    /// Like ``.seek()`` this method will attempt to seek to the specified key.
254    /// The difference with ``.seek()`` is that if the specified key do not exist, this method will
255    /// seek to key that lexicographically precedes it instead.
256    ///
257    /// # Examples
258    ///
259    /// ```rust
260    /// use rocksdb::{DB, Options};
261    ///
262    /// let path = "_path_for_rocksdb_storage8";
263    /// {
264    ///     let db = DB::open_default(path).unwrap();
265    ///     let mut iter = db.raw_iterator();
266    ///
267    ///     // Read the last key that starts with 'a'
268    ///     iter.seek_for_prev(b"b");
269    ///
270    ///     if iter.valid() {
271    ///         println!("{:?} {:?}", iter.key(), iter.value());
272    ///     } else {
273    ///         // There are no keys in the database
274    ///     }
275    /// }
276    /// let _ = DB::destroy(&Options::default(), path);
277    /// ```
278    pub fn seek_for_prev<K: AsRef<[u8]>>(&mut self, key: K) {
279        let key = key.as_ref();
280
281        unsafe {
282            ffi::rocksdb_iter_seek_for_prev(
283                self.inner.as_ptr(),
284                key.as_ptr() as *const c_char,
285                key.len() as size_t,
286            );
287        }
288    }
289
290    /// Seeks to the next key.
291    pub fn next(&mut self) {
292        unsafe {
293            ffi::rocksdb_iter_next(self.inner.as_ptr());
294        }
295    }
296
297    /// Seeks to the previous key.
298    pub fn prev(&mut self) {
299        unsafe {
300            ffi::rocksdb_iter_prev(self.inner.as_ptr());
301        }
302    }
303
304    /// Returns a slice of the current key.
305    pub fn key(&self) -> Option<&[u8]> {
306        if self.valid() {
307            Some(self.key_impl())
308        } else {
309            None
310        }
311    }
312
313    /// Returns a slice of the current value.
314    pub fn value(&self) -> Option<&[u8]> {
315        if self.valid() {
316            Some(self.value_impl())
317        } else {
318            None
319        }
320    }
321
322    /// Returns pair with slice of the current key and current value.
323    pub fn item(&self) -> Option<(&[u8], &[u8])> {
324        if self.valid() {
325            Some((self.key_impl(), self.value_impl()))
326        } else {
327            None
328        }
329    }
330
331    /// Returns a slice of the current key; assumes the iterator is valid.
332    fn key_impl(&self) -> &[u8] {
333        // Safety Note: This is safe as all methods that may invalidate the buffer returned
334        // take `&mut self`, so borrow checker will prevent use of buffer after seek.
335        unsafe {
336            let mut key_len: size_t = 0;
337            let key_len_ptr: *mut size_t = &mut key_len;
338            let key_ptr = ffi::rocksdb_iter_key(self.inner.as_ptr(), key_len_ptr);
339            slice::from_raw_parts(key_ptr as *const c_uchar, key_len)
340        }
341    }
342
343    /// Returns a slice of the current value; assumes the iterator is valid.
344    fn value_impl(&self) -> &[u8] {
345        // Safety Note: This is safe as all methods that may invalidate the buffer returned
346        // take `&mut self`, so borrow checker will prevent use of buffer after seek.
347        unsafe {
348            let mut val_len: size_t = 0;
349            let val_len_ptr: *mut size_t = &mut val_len;
350            let val_ptr = ffi::rocksdb_iter_value(self.inner.as_ptr(), val_len_ptr);
351            slice::from_raw_parts(val_ptr as *const c_uchar, val_len)
352        }
353    }
354}
355
356impl<'a, D: DBAccess> Drop for DBRawIteratorWithThreadMode<'a, D> {
357    fn drop(&mut self) {
358        unsafe {
359            ffi::rocksdb_iter_destroy(self.inner.as_ptr());
360        }
361    }
362}
363
364unsafe impl<'a, D: DBAccess> Send for DBRawIteratorWithThreadMode<'a, D> {}
365unsafe impl<'a, D: DBAccess> Sync for DBRawIteratorWithThreadMode<'a, D> {}
366
367/// A type alias to keep compatibility. See [`DBIteratorWithThreadMode`] for details
368pub type DBIterator<'a> = DBIteratorWithThreadMode<'a, DB>;
369
370/// An iterator over a database or column family, with specifiable
371/// ranges and direction.
372///
373/// ```
374/// use rocksdb::{DB, Direction, IteratorMode, Options};
375///
376/// let path = "_path_for_rocksdb_storage2";
377/// {
378///     let db = DB::open_default(path).unwrap();
379///     let mut iter = db.iterator(IteratorMode::Start); // Always iterates forward
380///     for item in iter {
381///         let (key, value) = item.unwrap();
382///         println!("Saw {:?} {:?}", key, value);
383///     }
384///     iter = db.iterator(IteratorMode::End);  // Always iterates backward
385///     for item in iter {
386///         let (key, value) = item.unwrap();
387///         println!("Saw {:?} {:?}", key, value);
388///     }
389///     iter = db.iterator(IteratorMode::From(b"my key", Direction::Forward)); // From a key in Direction::{forward,reverse}
390///     for item in iter {
391///         let (key, value) = item.unwrap();
392///         println!("Saw {:?} {:?}", key, value);
393///     }
394///
395///     // You can seek with an existing Iterator instance, too
396///     iter = db.iterator(IteratorMode::Start);
397///     iter.set_mode(IteratorMode::From(b"another key", Direction::Reverse));
398///     for item in iter {
399///         let (key, value) = item.unwrap();
400///         println!("Saw {:?} {:?}", key, value);
401///     }
402/// }
403/// let _ = DB::destroy(&Options::default(), path);
404/// ```
405pub struct DBIteratorWithThreadMode<'a, D: DBAccess> {
406    raw: DBRawIteratorWithThreadMode<'a, D>,
407    direction: Direction,
408    done: bool,
409}
410
411#[derive(Copy, Clone)]
412pub enum Direction {
413    Forward,
414    Reverse,
415}
416
417pub type KVBytes = (Box<[u8]>, Box<[u8]>);
418
419#[derive(Copy, Clone)]
420pub enum IteratorMode<'a> {
421    Start,
422    End,
423    From(&'a [u8], Direction),
424}
425
426impl<'a, D: DBAccess> DBIteratorWithThreadMode<'a, D> {
427    pub(crate) fn new(db: &D, readopts: ReadOptions, mode: IteratorMode) -> Self {
428        Self::from_raw(DBRawIteratorWithThreadMode::new(db, readopts), mode)
429    }
430
431    pub(crate) fn new_cf(
432        db: &'a D,
433        cf_handle: *mut ffi::rocksdb_column_family_handle_t,
434        readopts: ReadOptions,
435        mode: IteratorMode,
436    ) -> Self {
437        Self::from_raw(
438            DBRawIteratorWithThreadMode::new_cf(db, cf_handle, readopts),
439            mode,
440        )
441    }
442
443    fn from_raw(raw: DBRawIteratorWithThreadMode<'a, D>, mode: IteratorMode) -> Self {
444        let mut rv = DBIteratorWithThreadMode {
445            raw,
446            direction: Direction::Forward, // blown away by set_mode()
447            done: false,
448        };
449        rv.set_mode(mode);
450        rv
451    }
452
453    pub fn set_mode(&mut self, mode: IteratorMode) {
454        self.done = false;
455        self.direction = match mode {
456            IteratorMode::Start => {
457                self.raw.seek_to_first();
458                Direction::Forward
459            }
460            IteratorMode::End => {
461                self.raw.seek_to_last();
462                Direction::Reverse
463            }
464            IteratorMode::From(key, Direction::Forward) => {
465                self.raw.seek(key);
466                Direction::Forward
467            }
468            IteratorMode::From(key, Direction::Reverse) => {
469                self.raw.seek_for_prev(key);
470                Direction::Reverse
471            }
472        };
473    }
474}
475
476impl<'a, D: DBAccess> Iterator for DBIteratorWithThreadMode<'a, D> {
477    type Item = Result<KVBytes, Error>;
478
479    fn next(&mut self) -> Option<Result<KVBytes, Error>> {
480        if self.done {
481            None
482        } else if let Some((key, value)) = self.raw.item() {
483            let item = (Box::from(key), Box::from(value));
484            match self.direction {
485                Direction::Forward => self.raw.next(),
486                Direction::Reverse => self.raw.prev(),
487            }
488            Some(Ok(item))
489        } else {
490            self.done = true;
491            self.raw.status().err().map(Result::Err)
492        }
493    }
494}
495
496impl<'a, D: DBAccess> std::iter::FusedIterator for DBIteratorWithThreadMode<'a, D> {}
497
498impl<'a, D: DBAccess> Into<DBRawIteratorWithThreadMode<'a, D>> for DBIteratorWithThreadMode<'a, D> {
499    fn into(self) -> DBRawIteratorWithThreadMode<'a, D> {
500        self.raw
501    }
502}
503
504/// Iterates the batches of writes since a given sequence number.
505///
506/// `DBWALIterator` is returned by `DB::get_updates_since()` and will return the
507/// batches of write operations that have occurred since a given sequence number
508/// (see `DB::latest_sequence_number()`). This iterator cannot be constructed by
509/// the application.
510///
511/// The iterator item type is a tuple of (`u64`, `WriteBatch`) where the first
512/// value is the sequence number of the associated write batch.
513///
514pub struct DBWALIterator {
515    pub(crate) inner: *mut ffi::rocksdb_wal_iterator_t,
516    pub(crate) start_seq_number: u64,
517}
518
519impl DBWALIterator {
520    /// Returns `true` if the iterator is valid. An iterator is invalidated when
521    /// it reaches the end of its defined range, or when it encounters an error.
522    ///
523    /// To check whether the iterator encountered an error after `valid` has
524    /// returned `false`, use the [`status`](DBWALIterator::status) method.
525    /// `status` will never return an error when `valid` is `true`.
526    pub fn valid(&self) -> bool {
527        unsafe { ffi::rocksdb_wal_iter_valid(self.inner) != 0 }
528    }
529
530    /// Returns an error `Result` if the iterator has encountered an error
531    /// during operation. When an error is encountered, the iterator is
532    /// invalidated and [`valid`](DBWALIterator::valid) will return `false` when
533    /// called.
534    pub fn status(&self) -> Result<(), Error> {
535        unsafe {
536            ffi_try!(ffi::rocksdb_wal_iter_status(self.inner));
537        }
538        Ok(())
539    }
540}
541
542impl Iterator for DBWALIterator {
543    type Item = Result<(u64, WriteBatch), Error>;
544
545    fn next(&mut self) -> Option<Self::Item> {
546        if !self.valid() {
547            return None;
548        }
549
550        let mut seq: u64 = 0;
551        let mut batch = WriteBatch {
552            inner: unsafe { ffi::rocksdb_wal_iter_get_batch(self.inner, &mut seq) },
553        };
554
555        // if the initial sequence number is what was requested we skip it to
556        // only provide changes *after* it
557        if seq == self.start_seq_number {
558            unsafe {
559                ffi::rocksdb_wal_iter_next(self.inner);
560            }
561
562            if !self.valid() {
563                return None;
564            }
565
566            // this drops which in turn frees the skipped batch
567            batch = WriteBatch {
568                inner: unsafe { ffi::rocksdb_wal_iter_get_batch(self.inner, &mut seq) },
569            };
570        }
571
572        if !self.valid() {
573            return self.status().err().map(Result::Err);
574        }
575
576        // Seek to the next write batch.
577        // Note that WriteBatches live independently of the WAL iterator so this is safe to do
578        unsafe {
579            ffi::rocksdb_wal_iter_next(self.inner);
580        }
581
582        Some(Ok((seq, batch)))
583    }
584}
585
586impl Drop for DBWALIterator {
587    fn drop(&mut self) {
588        unsafe {
589            ffi::rocksdb_wal_iter_destroy(self.inner);
590        }
591    }
592}