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