ic_db/session.rs
1//! Synchronous access to a database attached by the host.
2
3use crate::{Batch, Database, Entity, Error, IndexValue, InsertInput, Query};
4use std::{
5 cell::{Ref, RefCell},
6 rc::Rc,
7};
8
9/// Named lookup components generated for a declared unique index.
10///
11/// All declared components are required.
12/// ```compile_fail,E0063
13/// # use ic_db::design::prelude::*;
14/// # use ic_db::DatabaseSession;
15/// # #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(fields=["issuer","subject"], unique), fields(
16/// # field(name="id", value(item(prim="Nat64"))), field(name="issuer", value(item(prim="Nat64"))),
17/// # field(name="subject", value(item(prim="Nat64")))))]
18/// # struct User {}
19/// let _ = UserByIssuerAndSubject { issuer: 1 };
20/// ```
21///
22/// Component types are exact.
23/// ```compile_fail,E0308
24/// # use ic_db::design::prelude::*;
25/// # use ic_db::DatabaseSession;
26/// # #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(fields=["issuer","subject"], unique), fields(
27/// # field(name="id", value(item(prim="Nat64"))), field(name="issuer", value(item(prim="Nat64"))),
28/// # field(name="subject", value(item(prim="Nat64")))))]
29/// # struct User {}
30/// let _ = UserByIssuerAndSubject { issuer: true, subject: 1 };
31/// ```
32///
33/// The key determines the result entity.
34/// ```compile_fail,E0308
35/// # use ic_db::design::prelude::*;
36/// # use ic_db::DatabaseSession;
37/// # #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(fields=["issuer","subject"], unique), fields(
38/// # field(name="id", value(item(prim="Nat64"))), field(name="issuer", value(item(prim="Nat64"))),
39/// # field(name="subject", value(item(prim="Nat64")))))]
40/// # struct User {}
41/// fn wrong(db: &DatabaseSession) -> Option<u64> {
42/// db.get_unique(&UserByIssuerAndSubject { issuer: 1, subject: 2 }).unwrap()
43/// }
44/// ```
45///
46/// Only unique indexes generate keys.
47/// ```compile_fail,E0422
48/// # use ic_db::design::prelude::*;
49/// # #[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(field="owner"), fields(
50/// # field(name="id", value(item(prim="Nat64"))), field(name="owner", value(item(prim="Nat64")))))]
51/// # struct User {}
52/// let _ = UserByOwner { owner: 1 };
53/// ```
54pub trait UniqueKey {
55 /// Entity owning the index.
56 type Entity: Entity;
57 /// Logical name of the declared unique index.
58 #[doc(hidden)]
59 const INDEX: &'static str;
60 /// Present components in declared index order.
61 #[doc(hidden)]
62 fn components(&self) -> impl AsRef<[IndexValue<'_>]>;
63}
64
65/// Result of inserting one input conditionally on its declared unique index.
66#[derive(Debug, PartialEq, Eq)]
67pub enum InsertOutcome<E> {
68 /// The input was inserted, including any generated ID and managed timestamps.
69 Inserted(E),
70 /// An existing row owns the selected key. No row was changed.
71 AlreadyPresent,
72}
73
74/// A session that can start a fluent query for `E`. Generic read helpers can
75/// accept either a store session or the session for the entity's canister.
76pub trait QuerySession<E: Entity> {
77 /// Build a live query. The builder owns the selected store handle.
78 fn entity_query<'a>(&self) -> Query<'a, E>;
79}
80
81impl<E: Entity> QuerySession<E> for DatabaseSession {
82 fn entity_query<'a>(&self) -> Query<'a, E> {
83 self.query()
84 }
85}
86
87/// A cloneable handle to one attached database and its existing storage lease.
88/// The host attaches once using [`Self::new`] and hands each caller a clone.
89/// Cloning takes no database borrow and performs no storage access.
90///
91/// Use a handle within one synchronous message execution. Drop explicit read
92/// guards before writing. Reacquire a handle from the host after an `await`. A handle supplies neither a snapshot nor a transaction
93/// spanning calls. Each batch uses the ordinary enclosing-message commit rules.
94///
95/// Each `insert`, `replace` or `delete` commits a separate batch in the
96/// enclosing message. Submit dependent changes together:
97/// ```
98/// # use ic_db::{Batch, DatabaseSession, Entity, Error};
99/// # fn change_together<E: Entity>(session: &DatabaseSession, first: &E, second: &E) -> Result<(), Error> {
100/// let mut batch = Batch::new();
101/// batch.replace(first)?;
102/// batch.replace(second)?;
103/// session.commit(batch)?;
104/// # Ok(()) }
105/// ```
106///
107/// Engine work and output limits apply to each query. Cloning creates no budget.
108/// Hosts enforcing a cumulative request allowance must share the same allowance
109/// across helpers in that request and establish a fresh one at the next boundary.
110#[derive(Clone)]
111pub struct DatabaseSession(Rc<RefCell<Database>>);
112
113impl DatabaseSession {
114 /// Wrap an already-created or reopened database. Its allocation remains
115 /// leased until the last handle is dropped.
116 #[must_use]
117 pub fn new(database: Database) -> Self {
118 Self(Rc::new(RefCell::new(database)))
119 }
120
121 /// Recover the attached database for a lifecycle operation requiring ownership.
122 /// # Errors
123 /// Returns this same handle if another handle still owns the attachment.
124 pub fn try_into_database(self) -> Result<Database, Self> {
125 Rc::try_unwrap(self.0)
126 .map(RefCell::into_inner)
127 .map_err(Self)
128 }
129
130 /// Borrow the database for fluent queries or a sequence of synchronous reads.
131 /// A builder from `read.query::<E>()` borrows this guard. Commits can resume
132 /// after the guard is dropped, even if several session handles still exist.
133 ///
134 /// # Errors
135 /// Returns [`Error::BorrowConflict`] if a commit has exclusive access.
136 pub fn read(&self) -> Result<Ref<'_, Database>, Error> {
137 self.0.try_borrow().map_err(|_| Error::BorrowConflict)
138 }
139
140 /// Build a live query over this attachment. Execution sees writes committed
141 /// before the terminal call. An exclusive borrow at execution returns
142 /// [`Error::BorrowConflict`]. The builder owns a session handle and borrows
143 /// only its predicate and cursor inputs.
144 #[must_use]
145 pub fn query<'a, E: Entity>(&self) -> Query<'a, E> {
146 Query::from_session(self.0.clone())
147 }
148
149 /// Read an owned entity by primary key, releasing the borrow before returning.
150 ///
151 /// # Errors
152 /// Returns a borrow conflict or the original [`Database::get`] error.
153 pub fn get<E: Entity>(&self, key: impl Into<crate::Id<E>>) -> Result<Option<E>, Error> {
154 self.read()?.get::<E>(key)
155 }
156
157 /// Build a live bulk lookup in the entity's store. The read borrow starts at `fetch`.
158 pub fn get_many<E: Entity>(
159 &self,
160 keys: &[impl Copy + Into<crate::Id<E>>],
161 ) -> crate::GetMany<'static, E> {
162 crate::GetMany::from_session(self.0.clone(), keys)
163 }
164
165 /// Look up an owned row using a generated unique key, such as
166 /// `UserByIssuerAndSubject { issuer, subject }`.
167 /// # Errors
168 /// Propagates session borrow, schema, key admission and row integrity errors.
169 pub fn get_unique<K: UniqueKey>(&self, key: &K) -> Result<Option<K::Entity>, Error> {
170 self.read()?.get_unique(key)
171 }
172
173 /// Insert one entity as one batch.
174 /// # Errors
175 /// Propagates batch preparation and commit errors.
176 pub fn insert<E: Entity>(&self, row: &E) -> Result<(), Error> {
177 let mut batch = Batch::new();
178 batch.insert(row)?;
179
180 self.commit(batch)
181 }
182
183 /// Insert one generated input, applying its schema defaults. Returns the row
184 /// after commit succeeds. Managed fields receive the current operation time.
185 /// # Errors
186 /// Propagates input preparation and commit errors.
187 pub fn insert_input<I: InsertInput>(&self, input: I) -> Result<I::Entity, Error> {
188 let mut batch = Batch::new();
189 let row = batch.insert_input(input)?;
190 self.commit(batch)?;
191
192 Ok(row)
193 }
194
195 /// Insert unless the input's selected unique key already has an owner.
196 /// Select the index by its generated key type. Components come from the input.
197 /// An absent sparse key participates in no conflict.
198 /// # Errors
199 /// Propagates invalid input, primary-key and other unique conflicts, reference,
200 /// storage and borrow errors, including on replay.
201 pub fn insert_if_absent<K: UniqueKey>(
202 &self,
203 input: impl InsertInput<Entity = K::Entity>,
204 ) -> Result<InsertOutcome<K::Entity>, Error> {
205 self.0
206 .try_borrow_mut()
207 .map_err(|_| Error::BorrowConflict)?
208 .insert_if_absent::<K>(input)
209 }
210
211 /// Replace one existing entity and return its stored value including any assigned update time.
212 /// # Errors
213 /// Propagates batch preparation and commit errors.
214 /// # Panics
215 /// Traps on a supplier write failure during publication.
216 pub fn replace<E: Entity>(&self, row: &E) -> Result<E, Error> {
217 let mut batch = Batch::new();
218 batch.replace(row)?;
219 self.commit_returning(batch, row.id())
220 }
221
222 /// Insert or replace by primary key and return the stored row with managed times.
223 /// # Errors
224 /// Propagates borrow, preparation and commit errors.
225 pub fn upsert<E: Entity>(&self, row: &E) -> Result<E, Error> {
226 self.0
227 .try_borrow_mut()
228 .map_err(|_| Error::BorrowConflict)?
229 .upsert(row)
230 }
231
232 /// Delete one entity by primary key as one batch.
233 /// # Errors
234 /// Propagates batch preparation and commit errors.
235 pub fn delete<E: Entity>(&self, key: impl Into<crate::Id<E>>) -> Result<(), Error> {
236 let mut batch = Batch::new();
237 batch.delete::<E>(key)?;
238
239 self.commit(batch)
240 }
241
242 /// Commit one batch through the attached database.
243 ///
244 /// # Errors
245 /// Returns [`Error::BorrowConflict`] before mutation if a borrow is active,
246 /// or the original [`Database::commit`] error.
247 pub fn commit(&self, batch: Batch) -> Result<(), Error> {
248 self.0
249 .try_borrow_mut()
250 .map_err(|_| Error::BorrowConflict)?
251 .commit(batch)
252 }
253
254 /// Commit the batch and return one queued insert or replacement by entity and key.
255 /// # Errors
256 /// Returns [`Error::BorrowConflict`] on an active borrow and propagates
257 /// [`Database::commit_returning`] errors.
258 pub fn commit_returning<E: Entity>(
259 &self,
260 batch: Batch,
261 key: impl Into<crate::Id<E>>,
262 ) -> Result<E, Error> {
263 self.0
264 .try_borrow_mut()
265 .map_err(|_| Error::BorrowConflict)?
266 .commit_returning(batch, key)
267 }
268}