Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lifetime-free range methods #732

Merged
merged 2 commits into from
Jan 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ use crate::tree_store::{
};
use crate::types::{RedbKey, RedbValue};
use crate::{
CompactionError, DatabaseError, Durability, ReadOnlyTable, ReadableTable, SavepointError,
StorageError,
CompactionError, DatabaseError, Durability, ReadOnlyTable, SavepointError, StorageError,
};
use crate::{ReadTransaction, Result, WriteTransaction};
use std::fmt::{Debug, Display, Formatter};
Expand Down
29 changes: 29 additions & 0 deletions src/multimap_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,35 @@ impl<'txn, K: RedbKey + 'static, V: RedbKey + 'static> ReadOnlyMultimapTable<'tx
_lifetime: Default::default(),
})
}

/// This method is like [`ReadableMultimapTable::get()`], but the iterator is reference counted and keeps the transaction
/// alive until it is dropped.
pub fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<MultimapValue<'static, V>> {
let iter = if let Some(collection) = self.tree.get(key.borrow())? {
DynamicCollection::iter(collection, self.transaction_guard.clone(), self.mem.clone())?
} else {
MultimapValue::new_subtree(
BtreeRangeIter::new::<RangeFull, &V::SelfType<'_>>(&(..), None, self.mem.clone())?,
self.transaction_guard.clone(),
)
};

Ok(iter)
}

/// This method is like [`ReadableMultimapTable::range()`], but the iterator is reference counted and keeps the transaction
/// alive until it is dropped.
pub fn range<'a, KR>(&self, range: impl RangeBounds<KR>) -> Result<MultimapRange<'static, K, V>>
where
KR: Borrow<K::SelfType<'a>>,
{
let inner = self.tree.range(&range)?;
Ok(MultimapRange::new(
inner,
self.transaction_guard.clone(),
self.mem.clone(),
))
}
}

impl<'txn, K: RedbKey + 'static, V: RedbKey + 'static> ReadableMultimapTable<K, V>
Expand Down
11 changes: 11 additions & 0 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,17 @@ impl<'txn, K: RedbKey + 'static, V: RedbValue + 'static> ReadOnlyTable<'txn, K,
_lifetime: Default::default(),
})
}

/// This method is like [`ReadableTable::range()`], but the iterator is reference counted and keeps the transaction
/// alive until it is dropped.
pub fn range<'a, KR>(&self, range: impl RangeBounds<KR>) -> Result<Range<'static, K, V>>
where
KR: Borrow<K::SelfType<'a>>,
{
self.tree
.range(&range)
.map(|x| Range::new(x, self.transaction_guard.clone()))
}
}

impl<'txn, K: RedbKey + 'static, V: RedbValue + 'static> ReadableTable<K, V>
Expand Down
13 changes: 5 additions & 8 deletions src/tree_store/btree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ impl UntypedBtreeMut {
}
}

pub(crate) struct BtreeMut<'a, K: RedbKey, V: RedbValue> {
pub(crate) struct BtreeMut<'a, K: RedbKey + 'static, V: RedbValue + 'static> {
mem: Arc<TransactionalMemory>,
transaction_guard: Arc<TransactionGuard>,
root: Arc<Mutex<Option<(PageNumber, Checksum)>>>,
Expand All @@ -227,7 +227,7 @@ pub(crate) struct BtreeMut<'a, K: RedbKey, V: RedbValue> {
_lifetime: PhantomData<&'a ()>,
}

impl<'a, K: RedbKey + 'a, V: RedbValue + 'a> BtreeMut<'a, K, V> {
impl<K: RedbKey + 'static, V: RedbValue + 'static> BtreeMut<'_, K, V> {
pub(crate) fn new(
root: Option<(PageNumber, Checksum)>,
guard: Arc<TransactionGuard>,
Expand Down Expand Up @@ -552,7 +552,7 @@ impl RawBtree {
}
}

pub(crate) struct Btree<K: RedbKey, V: RedbValue> {
pub(crate) struct Btree<K: RedbKey + 'static, V: RedbValue + 'static> {
mem: Arc<TransactionalMemory>,
_transaction_guard: Arc<TransactionGuard>,
// Cache of the root page to avoid repeated lookups
Expand Down Expand Up @@ -621,13 +621,10 @@ impl<K: RedbKey, V: RedbValue> Btree<K, V> {
}
}

pub(crate) fn range<'a0, T: RangeBounds<KR> + 'a0, KR: Borrow<K::SelfType<'a0>> + 'a0>(
pub(crate) fn range<'a0, T: RangeBounds<KR>, KR: Borrow<K::SelfType<'a0>>>(
&self,
range: &'_ T,
) -> Result<BtreeRangeIter<K, V>>
where
K: 'a0,
{
) -> Result<BtreeRangeIter<K, V>> {
BtreeRangeIter::new(range, self.root.map(|(p, _)| p), self.mem.clone())
}

Expand Down
17 changes: 7 additions & 10 deletions src/tree_store/btree_iters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ impl Iterator for AllPageNumbersBtreeIter {
}
}

pub(crate) struct BtreeDrain<K: RedbKey, V: RedbValue> {
pub(crate) struct BtreeDrain<K: RedbKey + 'static, V: RedbValue + 'static> {
inner: BtreeRangeIter<K, V>,
free_on_drop: Vec<PageNumber>,
master_free_list: Arc<Mutex<Vec<PageNumber>>>,
Expand Down Expand Up @@ -298,8 +298,8 @@ impl<K: RedbKey, V: RedbValue> Drop for BtreeDrain<K, V> {
}

pub(crate) struct BtreeDrainFilter<
K: RedbKey,
V: RedbValue,
K: RedbKey + 'static,
V: RedbValue + 'static,
F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> {
inner: BtreeRangeIter<K, V>,
Expand Down Expand Up @@ -380,7 +380,7 @@ impl<K: RedbKey, V: RedbValue, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>
}
}

pub(crate) struct BtreeRangeIter<K: RedbKey, V: RedbValue> {
pub(crate) struct BtreeRangeIter<K: RedbKey + 'static, V: RedbValue + 'static> {
left: Option<RangeIterState>, // Exclusive. The previous element returned
right: Option<RangeIterState>, // Exclusive. The previous element returned
include_left: bool, // left is inclusive, instead of exclusive
Expand All @@ -390,15 +390,12 @@ pub(crate) struct BtreeRangeIter<K: RedbKey, V: RedbValue> {
_value_type: PhantomData<V>,
}

impl<K: RedbKey, V: RedbValue> BtreeRangeIter<K, V> {
pub(crate) fn new<'a0, T: RangeBounds<KR> + 'a0, KR: Borrow<K::SelfType<'a0>> + 'a0>(
impl<K: RedbKey + 'static, V: RedbValue + 'static> BtreeRangeIter<K, V> {
pub(crate) fn new<'a, T: RangeBounds<KR>, KR: Borrow<K::SelfType<'a>>>(
query_range: &'_ T,
table_root: Option<PageNumber>,
manager: Arc<TransactionalMemory>,
) -> Result<Self>
where
K: 'a0,
{
) -> Result<Self> {
if let Some(root) = table_root {
let (include_left, left) = match query_range.start_bound() {
Bound::Included(k) => find_iter_left::<K, V>(
Expand Down
24 changes: 24 additions & 0 deletions tests/basic_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,30 @@ fn range_lifetime() {
assert!(iter.next().is_none());
}

#[test]
fn range_arc() {
let tmpfile = create_tempfile();
let db = Database::create(tmpfile.path()).unwrap();

let definition: TableDefinition<&str, &str> = TableDefinition::new("x");

let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_table(definition).unwrap();
table.insert("hello", "world").unwrap();
}
write_txn.commit().unwrap();

let mut iter = {
let read_txn = db.begin_read().unwrap();
let table = read_txn.open_table(definition).unwrap();
let start = "hello".to_string();
table.range::<&str>(start.as_str()..).unwrap()
};
assert_eq!(iter.next().unwrap().unwrap().1.value(), "world");
assert!(iter.next().is_none());
}

#[test]
fn drain_lifetime() {
let tmpfile = create_tempfile();
Expand Down
58 changes: 58 additions & 0 deletions tests/multimap_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,64 @@ fn range_lifetime() {
assert!(iter.next().is_none());
}

#[test]
fn range_arc_lifetime() {
let tmpfile = create_tempfile();
let db = Database::create(tmpfile.path()).unwrap();

let definition: MultimapTableDefinition<&str, &str> = MultimapTableDefinition::new("x");

let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_multimap_table(definition).unwrap();
table.insert("hello", "world").unwrap();
}
write_txn.commit().unwrap();

let mut iter = {
let read_txn = db.begin_read().unwrap();
let table = read_txn.open_multimap_table(definition).unwrap();
let start = "hello".to_string();
table.range::<&str>(start.as_str()..).unwrap()
};
assert_eq!(
iter.next()
.unwrap()
.unwrap()
.1
.next()
.unwrap()
.unwrap()
.value(),
"world"
);
assert!(iter.next().is_none());
}

#[test]
fn get_arc_lifetime() {
let tmpfile = create_tempfile();
let db = Database::create(tmpfile.path()).unwrap();

let definition: MultimapTableDefinition<&str, &str> = MultimapTableDefinition::new("x");

let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_multimap_table(definition).unwrap();
table.insert("hello", "world").unwrap();
}
write_txn.commit().unwrap();

let mut iter = {
let read_txn = db.begin_read().unwrap();
let table = read_txn.open_multimap_table(definition).unwrap();
let start = "hello".to_string();
table.get(start.as_str()).unwrap()
};
assert_eq!(iter.next().unwrap().unwrap().value(), "world");
assert!(iter.next().is_none());
}

#[test]
fn delete() {
let tmpfile = create_tempfile();
Expand Down
Loading