rexie/
transaction.rs

1mod index;
2mod store;
3
4pub use self::{index::StoreIndex, store::Store};
5
6use idb::Transaction as IdbTransaction;
7
8use crate::{Error, Result, TransactionMode, TransactionResult};
9
10/// Transaction on the database
11pub struct Transaction {
12    pub(crate) transaction: IdbTransaction,
13}
14
15impl Transaction {
16    /// Returns mode of the transaction
17    pub fn mode(&self) -> Result<TransactionMode> {
18        self.transaction.mode().map_err(Into::into)
19    }
20
21    /// Returns names of all stores in the transaction
22    pub fn store_names(&self) -> Vec<String> {
23        self.transaction.store_names()
24    }
25
26    /// Aborts a transaction
27    pub async fn abort(self) -> Result<()> {
28        let result = self.transaction.abort()?.await?;
29
30        if result.is_aborted() {
31            Ok(())
32        } else {
33            Err(Error::TransactionAbortFailed)
34        }
35    }
36
37    /// Commits a transaction
38    ///
39    /// # Note
40    ///
41    /// Note that `commit()` doesn't normally have to be called — a transaction will automatically commit when all
42    /// outstanding requests have been satisfied and no new requests have been made.
43    ///
44    /// [Reference](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/commit)
45    pub async fn commit(self) -> Result<()> {
46        let result = self.transaction.commit()?.await?;
47
48        if result.is_committed() {
49            Ok(())
50        } else {
51            Err(Error::TransactioncommitFailed)
52        }
53    }
54
55    /// Waits for a transaction to complete.
56    pub async fn done(self) -> Result<TransactionResult> {
57        self.transaction.await.map_err(Into::into)
58    }
59
60    /// Returns a store in the transaction
61    pub fn store(&self, store_name: &str) -> Result<Store> {
62        self.transaction
63            .object_store(store_name)
64            .map(|object_store| Store { object_store })
65            .map_err(Into::into)
66    }
67}