Skip to main content

ic_db/store/query/
get_many.rs

1//! Positional primary-key lookups over a live database or session.
2
3use super::{Database, Projection, QuerySource, SelectColumns, Selection};
4use crate::{Entity, EntitySchema, Error, Id, IndexValue, PrimaryKey, primary::RowKey};
5use ic_storage::{DefaultMemoryImpl, Memory};
6
7/// A bulk lookup that reads whole rows by default. Call `select` for individual columns.
8#[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/// A bulk lookup with selected result columns in caller order.
15#[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    /// Build a lookup for up to 32 raw primary keys or entity-typed IDs, returning one slot per input position.
23    /// Each distinct key is looked up once. Missing keys yield `None`; repeats have independent output slots.
24    /// An empty slice needs an element type, e.g. `&[] as &[u64]` for a Nat64 key.
25    /// ```compile_fail
26    /// use ic_db::{Database, Entity, Id};
27    /// fn wrong<A: Entity, B: Entity<Key = A::Key>>(db: &Database, ids: &[Id<A>]) {
28    ///     let _ = db.get_many::<B>(ids);
29    /// }
30    /// ```
31    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    /// Read the entity at each supplied key. Unknown keys yield `None`.
47    /// # Errors
48    /// More than 32 positions return `Limit`. Borrow, schema and row validation errors propagate.
49    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    /// Select a field or tuple using the same field handles as a fluent query.
54    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    /// Read the selected columns at each supplied key.
80    /// # Errors
81    /// Repeated columns return `InvalidQuery`. Ordinary bulk lookup errors apply.
82    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}