Skip to main content

ic_db/
session.rs

1//! Synchronous access to a database attached by the host.
2use crate::{Batch, Database, Entity, Error};
3use std::{
4    cell::{Ref, RefCell},
5    rc::Rc,
6};
7
8/// A cloneable handle to one attached database and its existing storage lease.
9/// The host attaches once using [`Self::new`] and hands each caller a clone.
10/// Cloning takes no database borrow and performs no storage access.
11///
12/// Use a handle within one synchronous message execution. Drop read guards and
13/// query builders before a write or an `await`, and reacquire a handle from the
14/// host in a callback. A handle supplies neither a snapshot nor a transaction
15/// spanning calls. Each batch uses the ordinary enclosing-message commit rules.
16///
17/// Engine work and output limits apply to each query. Cloning creates no budget.
18/// Hosts enforcing a cumulative request allowance must share the same allowance
19/// across helpers in that request and establish a fresh one at the next boundary.
20#[derive(Clone)]
21pub struct DatabaseSession(Rc<RefCell<Database>>);
22
23impl DatabaseSession {
24    /// Wrap an already-created or reopened database. Its allocation remains
25    /// leased until the last handle is dropped.
26    #[must_use]
27    pub fn new(database: Database) -> Self {
28        Self(Rc::new(RefCell::new(database)))
29    }
30
31    /// Recover the attached database for a lifecycle operation requiring ownership.
32    /// # Errors
33    /// Returns this same handle if another handle still owns the attachment.
34    pub fn try_into_database(self) -> Result<Database, Self> {
35        Rc::try_unwrap(self.0)
36            .map(RefCell::into_inner)
37            .map_err(Self)
38    }
39
40    /// Borrow the database for fluent queries or a sequence of synchronous reads.
41    /// A builder from `read.query::<E>()` borrows this guard. Commits can resume
42    /// after the guard is dropped, even if several session handles still exist.
43    ///
44    /// # Errors
45    /// Returns [`Error::BorrowConflict`] if a commit has exclusive access.
46    pub fn read(&self) -> Result<Ref<'_, Database>, Error> {
47        self.0.try_borrow().map_err(|_| Error::BorrowConflict)
48    }
49
50    /// Read an owned entity by primary key, releasing the borrow before returning.
51    ///
52    /// # Errors
53    /// Returns a borrow conflict or the original [`Database::get`] error.
54    pub fn get<E: Entity>(&self, key: E::Key) -> Result<Option<E>, Error> {
55        self.read()?.get::<E>(key)
56    }
57
58    /// Commit one batch through the attached database.
59    ///
60    /// # Errors
61    /// Returns [`Error::BorrowConflict`] before mutation if a borrow is active,
62    /// or the original [`Database::commit`] error.
63    pub fn commit(&self, batch: Batch) -> Result<(), Error> {
64        self.0
65            .try_borrow_mut()
66            .map_err(|_| Error::BorrowConflict)?
67            .commit(batch)
68    }
69}