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/// A session that can start a fluent query for `E`. Generic read helpers can
66/// accept either a store session or the session for the entity's canister.
67pub trait QuerySession<E: Entity> {
68 /// Build a live query. The builder owns the selected store handle.
69 fn entity_query<'a>(&self) -> Query<'a, E>;
70}
71
72impl<E: Entity> QuerySession<E> for DatabaseSession {
73 fn entity_query<'a>(&self) -> Query<'a, E> {
74 self.query()
75 }
76}
77
78/// A cloneable handle to one attached database and its existing storage lease.
79/// The host attaches once using [`Self::new`] and hands each caller a clone.
80/// Cloning takes no database borrow and performs no storage access.
81///
82/// Use a handle within one synchronous message execution. Drop explicit read
83/// guards before writing. Reacquire a handle from the host after an `await`. A handle supplies neither a snapshot nor a transaction
84/// spanning calls. Each batch uses the ordinary enclosing-message commit rules.
85///
86/// Each `insert`, `replace` or `delete` commits a separate batch in the
87/// enclosing message. Submit dependent changes together:
88/// ```
89/// # use ic_db::{Batch, DatabaseSession, Entity, Error};
90/// # fn change_together<E: Entity>(session: &DatabaseSession, first: &E, second: &E) -> Result<(), Error> {
91/// let mut batch = Batch::new();
92/// batch.replace(first)?;
93/// batch.replace(second)?;
94/// session.commit(batch)?;
95/// # Ok(()) }
96/// ```
97///
98/// Engine work and output limits apply to each query. Cloning creates no budget.
99/// Hosts enforcing a cumulative request allowance must share the same allowance
100/// across helpers in that request and establish a fresh one at the next boundary.
101#[derive(Clone)]
102pub struct DatabaseSession(Rc<RefCell<Database>>);
103
104impl DatabaseSession {
105 /// Wrap an already-created or reopened database. Its allocation remains
106 /// leased until the last handle is dropped.
107 #[must_use]
108 pub fn new(database: Database) -> Self {
109 Self(Rc::new(RefCell::new(database)))
110 }
111
112 /// Recover the attached database for a lifecycle operation requiring ownership.
113 /// # Errors
114 /// Returns this same handle if another handle still owns the attachment.
115 pub fn try_into_database(self) -> Result<Database, Self> {
116 Rc::try_unwrap(self.0)
117 .map(RefCell::into_inner)
118 .map_err(Self)
119 }
120
121 /// Borrow the database for fluent queries or a sequence of synchronous reads.
122 /// A builder from `read.query::<E>()` borrows this guard. Commits can resume
123 /// after the guard is dropped, even if several session handles still exist.
124 ///
125 /// # Errors
126 /// Returns [`Error::BorrowConflict`] if a commit has exclusive access.
127 pub fn read(&self) -> Result<Ref<'_, Database>, Error> {
128 self.0.try_borrow().map_err(|_| Error::BorrowConflict)
129 }
130
131 /// Build a live query over this attachment. Execution sees writes committed
132 /// before the terminal call. An exclusive borrow at execution returns
133 /// [`Error::BorrowConflict`]. The builder owns a session handle and borrows
134 /// only its predicate and cursor inputs.
135 #[must_use]
136 pub fn query<'a, E: Entity>(&self) -> Query<'a, E> {
137 Query::from_session(self.0.clone())
138 }
139
140 /// Read an owned entity by primary key, releasing the borrow before returning.
141 ///
142 /// # Errors
143 /// Returns a borrow conflict or the original [`Database::get`] error.
144 pub fn get<E: Entity>(&self, key: E::Key) -> Result<Option<E>, Error> {
145 self.read()?.get::<E>(key)
146 }
147
148 /// Read up to 32 primary keys in input order, preserving duplicates and missing slots.
149 /// # Errors
150 /// Returns a borrow conflict or the original [`Database::get_many`] error.
151 pub fn get_many<E: Entity>(&self, keys: &[E::Key]) -> Result<Vec<Option<E>>, Error> {
152 self.read()?.get_many::<E>(keys)
153 }
154
155 /// Look up an owned row using a generated unique key, such as
156 /// `UserByIssuerAndSubject { issuer, subject }`.
157 /// # Errors
158 /// Propagates session borrow, schema, key admission and row integrity errors.
159 pub fn get_unique<K: UniqueKey>(&self, key: &K) -> Result<Option<K::Entity>, Error> {
160 let components = key.components();
161 let values = components.as_ref();
162 if !K::Entity::SCHEMA
163 .index_by_name(K::INDEX)
164 .is_some_and(|index| index.is_unique_lookup(values.len()))
165 {
166 return Err(Error::InvalidQuery);
167 }
168
169 self.read()?
170 .query::<K::Entity>()
171 .using_index(K::INDEX, values)
172 .work_limit(1)
173 .try_one()
174 }
175
176 /// Insert one entity as one batch.
177 /// # Errors
178 /// Propagates batch preparation and commit errors.
179 pub fn insert<E: Entity>(&self, row: &E) -> Result<(), Error> {
180 let mut batch = Batch::new();
181 batch.insert(row)?;
182
183 self.commit(batch)
184 }
185
186 /// Insert one generated input, applying its schema defaults. Returns the row
187 /// after commit succeeds. For managed timestamps use [`Batch::at`].
188 /// # Errors
189 /// Propagates input preparation and commit errors.
190 pub fn insert_input<I: InsertInput>(&self, input: I) -> Result<I::Entity, Error> {
191 let mut batch = Batch::new();
192 let row = batch.insert_input(input)?;
193 self.commit(batch)?;
194
195 Ok(row)
196 }
197
198 /// Replace one existing entity as one batch.
199 /// # Errors
200 /// Propagates batch preparation and commit errors.
201 pub fn replace<E: Entity>(&self, row: &E) -> Result<(), Error> {
202 let mut batch = Batch::new();
203 batch.replace(row)?;
204
205 self.commit(batch)
206 }
207
208 /// Delete one entity by primary key as one batch.
209 /// # Errors
210 /// Propagates batch preparation and commit errors.
211 pub fn delete<E: Entity>(&self, key: E::Key) -> Result<(), Error> {
212 let mut batch = Batch::new();
213 batch.delete::<E>(key)?;
214
215 self.commit(batch)
216 }
217
218 /// Commit one batch through the attached database.
219 ///
220 /// # Errors
221 /// Returns [`Error::BorrowConflict`] before mutation if a borrow is active,
222 /// or the original [`Database::commit`] error.
223 pub fn commit(&self, batch: Batch) -> Result<(), Error> {
224 self.0
225 .try_borrow_mut()
226 .map_err(|_| Error::BorrowConflict)?
227 .commit(batch)
228 }
229}