Skip to main content

ic_db/
session.rs

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