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};
6use std::{cell::RefCell, rc::Rc};
7
8/// A bulk lookup that reads whole rows by default. Call `select` for individual columns.
9#[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/// A bulk lookup with selected result columns in caller order.
16#[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    /// Build a lookup for up to 32 raw primary keys or entity-typed IDs, returning one slot per input position.
24    /// Each distinct key is looked up once. Missing keys yield `None`; repeats have independent output slots.
25    /// An empty slice needs an element type, e.g. `&[] as &[u64]` for a Nat64 key.
26    /// ```compile_fail
27    /// use ic_db::{Database, Entity, Id};
28    /// fn wrong<A: Entity, B: Entity<Key = A::Key>>(db: &Database, ids: &[Id<A>]) {
29    ///     let _ = db.get_many::<B>(ids);
30    /// }
31    /// ```
32    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    /// Read the entity at each supplied key. Unknown keys yield `None`.
55    /// # Errors
56    /// More than 32 positions return `Limit`. Borrow, schema and row validation errors propagate.
57    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    /// Select a field or tuple using the same field handles as a fluent query.
62    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    /// Read the selected columns at each supplied key.
88    /// # Errors
89    /// Repeated columns return `InvalidQuery`. Ordinary bulk lookup errors apply.
90    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}