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};
6
7#[must_use = "call fetch to execute the lookup"]
9pub struct GetMany<'a, E: Entity, M: Memory = DefaultMemoryImpl> {
10 db: QuerySource<'a, M>,
11 keys: Result<Vec<E::Key>, Error>,
12}
13
14#[must_use = "call fetch to execute the lookup"]
16pub struct SelectedGetMany<'a, E: Entity, S, M: Memory = DefaultMemoryImpl> {
17 lookup: GetMany<'a, E, M>,
18 selection: S,
19}
20
21impl<M: Memory> Database<M> {
22 pub fn get_many<E: Entity>(&self, keys: &[impl Copy + Into<Id<E>>]) -> GetMany<'_, E, M> {
32 GetMany::new(QuerySource::Direct(self), keys)
33 }
34}
35
36impl<'a, E: Entity, M: Memory> GetMany<'a, E, M> {
37 pub(crate) fn new(db: QuerySource<'a, M>, keys: &[impl Copy + Into<Id<E>>]) -> Self {
38 let keys = if keys.len() <= u32::BITS as usize {
39 Ok(keys.iter().map(|&key| key.into().key()).collect())
40 } else {
41 Err(Error::Limit)
42 };
43 Self { db, keys }
44 }
45
46 pub fn fetch(self) -> Result<Vec<Option<E>>, Error> {
50 self.fetch_with(|_, key, bytes| super::super::decode_primary::<E>(bytes, key))
51 }
52
53 pub fn select<S: Selection<E>>(
55 self,
56 fields: impl FnOnce(E::Columns) -> S,
57 ) -> SelectedGetMany<'a, E, S, M>
58 where
59 E: SelectColumns,
60 {
61 SelectedGetMany {
62 lookup: self,
63 selection: fields(E::COLUMNS),
64 }
65 }
66
67 fn fetch_with<R>(
68 self,
69 decode: impl Fn(&EntitySchema, E::Key, &[u8]) -> Result<R, Error>,
70 ) -> Result<Vec<Option<R>>, Error> {
71 let db = self.db.read()?;
72 let keys = self.keys?;
73 let entity = db.schema.admits(E::SCHEMA)?;
74 db.get_many_typed(entity, &keys, decode)
75 }
76}
77
78impl<E: SelectColumns, S: Selection<E>, M: Memory> SelectedGetMany<'_, E, S, M> {
79 pub fn fetch(self) -> Result<Vec<Option<S::Output>>, Error> {
83 let selection = self.selection;
84 let positions = selection.positions();
85 let positions = positions.as_ref();
86 Projection::Columns(positions).mask(E::SCHEMA)?;
87 let primary = E::SCHEMA.primary_position().ok_or(Error::Corrupt)?;
88 self.lookup.fetch_with(|entity, key, bytes| {
89 let mut spans = [(0, 0); crate::schema::MAX_FIELDS];
90 let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
91 entity.inspect_fields(bytes, 1 << primary, &mut values, Some(&mut spans))?;
92 if RowKey::from_index(values[primary])? != key.into_row_key() {
93 return Err(Error::Corrupt);
94 }
95 selection.decode_spans(bytes, &spans)
96 })
97 }
98}