Skip to main content

Environment

Struct Environment 

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

A database environment.

An Environment provides support for caching, locking, logging, and transactions. It is the top-level handle through which databases are opened and transactions are started.

§Example

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

let config = EnvironmentConfig::new(PathBuf::from("/tmp/mydb"))
    .allow_create(true)
    .transactional(true);
let env = Environment::open(config).unwrap();
env.close().unwrap();

Implementations§

Source§

impl Environment

Source

pub fn open(config: EnvironmentConfig) -> Result<Self>

Opens or creates a database environment.

Constructor.

§Arguments
  • config - The environment configuration
§Returns

The opened environment handle

§Errors

Returns an error if:

  • The environment directory does not exist and allow_create is false
  • The environment directory exists but is not writable and read_only is false
  • Invalid configuration parameters are provided
Source

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

Closes the environment handle.

§Errors

Returns an error if:

  • The environment is already closed
  • There are open database handles
  • There are active transactions
Source

pub fn open_database( &self, txn: Option<&Transaction>, name: &str, config: &DatabaseConfig, ) -> Result<Database>

Opens or creates a database.

§Arguments
  • txn - Optional transaction handle (currently ignored)
  • name - Database name
  • config - Database configuration
§Returns

The opened database handle

§Errors

Returns an error if:

  • The environment is closed
  • The database name is invalid
  • The database does not exist and allow_create is false
  • A handle for name is already open in this Environment (DatabaseAlreadyExists)
Source

pub fn remove_database( &self, _txn: Option<&Transaction>, name: &str, ) -> Result<()>

Removes a database.

§Arguments
  • txn - Optional transaction handle (currently ignored)
  • name - Database name
§Errors

Returns an error if:

  • The environment is closed
  • The database does not exist
  • The database is currently open
Source

pub fn truncate_database( &self, _txn: Option<&Transaction>, name: &str, ) -> Result<u64>

Truncates a database: removes all records while keeping the database registered and any open handles valid.

Returns the number of records that were in the database before truncation.

Mirrors Environment.truncateDatabase(txn, dbName, returnCount).

Source

pub fn rename_database( &self, _txn: Option<&Transaction>, old_name: &str, new_name: &str, ) -> Result<()>

Renames a database.

§Arguments
  • txn - Optional transaction handle (currently ignored)
  • old_name - Current database name
  • new_name - New database name
§Errors

Returns an error if:

  • The environment is closed
  • The source database does not exist
  • The destination database already exists
  • The source database is currently open
Source

pub fn begin_transaction( &self, config: Option<&TransactionConfig>, ) -> Result<Transaction>

Begins a new transaction.

§Arguments
  • config - Optional transaction configuration
§Returns

A new transaction handle.

§Errors

Returns an error if:

  • The environment is closed
  • The environment is not transactional
§Nested transactions

Nested (child) transactions are not supported. In v1.5 this method took an Option<&Transaction> parent argument that was rejected at runtime with NoxuError::Unsupported (Decision 3B in docs/src/internal/v1.5-decisions-2026-05.md, audit finding F11). In v2.0 the parameter has been removed entirely — the type system now enforces the constraint, so what was a runtime error is now a compile error.

Source

pub fn get_database_names(&self) -> Result<Vec<String>>

Returns a list of database names.

§Returns

A vector of database names

§Errors

Returns an error if the environment is closed

Source

pub fn set_replica_coordinator(&self, coord: SharedReplicaAckCoordinator)

Install a replica-ack coordinator on this environment.

After this call, every transaction begun on this environment will consult the coordinator on commit_with_durability and block until the configured ReplicaAckPolicy is satisfied (or until replica_ack_timeout elapses, in which case NoxuError::InsufficientReplicas is returned).

noxu_rep::ReplicatedEnvironment implements noxu_dbi::ReplicaAckCoordinator; users typically wire it as:

let rep_env = Arc::new(ReplicatedEnvironment::new(rep_config)?);
env.set_replica_coordinator(rep_env.clone());
rep_env.with_environment(env_impl);

Closes finding F1 of docs/src/internal/api-audit-2026-05-rep.md.

Source

pub fn clear_replica_coordinator(&self)

Clear any installed replica-ack coordinator.

Subsequent commit_with_durability calls revert to local-only durability semantics.

Source

pub fn set_replica_ack_timeout(&self, timeout: Duration)

Set the per-commit timeout used when waiting for replica acknowledgments.

Default is 5 seconds. Mirrors noxu_rep::RepConfig::replica_ack_timeout.

Source

pub fn get_replica_ack_timeout(&self) -> Duration

Returns the per-commit replica-ack timeout.

Source

pub fn get_home(&self) -> &Path

Returns the home directory path.

Source

pub fn get_config(&self) -> &EnvironmentConfig

Returns the environment configuration.

Source

pub fn get_mutable_config(&self) -> Result<EnvironmentMutableConfig>

Returns the mutable subset of environment configuration.

Mirrors Environment.getMutableConfig(). The returned struct reflects the current runtime values; pass it (modified) to set_mutable_config() to apply changes without re-opening the environment.

Source

pub fn set_mutable_config( &mut self, cfg: EnvironmentMutableConfig, ) -> Result<()>

Applies a set of mutable configuration changes to the running environment.

Mirrors Environment.setMutableConfig(EnvironmentMutableConfig). Only the fields that differ from their sentinel “no-change” values are applied (None means unchanged). Some(0) for a timeout clears it (matches JE: 0 = no timeout).

§Errors

Returns an error if the environment is closed or invalidated.

Source

pub fn checkpoint(&self, config: Option<&CheckpointConfig>) -> Result<()>

Runs a checkpoint.

Mirrors Environment.checkpoint(CheckpointConfig). If the environment has no checkpointer (e.g. non-transactional or in-memory), this is a no-op.

§Arguments
  • config - Optional checkpoint options (force, thresholds, etc.)
§Errors

Returns an error if the environment is closed, invalidated, or if the checkpoint itself fails (e.g. disk write error).

Source

pub fn is_valid(&self) -> bool

Returns true if the environment is open and has not been invalidated by a fatal error.

Mirrors Environment.isValid(). Returns false after the environment is closed or after an EnvironmentFailure whose reason.invalidates_environment() returns true (e.g. LogChecksum, BtreeCorruption, DiskLimit). Once invalidated the environment must be closed and re-opened.

Source

pub fn invalidate(&self)

Invalidates the environment in response to a fatal error.

Called internally when an EnvironmentFailure with reason.invalidates_environment() == true propagates out of a background daemon. After invalidation is_valid() returns false and all subsequent public API calls return EnvironmentFailure.

Source

pub fn is_transactional(&self) -> bool

Returns whether the environment is transactional.

Via environment.

Source

pub fn is_read_only(&self) -> bool

Returns whether the environment is read-only.

Via environment.

Source

pub fn get_stats(&self) -> Result<EnvironmentStats>

Returns a snapshot of environment statistics from all subsystems.

Mirrors Environment.getStats(StatsConfig).

Source

pub fn stat_fsync_count(&self) -> u64

Returns the total number of fdatasync calls performed by the log manager.

Useful for benchmarking and for verifying that group commit is working (fewer fsyncs than commits). Returns 0 if the environment is non-transactional (no log manager).

Source

pub fn recovered_prepared_txns(&self) -> Vec<PreparedTxnInfo>

Returns the list of XA in-doubt prepared transactions surfaced by the most recent recovery pass.

The XA layer (noxu_xa::XaEnvironment::xa_recover) reads this list to populate its return value with XIDs that completed phase 1 of two-phase commit but were not committed or aborted before the previous shutdown / crash. An empty Vec means there are no in-doubt transactions to resolve.

See noxu_xa for XA two-phase commit.

Source

pub fn take_recovered_prepared_lns(&self, txn_id: u64) -> Vec<PreparedLnReplay>

Removes and returns the LN replay list for a recovered prepared transaction.

Used by xa_commit(xid) after locating the txn id from Self::recovered_prepared_txns. The XA layer iterates the returned list and applies each LN to the in-memory tree before writing the TxnCommit WAL frame.

Source

pub fn forget_recovered_prepared_txn(&self, txn_id: u64)

Removes a recovered prepared txn entry after the XA layer has successfully resolved it (xa_commit or xa_rollback). Idempotent.

Source

pub fn write_txn_commit_for_recovered(&self, txn_id: u64) -> Result<()>

Writes a TxnCommit WAL frame for txn_id and fsyncs.

Used by xa_commit(xid) to durably resolve a recovered prepared transaction without requiring an in-memory Txn (which the crash destroyed). The caller must have already replayed any LNs into the in-memory tree via Self::take_recovered_prepared_lns and applied them.

See noxu_xa for XA two-phase commit.

Source

pub fn write_txn_abort_for_recovered(&self, txn_id: u64) -> Result<()>

Writes a TxnAbort WAL frame for txn_id. Used by xa_rollback(xid) to durably resolve a recovered prepared transaction.

Source

pub fn apply_recovered_prepared_lns( &self, lns: &[PreparedLnReplay], ) -> Result<()>

Replays a recovered prepared transaction’s LNs into the in-memory tree at xa_commit resolution time.

Iterates the LN list (already removed from the recovered map by the caller) and applies each insert/update/delete to the matching DatabaseImpl’s tree. This makes the prepared writes observable to subsequent reads in the same process — without this step, a recovered+committed XA branch’s writes would only become visible after a second recovery on the next reopen.

Source

pub fn verify(&self, config: &VerifyConfig) -> Result<VerifyResult>

Verifies the structural integrity of all databases in this environment.

Iterates every open DatabaseImpl in the environment’s db_map and calls verify_database_impl() on each one (B-tree key-order checks, LSN validity, child-pointer completeness). Results are merged into a single VerifyResult.

Mirrors Environment.verify(VerifyConfig, PrintStream) in creates a BtreeVerifier and calls verifier.verifyAll().

§Arguments
  • config - Verification options (btree, log, checksums, max_errors).
§Returns

A combined VerifyResult over all databases.

§Errors

Returns an error if the environment is closed or invalidated.

Source

pub fn compress(&self) -> Result<usize>

Explicitly trigger BIN compression for all open databases.

Mirrors Environment.compress() in JE (Environment.java:1887). Synchronously runs one pass of the INCompressor logic: finds every BIN with known-deleted slots and compresses them. Useful in tests to drain the compressor queue before taking a checkpoint, and for applications that want deterministic memory reclamation after bulk deletes.

Returns Ok(n) where n is the number of BINs compressed. Returns Err if the environment is closed or invalid.

Source

pub fn evict_memory(&self) -> Result<usize>

Explicitly trigger the memory evictor.

Mirrors Environment.evictMemory() in JE (Environment.java:1860). Requests that the cache evictor free cache pages down toward the configured cache size. Useful after bulk inserts to reclaim memory proactively rather than waiting for the background daemon.

Returns Ok(bytes_evicted). Returns Err if the environment is closed or invalid.

Trait Implementations§

Source§

impl Drop for Environment

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