Skip to main content

Transaction

Struct Transaction 

Source
pub struct Transaction { /* private fields */ }
Expand description

A transaction handle.

Transaction handles are used to protect database operations. A single Transaction may be used for operations on multiple databases within the same environment.

Transaction handles are free-threaded; they may be used concurrently by multiple threads. Once committed or aborted, the handle must not be used for any further operations.

§Example

use noxu_db::{Environment, EnvironmentConfig};
use std::path::PathBuf;

let config = EnvironmentConfig::new(PathBuf::from("/tmp/mydb"))
    .with_allow_create(true)
    .with_transactional(true);
let env = Environment::open(config).unwrap();
let txn = env.begin_transaction(None).unwrap();
// ... do operations ...
txn.commit().unwrap();

Implementations§

Source§

impl Transaction

Source

pub fn new(id: u64, config: TransactionConfig) -> Self

👎Deprecated since 2.4.1:

use Environment::begin_transaction() to obtain a fully wired transaction handle

Create a new unconnected transaction handle.

Deprecated — this constructor creates a transaction that is not wired to a WAL, lock manager, or environment. Commits and aborts on such a transaction are no-ops. Use Environment::begin_transaction to obtain a fully operational handle.

§Arguments
  • id - Unique transaction ID
  • config - Transaction configuration
Source

pub fn with_log_manager( id: u64, config: TransactionConfig, log_manager: Arc<LogManager>, ) -> Self

Create a new transaction backed by a real WAL.

Called by Environment::begin_transaction() to wire the transaction to the environment’s log manager so that commit/abort write WAL entries.

Internal — this method is pub for cross-crate wiring within the Noxu DB engine but is not part of the v3.0 stable surface. LogManager is not re-exported by noxu-db; downstream callers cannot use this method without adding an internal crate dependency.

Source

pub fn with_env_impl(self, env_impl: Arc<SyncMutex<EnvironmentImpl>>) -> Self

Wires the EnvironmentImpl so that abort() can apply undo records.

Called by Environment::begin_transaction() after constructing the Transaction.

InternalEnvironmentImpl is not re-exported by noxu-db.

Source

pub fn with_inner_txn(self, txn: Arc<Mutex<Txn>>) -> Self

Sets the inner Txn for lock management and write-set tracking.

Called by Environment::begin_transaction() to wire the transaction to the environment’s TxnManager / LockManager.

Internalnoxu_txn::Txn is not re-exported by noxu-db.

Source

pub fn get_inner_txn(&self) -> Option<Arc<Mutex<Txn>>>

Returns a clone of the Arc<Mutex<Txn>> inner transaction, if any.

Used by Database::make_cursor_for_txn() to wire the cursor to the same Txn so that write operations lock via the transaction.

Internalnoxu_txn::Txn is not re-exported by noxu-db.

Source

pub fn register_abort_callback<F>(&self, f: F)
where F: FnOnce() + Send + 'static,

Register a callback to run when this transaction aborts.

Used by Environment::open_database() to roll back a transactional database creation if the owning transaction is aborted (C-4 / JE 1-I). The callback is invoked from within abort(), after WAL writes but before the outer state is marked Aborted.

Source

pub fn register_commit_callback<F>(&self, f: F)
where F: FnOnce() + Send + 'static,

Register a callback to run when this transaction commits.

Used by Environment::open_database() to finalise a transactional database creation when the owning transaction commits (C-4 / JE 1-I). The callback is invoked from within commit_with_durability(), after the WAL entry is written and locks are released.

Source

pub fn commit(&self) -> Result<()>

Commit the transaction.

All operations performed under this transaction are made durable and visible to other transactions.

§Errors

Returns an error if:

  • The transaction is not in Open state.
  • Writing the TxnCommit WAL entry fails (EnvironmentFailure with reason LogWrite, propagated from write_txn_end).
  • The inner-Txn commit fails after the WAL entry has been fsynced (e.g. open cursors held against this transaction, or inner-state inconsistency surfaced by check_state). When this happens the transaction is still durably committed; the error is propagated so the caller can react to the leak.
Source

pub fn commit_with_durability(&self, durability: Durability) -> Result<()>

Commit the transaction with specific durability.

§Arguments
  • durability - Durability settings for this commit
§Errors

Returns an error if:

  • The transaction is not in Open state.
  • Writing the TxnCommit WAL entry fails (EnvironmentFailure with reason LogWrite, propagated from write_txn_end).
  • The inner-Txn commit fails after the WAL entry has been fsynced (e.g. open cursors held against this transaction, or inner-state inconsistency surfaced by check_state). When this happens the transaction is still durably committed; the error is propagated so the caller can react to the leak.
Source

pub fn abort(&self) -> Result<()>

Abort the transaction.

All operations performed under this transaction are rolled back.

§Errors

Returns an error if:

  • The transaction is already committed or aborted.
  • Writing the TxnAbort WAL entry fails (EnvironmentFailure with reason LogWrite, propagated from write_txn_end). This path is taken only when the transaction is not read-only and a LogManager is configured on the environment.
Source

pub fn prepare( &self, xid_format_id: i32, xid_gtrid: &[u8], xid_bqual: &[u8], ) -> Result<()>

Prepares the transaction for the second phase of XA two-phase commit.

Implements the crash-durable contract introduced in wave 3-2:

  1. Writes a TxnPrepare WAL frame containing the txn id, the first / last LSN logged by this transaction, and the supplied XID components (format_id, gtrid, bqual). The frame is fsynced before this method returns, so a crash immediately afterwards still allows recovery to resurrect the prepared state.
  2. Marks the inner Txn as PREPARED — direct commit() and abort() calls now return OperationNotAllowed; only resolved_commit_after_prepare and resolved_abort_after_prepare may finalise the transaction.
  3. Locks are RETAINED — prepared transactions hold every lock until xa_commit / xa_rollback so concurrent readers cannot observe in-flight state.
  4. The persistent prepared-log entry (the noxu-xa::PreparedLog XID -> timestamp record) is the responsibility of the XA layer and is written after this method returns. The WAL TxnPrepare frame is the source of truth for crash durability; the prepared-log database is a convenience for operators inspecting in-doubt XIDs without scanning the WAL.

Returns Ok(()) on success. Read-only transactions (no LN frames written) still take a code path here so the inner Txn flips to PREPARED, but no TxnPrepare frame is emitted — the XA layer should take its PrepareResult::ReadOnly shortcut rather than calling this method on read-only branches.

§Errors
  • OperationNotAllowed if the transaction is not Open.
  • EnvironmentFailure { reason: LogWrite } if the WAL write or fsync fails.
Source

pub fn resolved_commit_after_prepare(&self) -> Result<()>

Resolves a prepared transaction with a commit.

Used by the XA xa_commit path. Bypasses the TransactionState::Prepared guard in commit_with_durability because the prepare already established the commit decision.

Steps:

  1. Verifies the txn is Prepared.
  2. Writes a TxnCommit WAL frame (mirrors commit()).
  3. Releases the inner Txn’s locks via resolved_commit_after_prepare.
  4. Transitions state to Committed and prunes from the active-txns registry.
Source

pub fn resolved_abort_after_prepare(&self) -> Result<()>

Resolves a prepared transaction with an abort.

Source

pub fn get_id(&self) -> u64

Get the transaction ID.

Source

pub fn set_name<S: Into<String>>(&self, name: S)

Set the human-readable name of this transaction.

Mirrors Transaction.setName(String). The name is purely diagnostic — it appears in Debug output, structured log records, and lock-conflict reports. (transaction-env F22).

Source

pub fn get_name(&self) -> Option<String>

Returns the caller-supplied transaction name, if any.

Mirrors Transaction.getName().

Source

pub fn lock_count(&self) -> usize

Returns the number of locks currently held by this transaction.

Mirrors Transaction.getLockStat() / Transaction.getNumWriteLocks() + getNumReadLocks() (the JE API exposes both counts; we return the sum because the lock manager partitions reads / writes per LSN rather than per record). Returns 0 for transactions that have not acquired any locks (or for read-only transactions running with read-uncommitted isolation, which skip lock acquisition entirely). (transaction-env F23 “lock-stat reporting missing”).

Source

pub fn lock_counts(&self) -> (usize, usize)

Returns (read_lock_count, write_lock_count) for this transaction’s lock set.

Mirrors JE’s Transaction.getNumReadLocks() / getNumWriteLocks() accessors. Returns (0, 0) for a transaction that has not acquired any locks.

Source

pub fn get_state(&self) -> TransactionState

Get the current transaction state.

Source

pub fn is_valid(&self) -> bool

Check if the transaction is valid (in Open state).

Source

pub fn set_lock_timeout(&self, timeout_ms: u64)

Set the lock timeout for this transaction.

§Arguments
  • timeout_ms - Lock timeout in milliseconds (0 = use environment default)
Source

pub fn get_lock_timeout(&self) -> u64

Get the lock timeout for this transaction.

Source

pub fn set_txn_timeout(&self, timeout_ms: u64)

Set the transaction timeout.

§Arguments
  • timeout_ms - Transaction timeout in milliseconds (0 = use environment default)
Source

pub fn get_txn_timeout(&self) -> u64

Get the transaction timeout for this transaction.

Source

pub fn get_durability(&self) -> Option<Durability>

Get the durability setting for this transaction.

Source

pub fn is_read_only(&self) -> bool

Check if this is a read-only transaction.

Source

pub fn elapsed(&self) -> Duration

Get the elapsed time since transaction start.

Trait Implementations§

Source§

impl Drop for Transaction

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more