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
impl Environment
Sourcepub fn open(config: EnvironmentConfig) -> Result<Self>
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_createis false - The environment directory exists but is not writable and
read_onlyis false - Invalid configuration parameters are provided
Sourcepub fn close(&self) -> Result<()>
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
Sourcepub fn open_database(
&self,
txn: Option<&Transaction>,
name: &str,
config: &DatabaseConfig,
) -> Result<Database>
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 nameconfig- 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_createis false - A handle for
nameis already open in thisEnvironment(DatabaseAlreadyExists)
Sourcepub fn remove_database(
&self,
_txn: Option<&Transaction>,
name: &str,
) -> Result<()>
pub fn remove_database( &self, _txn: Option<&Transaction>, name: &str, ) -> Result<()>
Sourcepub fn truncate_database(
&self,
_txn: Option<&Transaction>,
name: &str,
) -> Result<u64>
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).
Sourcepub fn rename_database(
&self,
_txn: Option<&Transaction>,
old_name: &str,
new_name: &str,
) -> Result<()>
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 namenew_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
Sourcepub fn begin_transaction(
&self,
config: Option<&TransactionConfig>,
) -> Result<Transaction>
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.
Sourcepub fn get_database_names(&self) -> Result<Vec<String>>
pub fn get_database_names(&self) -> Result<Vec<String>>
Sourcepub fn set_replica_coordinator(&self, coord: SharedReplicaAckCoordinator)
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.
Sourcepub fn clear_replica_coordinator(&self)
pub fn clear_replica_coordinator(&self)
Clear any installed replica-ack coordinator.
Subsequent commit_with_durability calls revert to local-only
durability semantics.
Sourcepub fn set_replica_ack_timeout(&self, timeout: Duration)
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.
Sourcepub fn get_replica_ack_timeout(&self) -> Duration
pub fn get_replica_ack_timeout(&self) -> Duration
Returns the per-commit replica-ack timeout.
Sourcepub fn get_config(&self) -> &EnvironmentConfig
pub fn get_config(&self) -> &EnvironmentConfig
Returns the environment configuration.
Sourcepub fn get_mutable_config(&self) -> Result<EnvironmentMutableConfig>
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.
Sourcepub fn set_mutable_config(
&mut self,
cfg: EnvironmentMutableConfig,
) -> Result<()>
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.
Sourcepub fn checkpoint(&self, config: Option<&CheckpointConfig>) -> Result<()>
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).
Sourcepub fn is_valid(&self) -> bool
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.
Sourcepub fn invalidate(&self)
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.
Sourcepub fn is_transactional(&self) -> bool
pub fn is_transactional(&self) -> bool
Returns whether the environment is transactional.
Via environment.
Sourcepub fn is_read_only(&self) -> bool
pub fn is_read_only(&self) -> bool
Returns whether the environment is read-only.
Via environment.
Sourcepub fn get_stats(&self) -> Result<EnvironmentStats>
pub fn get_stats(&self) -> Result<EnvironmentStats>
Returns a snapshot of environment statistics from all subsystems.
Mirrors Environment.getStats(StatsConfig).
Sourcepub fn stat_fsync_count(&self) -> u64
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).
Sourcepub fn recovered_prepared_txns(&self) -> Vec<PreparedTxnInfo>
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.
Sourcepub fn take_recovered_prepared_lns(&self, txn_id: u64) -> Vec<PreparedLnReplay>
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.
Sourcepub fn forget_recovered_prepared_txn(&self, txn_id: u64)
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.
Sourcepub fn write_txn_commit_for_recovered(&self, txn_id: u64) -> Result<()>
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.
Sourcepub fn write_txn_abort_for_recovered(&self, txn_id: u64) -> Result<()>
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.
Sourcepub fn apply_recovered_prepared_lns(
&self,
lns: &[PreparedLnReplay],
) -> Result<()>
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.
Sourcepub fn verify(&self, config: &VerifyConfig) -> Result<VerifyResult>
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.
Sourcepub fn compress(&self) -> Result<usize>
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.
Sourcepub fn evict_memory(&self) -> Result<usize>
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.