postgres/
transaction_builder.rs

1use crate::connection::ConnectionRef;
2use crate::{Error, IsolationLevel, Transaction};
3
4/// A builder for database transactions.
5pub struct TransactionBuilder<'a> {
6    connection: ConnectionRef<'a>,
7    builder: tokio_postgres::TransactionBuilder<'a>,
8}
9
10impl<'a> TransactionBuilder<'a> {
11    pub(crate) fn new(
12        connection: ConnectionRef<'a>,
13        builder: tokio_postgres::TransactionBuilder<'a>,
14    ) -> TransactionBuilder<'a> {
15        TransactionBuilder {
16            connection,
17            builder,
18        }
19    }
20
21    /// Sets the isolation level of the transaction.
22    pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self {
23        self.builder = self.builder.isolation_level(isolation_level);
24        self
25    }
26
27    /// Sets the access mode of the transaction.
28    pub fn read_only(mut self, read_only: bool) -> Self {
29        self.builder = self.builder.read_only(read_only);
30        self
31    }
32
33    /// Sets the deferrability of the transaction.
34    ///
35    /// If the transaction is also serializable and read only, creation of the transaction may block, but when it
36    /// completes the transaction is able to run with less overhead and a guarantee that it will not be aborted due to
37    /// serialization failure.
38    pub fn deferrable(mut self, deferrable: bool) -> Self {
39        self.builder = self.builder.deferrable(deferrable);
40        self
41    }
42
43    /// Begins the transaction.
44    ///
45    /// The transaction will roll back by default - use the `commit` method to commit it.
46    pub fn start(mut self) -> Result<Transaction<'a>, Error> {
47        let transaction = self.connection.block_on(self.builder.start())?;
48        Ok(Transaction::new(self.connection, transaction))
49    }
50}