Skip to main content

Crate libmdbx

Crate libmdbx 

Source
Expand description

§libmdbx-rs

Idiomatic, safe Rust bindings for libmdbx, an embedded key-value store.

The crate wraps the vendored C library (mdbx-sys) behind a Send + Sync transaction API. An optional typed ORM lives under libmdbx::orm.

Documentation · Repository

The crate is pre-1.0: breaking changes are called out in CHANGELOG.md.

§Build requirements

Building compiles the vendored libmdbx C sources and generates FFI bindings:

  • A C compiler (any toolchain supported by the cc crate).
  • libclang for bindgen (on Windows, point LIBCLANG_PATH at your LLVM installation).

Rust: latest stable (edition 2024).

§Usage

The unnamed table needs no extra options:

use libmdbx::{Database, NoWriteMap, WriteFlags};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let path = std::env::temp_dir().join("libmdbx-demo");
    let db = Database::<NoWriteMap>::open(&path)?;

    let txn = db.begin_rw_txn()?;
    let table = txn.create_table(None, Default::default())?;
    txn.put(&table, b"cat", b"meow", WriteFlags::UPSERT)?;
    txn.commit()?;

    let txn = db.begin_ro_txn()?;
    let table = txn.open_table(None)?;
    let value = txn.get::<Vec<u8>>(&table, b"cat")?.unwrap();
    assert_eq!(value, b"meow");

    Ok(())
}

Named tables need slots reserved at open (max_tables defaults to 0). Without that, open_table / create_table fail with Error::DbsFull:

use libmdbx::{Database, DatabaseOptions, NoWriteMap};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let db = Database::<NoWriteMap>::open_with_options(
        "mydb",
        DatabaseOptions {
            max_tables: Some(4),
            ..Default::default()
        },
    )?;
    let txn = db.begin_rw_txn()?;
    txn.create_table(Some("pets"), Default::default())?;
    txn.commit()?;
    Ok(())
}

Walk a table with Cursor. Reads in a read-only transaction can be zero-copy (Cow<[u8]>); read-write transactions always copy, because libmdbx may relocate pages on a later write.

Database is generic over the write path:

  • NoWriteMap — modified pages are buffered and written through file I/O.
  • WriteMap — writes go through the memory map (typically faster). The ORM defaults to this.

§Logging

libmdbx’s own diagnostics are forwarded to the log crate under the libmdbx target (they are never printed to stderr). Install any log backend to see them, e.g. with RUST_LOG=libmdbx=info for env_logger.

§ORM

Enable the orm feature and see libmdbx::orm. Declare tables with table! / dupsort!, assemble a DatabaseChart, and use typed get / upsert / cursors. cbor adds serde-via-CBOR table objects.

§Features

FeatureDescription
ormTyped table mapping (libmdbx::orm).
cborAny serde type as an ORM key/value via CBOR (cbor_table_object!, ciborium). Implies orm.
bytesbytes::Bytes as a decoded value for core reads (copied), and as an ORM key/value.
lifetimed-bytesZero-copy lifetime-carrying Bytes<'tx> handles for core transaction reads.

§FFI crate

mdbx-sys is the raw bindgen crate. This workspace pins it exactly (=) so the wrapper and FFI crate always match.

§License

Apache License 2.0. See LICENSE.

Modules§

ormorm
Fully typed ORM for use with libmdbx. Fully typed ORM based on libmdbx.

Macros§

cbor_table_objectcbor and orm
Implements Encodable and Decodable for a type using CBOR, via serde::Serialize and serde::Deserialize.
dupsortorm
Declares a DUP_SORT table type, like table! plus an optional [SeekValue] after the value type.
tableorm
Declares a table type: table!((Name) Key => Value), or table!((Name) Key [SeekKey] => Value) with a distinct seek-key type.
table_infoorm
The DatabaseChart entry of a table type: table_info!(Name).
table_integerorm
Implements Encodable and Decodable for an integer newtype ty wrapping real_ty, as big-endian bytes (so keys sort numerically).

Structs§

Cursor
A cursor for navigating the items within a table.
CursorPtr
A raw libmdbx cursor handle, for direct FFI use; see Cursor::cursor.
Database
Supports multiple tables, all residing in the same shared-memory map.
DatabaseOptions
Options for Database::open_with_options. None and false keep libmdbx’s defaults.
DbPtr
A raw libmdbx environment handle, for direct FFI use; see Database::ptr.
GeometryInfo
The database file’s size limits and growth policy, in bytes; see ReadWriteOptions.
Info
Database information.
IntoIter
An iterator over the key/value pairs in an MDBX table, owning its cursor.
Iter
An iterator over the key/value pairs in an MDBX table, borrowing its cursor.
IterDup
An iterator over the keys and duplicate values in an MDBX table.
NoWriteMap
DatabaseKind that buffers modified pages and writes them with file I/O.
ObjectLength
If you don’t need the data itself, just its length.
RO
TransactionKind of read-only transactions: MVCC snapshots with zero-copy reads.
RW
TransactionKind of read-write transactions; one at a time per database.
ReadWriteOptions
Settings of a read-write database. File sizes are in bytes; None keeps the current value (or libmdbx’s default for a new database).
Stat
Database statistics.
Table
A handle to an individual table in a database.
TableFlags
Table options, fixed when a table is created.
Transaction
An MDBX transaction.
TxnPtr
A raw libmdbx transaction handle, for direct FFI use; see Transaction::txn.
WriteFlags
Write options for put and delete operations.
WriteMap
DatabaseKind that writes directly through the memory map (MDBX_WRITEMAP); typically faster, but nested transactions are unavailable.

Enums§

Error
An error from libmdbx or from this wrapper.
Mode
Whether a database is opened read-only or read-write.
PageSize
Page size of a newly created database; see DatabaseOptions::page_size.
SyncMode
MDBX sync mode

Traits§

DatabaseKind
How a Database writes: through the memory map (WriteMap) or through file I/O (NoWriteMap). Sealed.
Decodable
Implement this to be able to decode data values.
TransactionKind
Whether a Transaction is read-only (RO) or read-write (RW). Sealed.

Type Aliases§

Result
An MDBX result.