Skip to main content

ic_db/
canister_session.rs

1//! Route typed operations to the single-store session admitted by the host.
2
3use crate::{
4    Batch, CompiledCanister, CompiledStore, DatabaseSession, Entity, Error, InsertInput, Query,
5    QuerySession, Store, UniqueKey,
6};
7use std::{marker::PhantomData, rc::Rc};
8
9/// Implemented by schema assembly for stores in a compiled canister roster.
10#[doc(hidden)]
11pub trait MountedStore: Store {
12    /// Executable-local position in the owner's roster.
13    const SLOT: usize;
14}
15
16/// All store sessions for one declared canister. Clones share the same leases.
17pub struct CanisterSession<C> {
18    stores: Rc<[DatabaseSession]>,
19    owner: PhantomData<fn() -> C>,
20}
21
22impl<C> Clone for CanisterSession<C> {
23    fn clone(&self) -> Self {
24        Self {
25            stores: self.stores.clone(),
26            owner: PhantomData,
27        }
28    }
29}
30
31impl<C: CompiledCanister> CanisterSession<C> {
32    /// Attach every store once, in compiled roster order. The host must acquire
33    /// the lease named by each descriptor's key and create or reopen it with
34    /// that descriptor's schema. A failed attachment drops collected handles.
35    /// A host creating stores must trap its lifecycle message on failure to
36    /// roll back any preceding creates.
37    ///
38    /// # Errors
39    /// Returns the first host error without exposing a partially attached session.
40    pub fn try_attach<F>(
41        attach: impl FnMut(&CompiledStore) -> Result<DatabaseSession, F>,
42    ) -> Result<Self, F> {
43        let stores = C::STORES
44            .iter()
45            .map(attach)
46            .collect::<Result<Rc<[_]>, _>>()?;
47        Ok(Self {
48            stores,
49            owner: PhantomData,
50        })
51    }
52
53    fn session<S: MountedStore<Canister = C>>(&self) -> &DatabaseSession {
54        &self.stores[S::SLOT]
55    }
56
57    /// Prepare dependent changes in one store, inferred from the entities added.
58    #[must_use]
59    pub fn batch<S: MountedStore<Canister = C>>(&self) -> StoreBatch<'_, S> {
60        StoreBatch {
61            session: self.session::<S>(),
62            batch: Batch::new(),
63            store: PhantomData,
64        }
65    }
66
67    /// Build a live query in the entity's declared store.
68    #[must_use]
69    pub fn query<'a, E: Entity<Store: MountedStore<Canister = C>>>(&self) -> Query<'a, E> {
70        self.session::<E::Store>().query()
71    }
72
73    /// Read an entity by its primary key.
74    /// # Errors
75    /// Propagates the owning store's lookup errors.
76    pub fn get<E: Entity<Store: MountedStore<Canister = C>>>(
77        &self,
78        key: impl Into<crate::Id<E>>,
79    ) -> Result<Option<E>, Error> {
80        self.session::<E::Store>().get::<E>(key)
81    }
82
83    /// Read up to 32 primary keys in input order, preserving duplicates and missing slots.
84    /// # Errors
85    /// Propagates the owning store session’s lookup and limit errors.
86    pub fn get_many<E: Entity<Store: MountedStore<Canister = C>>>(
87        &self,
88        keys: &[E::Key],
89    ) -> Result<Vec<Option<E>>, Error> {
90        self.session::<E::Store>().get_many::<E>(keys)
91    }
92
93    /// Read an entity using its generated unique key.
94    /// # Errors
95    /// Propagates the owning store's unique lookup errors.
96    pub fn get_unique<K: UniqueKey<Entity: Entity<Store: MountedStore<Canister = C>>>>(
97        &self,
98        key: &K,
99    ) -> Result<Option<K::Entity>, Error> {
100        self.session::<<K::Entity as Entity>::Store>()
101            .get_unique(key)
102    }
103
104    /// Insert one row in its declared store.
105    /// # Errors
106    /// Propagates batch preparation and commit errors.
107    pub fn insert<E: Entity<Store: MountedStore<Canister = C>>>(
108        &self,
109        row: &E,
110    ) -> Result<(), Error> {
111        self.session::<E::Store>().insert(row)
112    }
113
114    /// Insert one generated input in its declared store and return the committed row.
115    /// Managed fields receive the current operation time.
116    /// # Errors
117    /// Propagates [`DatabaseSession::insert_input`] preparation and commit errors.
118    pub fn insert_input<I: InsertInput<Entity: Entity<Store: MountedStore<Canister = C>>>>(
119        &self,
120        input: I,
121    ) -> Result<I::Entity, Error> {
122        self.session::<<I::Entity as Entity>::Store>()
123            .insert_input(input)
124    }
125
126    /// Replace one row in its declared store and return the stored value.
127    /// # Errors
128    /// Propagates batch preparation and commit errors.
129    pub fn replace<E: Entity<Store: MountedStore<Canister = C>>>(
130        &self,
131        row: &E,
132    ) -> Result<E, Error> {
133        self.session::<E::Store>().replace(row)
134    }
135
136    /// Delete one row from its declared store by primary key.
137    /// # Errors
138    /// Propagates batch preparation and commit errors.
139    pub fn delete<E: Entity<Store: MountedStore<Canister = C>>>(
140        &self,
141        key: impl Into<crate::Id<E>>,
142    ) -> Result<(), Error> {
143        self.session::<E::Store>().delete::<E>(key)
144    }
145}
146
147impl<C: CompiledCanister, E: Entity<Store: MountedStore<Canister = C>>> QuerySession<E>
148    for CanisterSession<C>
149{
150    fn entity_query<'a>(&self) -> Query<'a, E> {
151        self.query()
152    }
153}
154
155/// A synchronous batch bound to one mounted store. Dropping it discards its prepared changes.
156pub struct StoreBatch<'a, S: Store> {
157    session: &'a DatabaseSession,
158    batch: Batch,
159    store: PhantomData<fn() -> S>,
160}
161
162impl<S: Store> StoreBatch<'_, S> {
163    /// Queue an insertion in this store.
164    /// # Errors
165    /// Propagates [`Batch::insert`] admission errors.
166    pub fn insert<E: Entity<Store = S>>(&mut self, row: &E) -> Result<(), Error> {
167        self.batch.insert(row)
168    }
169
170    /// Queue an insertion using the entity's generated input and return the prepared row.
171    /// # Errors
172    /// Propagates [`Batch::insert_input`] admission errors.
173    pub fn insert_input<I: InsertInput<Entity: Entity<Store = S>>>(
174        &mut self,
175        input: I,
176    ) -> Result<I::Entity, Error> {
177        self.batch.insert_input(input)
178    }
179
180    /// Queue a replacement in this store.
181    /// # Errors
182    /// Propagates [`Batch::replace`] admission errors.
183    pub fn replace<E: Entity<Store = S>>(&mut self, row: &E) -> Result<(), Error> {
184        self.batch.replace(row)
185    }
186
187    /// Queue a deletion in this store.
188    /// # Errors
189    /// Propagates [`Batch::delete`] admission errors.
190    pub fn delete<E: Entity<Store = S>>(
191        &mut self,
192        key: impl Into<crate::Id<E>>,
193    ) -> Result<(), Error> {
194        self.batch.delete::<E>(key)
195    }
196
197    /// Apply the prepared changes through the owning store session.
198    /// # Errors
199    /// Propagates [`DatabaseSession::commit`] borrow and commit errors.
200    pub fn commit(self) -> Result<(), Error> {
201        self.session.commit(self.batch)
202    }
203}