Skip to main content

ic_db/
session.rs

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