Skip to main content

libkeri/keri/db/subing/
on.rs

1use crate::keri::db::dbing::LMDBer;
2use crate::keri::db::subing::{Suber, SuberBase};
3use crate::keri::db::subing::{SuberError, Utf8Codec, ValueCodec};
4use std::sync::Arc;
5
6pub struct OnSuberBase<C: ValueCodec = Utf8Codec> {
7    pub base: SuberBase<C>,
8}
9
10impl<C: ValueCodec> crate::keri::db::subing::on::OnSuberBase<C> {
11    /// Creates a new `OnSuberBase`.
12    ///
13    /// # Parameters
14    /// * `db` - The base database (LMDBer)
15    /// * `subkey` - LMDB sub database key
16    /// * `sep` - Separator to convert keys iterator to key bytes for db key. Default '.'
17    /// * `verify` - Whether to reverify when ._des from db when applicable. Default false
18    /// * `dupsort` - Whether to enable duplicates at each key. Default false
19    pub fn new(
20        db: Arc<LMDBer>,
21        subkey: &str,
22        sep: Option<u8>,
23        verify: bool,
24        dupsort: Option<bool>,
25    ) -> Result<Self, SuberError> {
26        let base = SuberBase::new(db, subkey, sep, verify, dupsort)?;
27
28        Ok(Self { base })
29    }
30
31    /// Returns whether duplicates are enabled at each key
32    pub fn is_dupsort(&self) -> bool {
33        self.base.is_dupsort()
34    }
35
36    /// Converts a collection of keys to a single key byte vector
37    pub fn _tokey<K: AsRef<[u8]>>(&self, keys: &[K]) -> Vec<u8> {
38        self.base.to_key(keys, false)
39    }
40
41    /// Converts a key byte vector to a collection of keys
42    pub fn _tokeys(&self, key: &[u8]) -> Vec<Vec<u8>> {
43        self.base.to_keys(key)
44    }
45
46    /// Serializes a value
47    pub fn _ser<T: ?Sized + Clone + Into<Vec<u8>>>(&self, val: &T) -> Result<Vec<u8>, SuberError> {
48        self.base.ser(val)
49    }
50
51    /// Deserializes a value
52    pub fn _des<T: TryFrom<Vec<u8>>>(&self, val: &[u8]) -> Result<T, SuberError> {
53        self.base.des(val)
54    }
55
56    /// Puts a value at a key with an ordinal number
57    ///
58    /// # Returns
59    /// * `true` if the onkey made from key+sep+serialized on is not found in database so value is written idempotently
60    /// * `false` otherwise
61    ///
62    /// # Parameters
63    /// * `keys` - Keys as prefix to be combined with serialized on suffix and sep to form onkey
64    /// * `on` - Ordinal number used to form key
65    /// * `val` - Serialization
66    pub fn put_on<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
67        &self,
68        keys: &[K],
69        on: u32,
70        val: &V,
71    ) -> Result<bool, SuberError> {
72        let key = self._tokey(keys);
73        let sval = self._ser(val)?;
74
75        self.base
76            .db
77            .put_on_val(&self.base.sdb, &key, on, &sval, Some([self.base.sep]))
78            .map_err(SuberError::DBError)
79    }
80
81    /// Sets or overwrites a value at a key with an ordinal number
82    ///
83    /// # Returns
84    /// * `true` if value is written or overwritten at onkey
85    /// * `false` otherwise
86    ///
87    /// # Parameters
88    /// * `keys` - Keys as prefix to be combined with serialized on suffix and sep to form onkey
89    /// * `on` - Ordinal number used to form key
90    /// * `val` - Serialization
91    pub fn pin_on<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
92        &self,
93        keys: &[K],
94        on: u32,
95        val: &V,
96    ) -> Result<bool, SuberError> {
97        let key = self._tokey(keys);
98        let sval = self._ser(val)?;
99
100        self.base
101            .db
102            .set_on_val(
103                &self.base.sdb,
104                &key,
105                Some(on as u64),
106                &sval,
107                Some([self.base.sep]),
108            )
109            .map_err(SuberError::DBError)
110    }
111
112    /// Appends a value with an automatically assigned ordinal number
113    ///
114    /// # Returns
115    /// * Ordinal number of newly appended value
116    ///
117    /// # Parameters
118    /// * `keys` - Top keys as prefix to be combined with serialized on suffix and sep to form key
119    /// * `val` - Serialization
120    pub fn append_on<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
121        &self,
122        keys: &[K],
123        val: &V,
124    ) -> Result<u64, SuberError> {
125        let key = self._tokey(keys);
126        let sval = self._ser(val)?;
127
128        self.base
129            .db
130            .append_on_val(&self.base.sdb, &key, &sval, Some([self.base.sep]))
131            .map_err(SuberError::DBError)
132    }
133
134    /// Gets a value at a key with an ordinal number
135    ///
136    /// # Returns
137    /// * Serialization at onkey if any
138    /// * None if no entry at onkey
139    ///
140    /// # Parameters
141    /// * `keys` - Keys as prefix to be combined with serialized on suffix and sep to form onkey
142    /// * `on` - Ordinal number used to form key
143    pub fn get_on<K: AsRef<[u8]>, R: TryFrom<Vec<u8>>>(
144        &self,
145        keys: &[K],
146        on: u32,
147    ) -> Result<Option<R>, SuberError>
148    where
149        <R as TryFrom<Vec<u8>>>::Error: std::fmt::Debug,
150    {
151        let key = self._tokey(keys);
152
153        match self
154            .base
155            .db
156            .get_on_val(&self.base.sdb, &key, on, Some([self.base.sep]))
157            .map_err(SuberError::DBError)?
158        {
159            Some(val) => Ok(Some(self._des(&val)?)),
160            None => Ok(None),
161        }
162    }
163
164    /// Removes a value at a key with an ordinal number
165    ///
166    /// # Returns
167    /// * `true` if onkey made from key+sep+serialized on is found in database so value is removed
168    /// * `false` otherwise
169    ///
170    /// # Parameters
171    /// * `keys` - Keys as prefix to be combined with serialized on suffix and sep to form onkey
172    /// * `on` - Ordinal number used to form key
173    pub fn rem_on<K: AsRef<[u8]>>(&self, keys: &[K], on: u32) -> Result<bool, SuberError> {
174        let key = self._tokey(keys);
175
176        self.base
177            .db
178            .del_on_val(&self.base.sdb, &key, on, Some([self.base.sep]))
179            .map_err(SuberError::DBError)
180    }
181
182    /// Counts the number of values with ordinal number suffix
183    ///
184    /// # Returns
185    /// * Count of all ordinal suffix keyed vals with same key prefix but different on in onkey
186    ///
187    /// # Parameters
188    /// * `keys` - Top keys as prefix to be combined with serialized on suffix and sep to form top key
189    /// * `on` - Ordinal number used to form key
190    pub fn cnt_on<K: AsRef<[u8]>>(&self, keys: &[K], on: u32) -> Result<usize, SuberError> {
191        let key = self._tokey(keys);
192
193        self.base
194            .db
195            .cnt_on_vals(
196                &self.base.sdb,
197                Some(&key),
198                Some(on as u64),
199                Some([self.base.sep]),
200            )
201            .map_err(SuberError::DBError)
202    }
203
204    /// Gets an iterator over values with ordinal number suffix >= on
205    ///
206    /// # Returns
207    /// * Iterator over values with same key but increments of on >= on
208    ///
209    /// # Parameters
210    /// * `keys` - Keys as prefix to be combined with serialized on suffix and sep to form actual key
211    /// * `on` - Ordinal number used to form key at which to initiate retrieval
212    pub fn get_on_iter<K: AsRef<[u8]>, R: TryFrom<Vec<u8>> + 'static>(
213        &self,
214        keys: &[K],
215        on: u32,
216    ) -> Result<Vec<R>, SuberError>
217    where
218        <R as TryFrom<Vec<u8>>>::Error: std::fmt::Debug,
219    {
220        let key = self._tokey(keys);
221        let mut raw_results: Vec<Vec<u8>> = Vec::new(); // First collect raw bytes
222
223        self.base
224            .db
225            .get_on_val_iter(
226                &self.base.sdb,
227                Some(&key),
228                Some(on as u64),
229                Some([self.base.sep]),
230                |val| {
231                    // Store the value to process after the callback
232                    raw_results.push(val.to_vec());
233                    Ok(true)
234                },
235            )
236            .map_err(SuberError::DBError)?;
237
238        // Process the values after the callback is done
239        let mut results = Vec::new(); // This will hold the final deserialized values
240        for val in raw_results {
241            results.push(self._des(&val)?);
242        }
243
244        Ok(results)
245    }
246
247    /// Gets an iterator over (key, on, val) triples with ordinal number suffix >= on
248    ///
249    /// # Returns
250    /// * Iterator over (key, on, val) triples with same key but increments of on >= on
251    ///
252    /// # Parameters
253    /// * `keys` - Keys as prefix to be combined with serialized on suffix and sep to form actual key
254    /// * `on` - Ordinal number used to form key at which to initiate retrieval
255    pub fn get_on_item_iter<K: AsRef<[u8]>, R: TryFrom<Vec<u8>> + 'static>(
256        &self,
257        keys: &[K],
258        on: u32,
259    ) -> Result<Vec<(Vec<Vec<u8>>, u64, R)>, SuberError>
260    where
261        <R as TryFrom<Vec<u8>>>::Error: std::fmt::Debug,
262    {
263        let key = self._tokey(keys);
264        let mut raw_results: Vec<(Vec<u8>, u64, Vec<u8>)> = Vec::new();
265
266        self.base
267            .db
268            .get_on_item_iter(
269                &self.base.sdb,
270                Some(&key),
271                Some(on as u64),
272                Some([self.base.sep]),
273                |k, o, val| {
274                    // Store the data to process after the callback
275                    let k_copy = k.to_vec();
276                    let val_copy = val.to_vec();
277                    raw_results.push((k_copy, o, val_copy));
278                    Ok(true)
279                },
280            )
281            .map_err(SuberError::DBError)?;
282
283        // Process the data after the callback is done
284        let mut results = Vec::new();
285        for (k, o, val) in raw_results {
286            let deserialized = self._des(&val)?;
287            results.push((self._tokeys(&k), o, deserialized));
288        }
289
290        Ok(results)
291    }
292}
293
294pub struct OnSuber<C: ValueCodec = Utf8Codec> {
295    pub base: Suber<C>,
296    pub on_base: OnSuberBase<C>,
297}
298
299impl<C: ValueCodec> OnSuber<C> {
300    pub fn new(
301        db: Arc<LMDBer>,
302        subkey: &str,
303        sep: Option<u8>,
304        verify: bool,
305    ) -> Result<Self, SuberError> {
306        let base = Suber::new(db.clone(), subkey, sep, verify)?;
307        let on_base = OnSuberBase::new(db, subkey, sep, verify, Some(false))?;
308
309        Ok(Self { base, on_base })
310    }
311
312    // === Methods from Suber ===
313
314    pub fn put<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
315        &self,
316        keys: &[K],
317        val: &V,
318    ) -> Result<bool, SuberError> {
319        self.base.put(keys, val)
320    }
321
322    pub fn pin<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
323        &self,
324        keys: &[K],
325        val: &V,
326    ) -> Result<bool, SuberError> {
327        self.base.pin(keys, val)
328    }
329
330    pub fn get<K: AsRef<[u8]>, V: TryFrom<Vec<u8>>>(
331        &self,
332        keys: &[K],
333    ) -> Result<Option<V>, SuberError> {
334        self.base.get(keys)
335    }
336
337    pub fn rem<K: AsRef<[u8]>>(&self, keys: &[K]) -> Result<bool, SuberError> {
338        self.base.rem(keys)
339    }
340
341    pub fn trim<K: AsRef<[u8]>>(&self, keys: &[K], topive: bool) -> Result<bool, SuberError> {
342        self.base.trim(keys, topive)
343    }
344
345    pub fn get_full_item_iter<K: AsRef<[u8]>>(
346        &self,
347        keys: &[K],
348        topive: bool,
349    ) -> Result<Vec<(Vec<Vec<u8>>, Vec<u8>)>, SuberError> {
350        self.base.get_full_item_iter(keys, topive)
351    }
352
353    pub fn get_item_iter<K: AsRef<[u8]>>(
354        &self,
355        keys: &[K],
356        topive: bool,
357    ) -> Result<Vec<(Vec<Vec<u8>>, Vec<u8>)>, SuberError> {
358        self.base.get_item_iter(keys, topive)
359    }
360
361    pub fn cnt_all(&self) -> Result<usize, SuberError> {
362        self.base.cnt_all()
363    }
364
365    // === Methods from OnSuberBase ===
366
367    pub fn is_dupsort(&self) -> bool {
368        self.on_base.is_dupsort()
369    }
370
371    pub fn put_on<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
372        &self,
373        keys: &[K],
374        on: u32,
375        val: &V,
376    ) -> Result<bool, SuberError> {
377        self.on_base.put_on(keys, on, val)
378    }
379
380    pub fn pin_on<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
381        &self,
382        keys: &[K],
383        on: u32,
384        val: &V,
385    ) -> Result<bool, SuberError> {
386        self.on_base.pin_on(keys, on, val)
387    }
388
389    pub fn append_on<K: AsRef<[u8]>, V: ?Sized + Clone + Into<Vec<u8>>>(
390        &self,
391        keys: &[K],
392        val: &V,
393    ) -> Result<u64, SuberError> {
394        self.on_base.append_on(keys, val)
395    }
396
397    pub fn get_on<K: AsRef<[u8]>, R: TryFrom<Vec<u8>>>(
398        &self,
399        keys: &[K],
400        on: u32,
401    ) -> Result<Option<R>, SuberError>
402    where
403        <R as TryFrom<Vec<u8>>>::Error: std::fmt::Debug,
404    {
405        self.on_base.get_on(keys, on)
406    }
407
408    pub fn rem_on<K: AsRef<[u8]>>(&self, keys: &[K], on: u32) -> Result<bool, SuberError> {
409        self.on_base.rem_on(keys, on)
410    }
411
412    pub fn cnt_on<K: AsRef<[u8]>>(&self, keys: &[K], on: u32) -> Result<usize, SuberError> {
413        self.on_base.cnt_on(keys, on)
414    }
415
416    pub fn get_on_iter<K: AsRef<[u8]>, R: TryFrom<Vec<u8>> + 'static>(
417        &self,
418        keys: &[K],
419        on: u32,
420    ) -> Result<Vec<R>, SuberError>
421    where
422        <R as TryFrom<Vec<u8>>>::Error: std::fmt::Debug,
423    {
424        self.on_base.get_on_iter(keys, on)
425    }
426
427    pub fn get_on_item_iter<K: AsRef<[u8]>, R: TryFrom<Vec<u8>> + 'static>(
428        &self,
429        keys: &[K],
430        on: u32,
431    ) -> Result<Vec<(Vec<Vec<u8>>, u64, R)>, SuberError>
432    where
433        <R as TryFrom<Vec<u8>>>::Error: std::fmt::Debug,
434    {
435        self.on_base.get_on_item_iter(keys, on)
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use crate::keri::db::dbing::LMDBer;
443    use std::sync::Arc;
444
445    #[test]
446    fn test_on_suber() -> Result<(), SuberError> {
447        // Create a temporary database
448        let db = LMDBer::builder()
449            .temp(true)
450            .name("test")
451            .build()
452            .map_err(SuberError::DBError)?;
453
454        assert_eq!(db.name(), "test");
455        assert!(db.opened());
456
457        let db_ref = Arc::new(db);
458
459        // Create OnSuber instance
460        let onsuber = OnSuber::<Utf8Codec>::new(db_ref.clone(), "bags.", None, false)?;
461
462        // Verify not dupsort (matches Python test)
463        assert!(!onsuber.is_dupsort());
464
465        // Test values
466        let w = "Blue dog";
467        let x = "Green tree";
468        let y = "Red apple";
469        let z = "White snow";
470
471        // Test append_on
472        assert_eq!(onsuber.append_on(&["a"], &w)?, 0);
473        assert_eq!(onsuber.append_on(&["a"], &x)?, 1);
474        assert_eq!(onsuber.append_on(&["a"], &y)?, 2);
475        assert_eq!(onsuber.append_on(&["a"], &z)?, 3);
476
477        // Test cnt_on
478        assert_eq!(onsuber.cnt_on(&["a"], 0)?, 4);
479        assert_eq!(onsuber.cnt_on(&["a"], 2)?, 2);
480        assert_eq!(onsuber.cnt_on(&["a"], 4)?, 0);
481
482        // Test get_item_iter
483        let items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = onsuber.get_item_iter(&[] as &[&str], true)?;
484
485        // Convert to strings for easier assertions
486        let items_as_strings: Vec<(Vec<String>, String)> = items
487            .into_iter()
488            .map(|(keys_bytes, val_bytes)| {
489                let parsed_keys = keys_bytes
490                    .into_iter()
491                    .map(|k| String::from_utf8(k).unwrap())
492                    .collect();
493                (parsed_keys, String::from_utf8(val_bytes).unwrap())
494            })
495            .collect();
496
497        assert_eq!(items_as_strings.len(), 4);
498        assert!(items_as_strings.contains(&(
499            vec![
500                "a".to_string(),
501                "00000000000000000000000000000000".to_string()
502            ],
503            "Blue dog".to_string()
504        )));
505        assert!(items_as_strings.contains(&(
506            vec![
507                "a".to_string(),
508                "00000000000000000000000000000001".to_string()
509            ],
510            "Green tree".to_string()
511        )));
512        assert!(items_as_strings.contains(&(
513            vec![
514                "a".to_string(),
515                "00000000000000000000000000000002".to_string()
516            ],
517            "Red apple".to_string()
518        )));
519        assert!(items_as_strings.contains(&(
520            vec![
521                "a".to_string(),
522                "00000000000000000000000000000003".to_string()
523            ],
524            "White snow".to_string()
525        )));
526
527        // Test get_on_item_iter
528        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> =
529            onsuber.get_on_item_iter::<&str, Vec<u8>>(&[] as &[&str], 0)?;
530
531        // Convert to strings for easier assertions
532        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
533            .into_iter()
534            .map(|(keys_bytes, idx, val_bytes)| {
535                let parsed_keys = keys_bytes
536                    .into_iter()
537                    .map(|k| String::from_utf8(k).unwrap())
538                    .collect();
539                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
540            })
541            .collect();
542
543        assert_eq!(on_items_as_strings.len(), 4);
544        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 0, "Blue dog".to_string())));
545        assert!(on_items_as_strings.contains(&(
546            vec!["a".to_string()],
547            1,
548            "Green tree".to_string()
549        )));
550        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 2, "Red apple".to_string())));
551        assert!(on_items_as_strings.contains(&(
552            vec!["a".to_string()],
553            3,
554            "White snow".to_string()
555        )));
556
557        // Test get_on_item_iter with specific key
558        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = onsuber.get_on_item_iter(&["a"], 0)?;
559
560        // Convert to strings
561        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
562            .into_iter()
563            .map(|(keys_bytes, idx, val_bytes)| {
564                let parsed_keys = keys_bytes
565                    .into_iter()
566                    .map(|k| String::from_utf8(k).unwrap())
567                    .collect();
568                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
569            })
570            .collect();
571
572        assert_eq!(on_items_as_strings.len(), 4);
573        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 0, "Blue dog".to_string())));
574        assert!(on_items_as_strings.contains(&(
575            vec!["a".to_string()],
576            1,
577            "Green tree".to_string()
578        )));
579        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 2, "Red apple".to_string())));
580        assert!(on_items_as_strings.contains(&(
581            vec!["a".to_string()],
582            3,
583            "White snow".to_string()
584        )));
585
586        // Test get_on_item_iter with specific on index
587        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = onsuber.get_on_item_iter(&["a"], 2)?;
588
589        // Convert to strings
590        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
591            .into_iter()
592            .map(|(keys_bytes, idx, val_bytes)| {
593                let parsed_keys = keys_bytes
594                    .into_iter()
595                    .map(|k| String::from_utf8(k).unwrap())
596                    .collect();
597                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
598            })
599            .collect();
600
601        assert_eq!(on_items_as_strings.len(), 2);
602        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 2, "Red apple".to_string())));
603        assert!(on_items_as_strings.contains(&(
604            vec!["a".to_string()],
605            3,
606            "White snow".to_string()
607        )));
608
609        // Test get_on_iter - no args
610        let on_vals: Vec<Vec<u8>> = onsuber.get_on_iter::<&str, Vec<u8>>(&[] as &[&str], 0)?;
611
612        // Convert to strings
613        let on_vals_as_strings: Vec<String> = on_vals
614            .into_iter()
615            .map(|val| String::from_utf8(val).unwrap())
616            .collect();
617
618        assert_eq!(on_vals_as_strings.len(), 4);
619        assert!(on_vals_as_strings.contains(&"Blue dog".to_string()));
620        assert!(on_vals_as_strings.contains(&"Green tree".to_string()));
621        assert!(on_vals_as_strings.contains(&"Red apple".to_string()));
622        assert!(on_vals_as_strings.contains(&"White snow".to_string()));
623
624        // Test get_on_iter with specific key
625        let on_vals: Vec<Vec<u8>> = onsuber.get_on_iter(&["a"], 0)?;
626
627        // Convert to strings
628        let on_vals_as_strings: Vec<String> = on_vals
629            .into_iter()
630            .map(|val| String::from_utf8(val).unwrap())
631            .collect();
632
633        assert_eq!(on_vals_as_strings.len(), 4);
634        assert!(on_vals_as_strings.contains(&"Blue dog".to_string()));
635        assert!(on_vals_as_strings.contains(&"Green tree".to_string()));
636        assert!(on_vals_as_strings.contains(&"Red apple".to_string()));
637        assert!(on_vals_as_strings.contains(&"White snow".to_string()));
638
639        // Test get_on_iter with specific on index
640        let on_vals: Vec<Vec<u8>> = onsuber.get_on_iter(&["a"], 2)?;
641
642        // Convert to strings
643        let on_vals_as_strings: Vec<String> = on_vals
644            .into_iter()
645            .map(|val| String::from_utf8(val).unwrap())
646            .collect();
647
648        assert_eq!(on_vals_as_strings.len(), 2);
649        assert!(on_vals_as_strings.contains(&"Red apple".to_string()));
650        assert!(on_vals_as_strings.contains(&"White snow".to_string()));
651
652        // Test append for additional keys
653        assert_eq!(onsuber.append_on(&["b"], &w)?, 0);
654        assert_eq!(onsuber.append_on(&["b"], &x)?, 1);
655        assert_eq!(onsuber.append_on(&["bc"], &y)?, 0);
656        assert_eq!(onsuber.append_on(&["ac"], &z)?, 0);
657
658        // Test counts
659        assert_eq!(onsuber.cnt_on(&["b"], 0)?, 2);
660        assert_eq!(onsuber.cnt_on(&["ac"], 2)?, 0);
661        assert_eq!(onsuber.cnt_on(&[""], 0)?, 8);
662
663        // Test get_item_iter for all items
664        let items = onsuber.get_item_iter::<Vec<u8>>(&[], true)?;
665
666        // Convert to strings for easier assertions
667        let items_as_strings: Vec<(Vec<String>, String)> = items
668            .into_iter()
669            .map(|(keys_bytes, val_bytes)| {
670                let parsed_keys = keys_bytes
671                    .into_iter()
672                    .map(|k| String::from_utf8(k).unwrap())
673                    .collect();
674                (parsed_keys, String::from_utf8(val_bytes).unwrap())
675            })
676            .collect();
677
678        assert_eq!(items_as_strings.len(), 8);
679        // Check all the key-value pairs we expect
680        assert!(items_as_strings.contains(&(
681            vec![
682                "a".to_string(),
683                "00000000000000000000000000000000".to_string()
684            ],
685            "Blue dog".to_string()
686        )));
687        assert!(items_as_strings.contains(&(
688            vec![
689                "a".to_string(),
690                "00000000000000000000000000000001".to_string()
691            ],
692            "Green tree".to_string()
693        )));
694        assert!(items_as_strings.contains(&(
695            vec![
696                "a".to_string(),
697                "00000000000000000000000000000002".to_string()
698            ],
699            "Red apple".to_string()
700        )));
701        assert!(items_as_strings.contains(&(
702            vec![
703                "a".to_string(),
704                "00000000000000000000000000000003".to_string()
705            ],
706            "White snow".to_string()
707        )));
708        assert!(items_as_strings.contains(&(
709            vec![
710                "ac".to_string(),
711                "00000000000000000000000000000000".to_string()
712            ],
713            "White snow".to_string()
714        )));
715        assert!(items_as_strings.contains(&(
716            vec![
717                "b".to_string(),
718                "00000000000000000000000000000000".to_string()
719            ],
720            "Blue dog".to_string()
721        )));
722        assert!(items_as_strings.contains(&(
723            vec![
724                "b".to_string(),
725                "00000000000000000000000000000001".to_string()
726            ],
727            "Green tree".to_string()
728        )));
729        assert!(items_as_strings.contains(&(
730            vec![
731                "bc".to_string(),
732                "00000000000000000000000000000000".to_string()
733            ],
734            "Red apple".to_string()
735        )));
736
737        // Test get_on_item_iter with specific key
738        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = onsuber.get_on_item_iter(&["b"], 0)?;
739
740        // Convert to strings
741        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
742            .into_iter()
743            .map(|(keys_bytes, idx, val_bytes)| {
744                let parsed_keys = keys_bytes
745                    .into_iter()
746                    .map(|k| String::from_utf8(k).unwrap())
747                    .collect();
748                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
749            })
750            .collect();
751
752        assert_eq!(on_items_as_strings.len(), 2);
753        assert!(on_items_as_strings.contains(&(vec!["b".to_string()], 0, "Blue dog".to_string())));
754        assert!(on_items_as_strings.contains(&(
755            vec!["b".to_string()],
756            1,
757            "Green tree".to_string()
758        )));
759
760        // Test get_on_item_iter with tuple key
761        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = onsuber.get_on_item_iter(&["b"], 0)?;
762
763        // Convert to strings
764        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
765            .into_iter()
766            .map(|(keys_bytes, idx, val_bytes)| {
767                let parsed_keys = keys_bytes
768                    .into_iter()
769                    .map(|k| String::from_utf8(k).unwrap())
770                    .collect();
771                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
772            })
773            .collect();
774
775        assert_eq!(on_items_as_strings.len(), 2);
776        assert!(on_items_as_strings.contains(&(vec!["b".to_string()], 0, "Blue dog".to_string())));
777        assert!(on_items_as_strings.contains(&(
778            vec!["b".to_string()],
779            1,
780            "Green tree".to_string()
781        )));
782
783        // Test get_on_item_iter with empty key parts
784        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> =
785            onsuber.get_on_item_iter(&["b", ""], 0)?;
786        assert_eq!(on_items.len(), 0);
787
788        // Test get_on_item_iter with empty key
789        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = onsuber.get_on_item_iter(&[""], 0)?;
790
791        // Convert to strings
792        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
793            .into_iter()
794            .map(|(keys_bytes, idx, val_bytes)| {
795                let parsed_keys = keys_bytes
796                    .into_iter()
797                    .map(|k| String::from_utf8(k).unwrap())
798                    .collect();
799                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
800            })
801            .collect();
802
803        assert_eq!(on_items_as_strings.len(), 8);
804        // Here we'd check all 8 items but for brevity I'll check just the count
805
806        // Test get_on_item_iter with no args
807        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> =
808            onsuber.get_on_item_iter::<&str, Vec<u8>>(&[], 0)?;
809
810        // Convert to strings
811        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
812            .into_iter()
813            .map(|(keys_bytes, idx, val_bytes)| {
814                let parsed_keys = keys_bytes
815                    .into_iter()
816                    .map(|k| String::from_utf8(k).unwrap())
817                    .collect();
818                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
819            })
820            .collect();
821
822        assert_eq!(on_items_as_strings.len(), 8);
823        // Again, just checking count for brevity
824
825        // Test rem_on
826        assert!(onsuber.rem_on(&["a"], 1)?);
827        assert!(!onsuber.rem_on(&["a"], 1)?); // Should now return false as already removed
828        assert!(onsuber.rem_on(&["a"], 3)?);
829        assert!(!onsuber.rem_on(&["a"], 3)?); // Should now return false as already removed
830
831        // Verify count after removal
832        assert_eq!(onsuber.cnt_on(&["a"], 0)?, 2);
833
834        // Test get_on_item_iter after removals
835        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = onsuber.get_on_item_iter(&["a"], 0)?;
836
837        // Convert to strings
838        let on_items_as_strings: Vec<(Vec<String>, u64, String)> = on_items
839            .into_iter()
840            .map(|(keys_bytes, idx, val_bytes)| {
841                let parsed_keys = keys_bytes
842                    .into_iter()
843                    .map(|k| String::from_utf8(k).unwrap())
844                    .collect();
845                (parsed_keys, idx, String::from_utf8(val_bytes).unwrap())
846            })
847            .collect();
848
849        assert_eq!(on_items_as_strings.len(), 2);
850        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 0, "Blue dog".to_string())));
851        assert!(on_items_as_strings.contains(&(vec!["a".to_string()], 2, "Red apple".to_string())));
852
853        // Test put_on and get_on
854        assert!(onsuber.put_on(&["d"], 0, &"moon")?);
855        let moon: Option<Vec<u8>> = onsuber.get_on(&["d"], 0)?;
856        assert!(moon.is_some());
857        assert_eq!(String::from_utf8(moon.unwrap()).unwrap(), "moon");
858
859        // Test put_on with duplicate (should return false)
860        assert!(!onsuber.put_on(&["d"], 0, &"moon")?);
861
862        // Test pin_on
863        assert!(onsuber.pin_on(&["d"], 0, &"sun")?);
864        let sun: Option<Vec<u8>> = onsuber.get_on(&["d"], 0)?;
865        assert!(sun.is_some());
866        assert_eq!(String::from_utf8(sun.unwrap()).unwrap(), "sun");
867
868        // Test rem_on
869        assert!(onsuber.rem_on(&["d"], 0)?);
870
871        // The database should be closed when db goes out of scope
872        drop(db_ref);
873
874        Ok(())
875    }
876}