Skip to main content

sentinel_driver/connection/
transaction_impl.rs

1use super::{notify, Connection, Result, TransactionConfig};
2
3impl Connection {
4    /// Begin a transaction with default settings.
5    pub async fn begin(&mut self) -> Result<()> {
6        self.begin_with(TransactionConfig::new()).await
7    }
8
9    /// Begin a transaction with custom settings.
10    pub async fn begin_with(&mut self, config: TransactionConfig) -> Result<()> {
11        self.instr().on_event(&crate::Event::TxBegin {
12            isolation: config.isolation,
13        });
14        self.simple_query(&config.begin_sql()).await?;
15        Ok(())
16    }
17
18    /// Commit the current transaction.
19    pub async fn commit(&mut self) -> Result<()> {
20        let started = std::time::Instant::now();
21        let res = self.simple_query("COMMIT").await;
22        let duration = started.elapsed();
23        self.instr().on_event(&crate::Event::TxCommit { duration });
24        res.map(|_| ())
25    }
26
27    /// Rollback the current transaction.
28    pub async fn rollback(&mut self) -> Result<()> {
29        let started = std::time::Instant::now();
30        let res = self.simple_query("ROLLBACK").await;
31        let duration = started.elapsed();
32        self.instr().on_event(&crate::Event::TxRollback {
33            duration,
34            reason: crate::RollbackReason::Explicit,
35        });
36        res.map(|_| ())
37    }
38
39    /// Create a savepoint.
40    pub async fn savepoint(&mut self, name: &str) -> Result<()> {
41        self.simple_query(&format!("SAVEPOINT {}", notify::quote_identifier(name)))
42            .await?;
43        Ok(())
44    }
45
46    /// Rollback to a savepoint.
47    pub async fn rollback_to(&mut self, name: &str) -> Result<()> {
48        self.simple_query(&format!(
49            "ROLLBACK TO SAVEPOINT {}",
50            notify::quote_identifier(name)
51        ))
52        .await?;
53        Ok(())
54    }
55}