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
//! `Transaction` is a structure representing an interactive transaction.

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

pub struct Transaction<'a, Client: DatabaseClient + ?Sized> {
    client: &'a Client,
}

impl<'a, Client: DatabaseClient + ?Sized> Transaction<'a, Client> {
    /// Creates a new transaction.
    pub async fn new(client: &'a Client) -> Result<Transaction<'a, Client>> {
        client.raw_batch(vec![Statement::new("BEGIN")]).await?;
        Ok(Self { 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(stmt.into()).await
    }

    /// Commits the transaction to the database.
    pub async fn commit(self) -> Result<()> {
        self.client.execute("COMMIT").await?;
        Ok(())
    }

    /// Rolls back the transaction, cancelling any of its side-effects.
    pub async fn rollback(self) -> Result<()> {
        self.client.execute("ROLLBACK").await?;
        Ok(())
    }
}