1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//! `Transaction` is a structure representing an interactive transaction.

use crate::{DatabaseClient, ResultSet, Statement};
use anyhow::Result;

pub struct Transaction<'a, Client: DatabaseClient + ?Sized> {
    pub(crate) id: u64,
    pub(crate) client: &'a Client,
}

impl<'a, Client: DatabaseClient + ?Sized> Transaction<'a, Client> {
    pub async fn new(client: &'a Client, id: u64) -> Result<Transaction<'a, Client>> {
        client
            .execute_in_transaction(id, Statement::from("BEGIN"))
            .await?;
        Ok(Self { id, client })
    }

    /// Executes a statement within the current transaction.
    /// # Example
    ///
    /// ```rust,no_run
    ///   # async fn f() -> anyhow::Result<()> {
    ///   # use crate::libsql_client::{DatabaseClient, Statement, args};
    ///   let mut db = libsql_client::new_client().await?;
    ///   let tx = db.transaction().await?;
    ///   tx.execute(Statement::with_args("INSERT INTO users (name) VALUES (?)", args!["John"])).await?;
    ///   let res = tx.execute(Statement::with_args("INSERT INTO users (name) VALUES (?)", args!["Jane"])).await;
    ///   if res.is_err() {
    ///     tx.rollback().await?;
    ///   } else {
    ///     tx.commit().await?;
    ///   }
    ///   # Ok(())
    ///   # }
    /// ```
    pub async fn execute(&self, stmt: impl Into<Statement>) -> Result<ResultSet> {
        self.client
            .execute_in_transaction(self.id, stmt.into())
            .await
    }

    /// Commits the transaction to the database.
    pub async fn commit(self) -> Result<()> {
        self.client.commit_transaction(self.id).await
    }

    /// Rolls back the transaction, cancelling any of its side-effects.
    pub async fn rollback(self) -> Result<()> {
        self.client.rollback_transaction(self.id).await
    }
}