ic_db/store/query/
get_many.rs1use super::{Database, Projection, QuerySource, SelectColumns, Selection};
4use crate::{Entity, EntitySchema, Error, Id, IndexValue, PrimaryKey, primary::RowKey};
5use ic_storage::{DefaultMemoryImpl, Memory};
6use std::{cell::RefCell, rc::Rc};
7
8#[must_use = "call fetch to execute the lookup"]
10pub struct GetMany<'a, E: Entity, M: Memory = DefaultMemoryImpl> {
11 db: QuerySource<'a, M>,
12 keys: Result<Vec<E::Key>, Error>,
13}
14
15#[must_use = "call fetch to execute the lookup"]
17pub struct SelectedGetMany<'a, E: Entity, S, M: Memory = DefaultMemoryImpl> {
18 lookup: GetMany<'a, E, M>,
19 selection: S,
20}
21
22impl<M: Memory> Database<M> {
23 pub fn get_many<E: Entity>(&self, keys: &[impl Copy + Into<Id<E>>]) -> GetMany<'_, E, M> {
33 GetMany::new(QuerySource::Direct(self), keys)
34 }
35}
36
37impl<'a, E: Entity, M: Memory> GetMany<'a, E, M> {
38 fn new(db: QuerySource<'a, M>, keys: &[impl Copy + Into<Id<E>>]) -> Self {
39 let keys = if keys.len() <= u32::BITS as usize {
40 Ok(keys.iter().map(|&key| key.into().key()).collect())
41 } else {
42 Err(Error::Limit)
43 };
44 Self { db, keys }
45 }
46
47 pub(crate) fn from_session(
48 db: Rc<RefCell<Database<M>>>,
49 keys: &[impl Copy + Into<Id<E>>],
50 ) -> Self {
51 Self::new(QuerySource::Session(db), keys)
52 }
53
54 pub fn fetch(self) -> Result<Vec<Option<E>>, Error> {
58 self.fetch_with(|_, key, bytes| super::super::decode_primary::<E>(bytes, key))
59 }
60
61 pub fn select<S: Selection<E>>(
63 self,
64 fields: impl FnOnce(E::Columns) -> S,
65 ) -> SelectedGetMany<'a, E, S, M>
66 where
67 E: SelectColumns,
68 {
69 SelectedGetMany {
70 lookup: self,
71 selection: fields(E::COLUMNS),
72 }
73 }
74
75 fn fetch_with<R>(
76 self,
77 decode: impl Fn(&EntitySchema, E::Key, &[u8]) -> Result<R, Error>,
78 ) -> Result<Vec<Option<R>>, Error> {
79 let db = self.db.read()?;
80 let keys = self.keys?;
81 let entity = db.schema.admits(E::SCHEMA)?;
82 db.get_many_typed(entity, &keys, decode)
83 }
84}
85
86impl<E: SelectColumns, S: Selection<E>, M: Memory> SelectedGetMany<'_, E, S, M> {
87 pub fn fetch(self) -> Result<Vec<Option<S::Output>>, Error> {
91 let selection = self.selection;
92 let positions = selection.positions();
93 let positions = positions.as_ref();
94 Projection::Columns(positions).mask(E::SCHEMA)?;
95 let primary = E::SCHEMA.primary_position().ok_or(Error::Corrupt)?;
96 self.lookup.fetch_with(|entity, key, bytes| {
97 let mut spans = [(0, 0); crate::schema::MAX_FIELDS];
98 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
99 entity.inspect_fields(bytes, 1 << primary, &mut values, Some(&mut spans))?;
100 if RowKey::from_index(values[primary])? != key.into_row_key() {
101 return Err(Error::Corrupt);
102 }
103 selection.decode_spans(bytes, &spans)
104 })
105 }
106}