toasty_core/driver/operation/
transaction.rs

1use super::Operation;
2
3/// SQL transaction isolation levels.
4///
5/// Not all backends support all levels. The driver returns an error if an
6/// unsupported level is requested.
7///
8/// # Examples
9///
10/// ```
11/// use toasty_core::driver::operation::IsolationLevel;
12///
13/// let level = IsolationLevel::Serializable;
14/// assert_eq!(level, IsolationLevel::Serializable);
15/// ```
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum IsolationLevel {
18    /// Transactions can see uncommitted changes from other transactions.
19    ReadUncommitted,
20    /// Transactions only see changes committed before each statement.
21    ReadCommitted,
22    /// Transactions see a consistent snapshot from the start of the transaction.
23    RepeatableRead,
24    /// Full serializability; transactions behave as if executed one at a time.
25    Serializable,
26}
27
28/// A transaction lifecycle operation.
29///
30/// Covers the full transaction lifecycle: begin, commit, rollback, and
31/// savepoint management. Convert to [`Operation`] with `.into()`.
32///
33/// # Examples
34///
35/// ```
36/// use toasty_core::driver::operation::{Transaction, Operation};
37///
38/// // Start a default transaction
39/// let op: Operation = Transaction::start().into();
40///
41/// // Commit
42/// let op: Operation = Transaction::Commit.into();
43/// assert!(op.is_transaction_commit());
44/// ```
45#[derive(Debug, Clone)]
46pub enum Transaction {
47    /// Start a transaction with optional configuration.
48    ///
49    /// When `isolation` is `None` and `read_only` is `false`, the database's
50    /// default isolation level and read-write mode are used.
51    Start {
52        /// Optional isolation level. `None` uses the database default.
53        isolation: Option<IsolationLevel>,
54        /// When `true`, the transaction is read-only.
55        read_only: bool,
56    },
57
58    /// Commit a transaction
59    Commit,
60
61    /// Rollback a transaction
62    Rollback,
63
64    /// Create a savepoint with the given identifier
65    Savepoint(String),
66
67    /// Release (commit) a savepoint
68    ReleaseSavepoint(String),
69
70    /// Rollback to a savepoint, undoing work since it was created
71    RollbackToSavepoint(String),
72}
73
74impl Transaction {
75    /// Start a transaction with database defaults.
76    pub fn start() -> Self {
77        Self::Start {
78            isolation: None,
79            read_only: false,
80        }
81    }
82}
83
84impl Operation {
85    /// Returns `true` if this is a [`Transaction::Commit`] operation.
86    pub fn is_transaction_commit(&self) -> bool {
87        matches!(self, Operation::Transaction(Transaction::Commit))
88    }
89}
90
91impl From<Transaction> for Operation {
92    fn from(value: Transaction) -> Self {
93        Self::Transaction(value)
94    }
95}