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    /// Build a live bulk lookup in the entity's store. The read borrow starts at `fetch`.
84    pub fn get_many<E: Entity<Store: MountedStore<Canister = C>>>(
85        &self,
86        keys: &[impl Copy + Into<crate::Id<E>>],
87    ) -> crate::GetMany<'static, E> {
88        self.session::<E::Store>().get_many::<E>(keys)
89    }
90
91    /// Read an entity using its generated unique key.
92    /// # Errors
93    /// Propagates the owning store's unique lookup errors.
94    pub fn get_unique<K: UniqueKey<Entity: Entity<Store: MountedStore<Canister = C>>>>(
95        &self,
96        key: &K,
97    ) -> Result<Option<K::Entity>, Error> {
98        self.session::<<K::Entity as Entity>::Store>()
99            .get_unique(key)
100    }
101
102    /// Insert one row in its declared store.
103    /// # Errors
104    /// Propagates batch preparation and commit errors.
105    pub fn insert<E: Entity<Store: MountedStore<Canister = C>>>(
106        &self,
107        row: &E,
108    ) -> Result<(), Error> {
109        self.session::<E::Store>().insert(row)
110    }
111
112    /// Insert one generated input in its declared store and return the committed row.
113    /// Managed fields receive the current operation time.
114    /// # Errors
115    /// Propagates [`DatabaseSession::insert_input`] preparation and commit errors.
116    pub fn insert_input<I: InsertInput<Entity: Entity<Store: MountedStore<Canister = C>>>>(
117        &self,
118        input: I,
119    ) -> Result<I::Entity, Error> {
120        self.session::<<I::Entity as Entity>::Store>()
121            .insert_input(input)
122    }
123
124    /// Insert in the selected unique key's store, preserving its existing owner on replay.
125    /// # Errors
126    /// Propagates the owning session's [conditional insert](DatabaseSession::insert_if_absent) errors.
127    pub fn insert_if_absent<K: UniqueKey<Entity: Entity<Store: MountedStore<Canister = C>>>>(
128        &self,
129        input: impl InsertInput<Entity = K::Entity>,
130    ) -> Result<crate::InsertOutcome<K::Entity>, Error> {
131        self.session::<<K::Entity as Entity>::Store>()
132            .insert_if_absent::<K>(input)
133    }
134
135    /// Replace one row in its declared store and return the stored value.
136    /// # Errors
137    /// Propagates batch preparation and commit errors.
138    pub fn replace<E: Entity<Store: MountedStore<Canister = C>>>(
139        &self,
140        row: &E,
141    ) -> Result<E, Error> {
142        self.session::<E::Store>().replace(row)
143    }
144
145    /// Insert or replace by primary key in the declared store and return the stored row.
146    /// # Errors
147    /// Propagates [`DatabaseSession::upsert`] errors.
148    pub fn upsert<E: Entity<Store: MountedStore<Canister = C>>>(
149        &self,
150        row: &E,
151    ) -> Result<E, Error> {
152        self.session::<E::Store>().upsert(row)
153    }
154
155    /// Delete one row from its declared store by primary key.
156    /// # Errors
157    /// Propagates batch preparation and commit errors.
158    pub fn delete<E: Entity<Store: MountedStore<Canister = C>>>(
159        &self,
160        key: impl Into<crate::Id<E>>,
161    ) -> Result<(), Error> {
162        self.session::<E::Store>().delete::<E>(key)
163    }
164}
165
166impl<C: CompiledCanister, E: Entity<Store: MountedStore<Canister = C>>> QuerySession<E>
167    for CanisterSession<C>
168{
169    fn entity_query<'a>(&self) -> Query<'a, E> {
170        self.query()
171    }
172}
173
174/// A synchronous batch bound to one mounted store. Dropping it discards its prepared changes.
175pub struct StoreBatch<'a, S: Store> {
176    session: &'a DatabaseSession,
177    batch: Batch,
178    store: PhantomData<fn() -> S>,
179}
180
181impl<S: Store> StoreBatch<'_, S> {
182    /// Queue an insertion in this store.
183    /// # Errors
184    /// Propagates [`Batch::insert`] admission errors.
185    pub fn insert<E: Entity<Store = S>>(&mut self, row: &E) -> Result<(), Error> {
186        self.batch.insert(row)
187    }
188
189    /// Queue an insertion using the entity's generated input and return the prepared row.
190    /// # Errors
191    /// Propagates [`Batch::insert_input`] admission errors.
192    pub fn insert_input<I: InsertInput<Entity: Entity<Store = S>>>(
193        &mut self,
194        input: I,
195    ) -> Result<I::Entity, Error> {
196        self.batch.insert_input(input)
197    }
198
199    /// Queue a replacement in this store.
200    /// # Errors
201    /// Propagates [`Batch::replace`] admission errors.
202    pub fn replace<E: Entity<Store = S>>(&mut self, row: &E) -> Result<(), Error> {
203        self.batch.replace(row)
204    }
205
206    /// Queue an insertion or replacement by primary key in this store.
207    /// # Errors
208    /// Propagates [`Batch::upsert`] admission errors.
209    pub fn upsert<E: Entity<Store = S>>(&mut self, row: &E) -> Result<(), Error> {
210        self.batch.upsert(row)
211    }
212
213    /// Queue a deletion in this store.
214    /// # Errors
215    /// Propagates [`Batch::delete`] admission errors.
216    pub fn delete<E: Entity<Store = S>>(
217        &mut self,
218        key: impl Into<crate::Id<E>>,
219    ) -> Result<(), Error> {
220        self.batch.delete::<E>(key)
221    }
222
223    /// Apply the prepared changes through the owning store session.
224    /// # Errors
225    /// Propagates [`DatabaseSession::commit`] borrow and commit errors.
226    pub fn commit(self) -> Result<(), Error> {
227        self.session.commit(self.batch)
228    }
229
230    /// Commit all queued changes and return one inserted or replaced row from this store.
231    /// # Errors
232    /// Propagates [`DatabaseSession::commit_returning`] borrow, selection and commit errors.
233    pub fn commit_returning<E: Entity<Store = S>>(
234        self,
235        key: impl Into<crate::Id<E>>,
236    ) -> Result<E, Error> {
237        self.session.commit_returning(self.batch, key)
238    }
239}