libsql/
transaction.rs

1use std::ops::Deref;
2
3use crate::Result;
4
5use super::Connection;
6
7/// Transaction types that correlate to sqlite3 transactions and
8/// additional ones introduced by libsql.
9#[derive(Debug)]
10pub enum TransactionBehavior {
11    Deferred,
12    Immediate,
13    Exclusive,
14    ReadOnly,
15}
16
17/// A transaction on some connection.
18pub struct Transaction {
19    pub(crate) inner: Box<dyn Tx + Send + Sync>,
20    pub(crate) conn: Connection,
21    /// An optional action executed whenever a transaction needs to be dropped.
22    pub(crate) close: Option<Box<dyn FnOnce() + Send + Sync + 'static>>,
23}
24
25impl Transaction {
26    /// Consume this transaction and commit.
27    pub async fn commit(mut self) -> Result<()> {
28        self.inner.commit().await
29    }
30
31    /// Consume this transaction and rollback.
32    pub async fn rollback(mut self) -> Result<()> {
33        self.inner.rollback().await
34    }
35}
36
37impl Deref for Transaction {
38    type Target = Connection;
39
40    #[inline]
41    fn deref(&self) -> &Connection {
42        &self.conn
43    }
44}
45
46impl Drop for Transaction {
47    fn drop(&mut self) {
48        if let Some(close) = self.close.take() {
49            close();
50        }
51    }
52}
53
54#[async_trait::async_trait]
55pub(crate) trait Tx {
56    async fn commit(&mut self) -> Result<()>;
57    async fn rollback(&mut self) -> Result<()>;
58}