MDBX Derive
Derive macros and a lightweight ORM for libmdbx, built on top of libmdbx-remote.
Usage
Derive Macros
Key encoding
KeyObject— ImplementsKeyObjectEncode/KeyObjectDecodeby serializing each field as raw big-endian bytes, concatenated in declaration order. A struct with oneu8and oneu16produces exactly 3 bytes. The encoding is unambiguous only when decoded with the same schema.KeyAsTableObject— Reuses theKeyObjectencoding as aTableObjectEncode/TableObjectDecodeimplementation.
Value (table object) encoding
ZstdPostcardObject— Serializes with postcard, then compresses with zstd.ZstdJSONObject— Serializes to JSON (serde_jsonorsimd-json), then compresses with zstd. Requiresserde_jsonorsimd-jsonfeature.ZstdBcsObject— Serializes with BCS, then compresses with zstd. Requiresbcsfeature.BcsObject— Serializes with BCS (no compression). Requiresbcsfeature.
ORM macros (require mdbx feature)
mdbx_table!/mdbx_table_def!— Define a table with key/value types.mdbx_dupsort_table!/mdbx_dupsort_table_def!— Define a DUPSORT table.mdbx_database!— Define a database struct that groups multiple tables, with auto-generated DBI handles and helper methods.
Features
| Feature | Default | Description |
|---|---|---|
mdbx |
no | Enable libmdbx-remote dependency and the ORM layer (mdbx_table!, mdbx_database!, etc.). Without this, the crate provides only the derive macros and encode/decode traits. |
serde_json |
yes | Use serde_json for ZstdJSONObject. |
simd-json |
no | Use simd-json for ZstdJSONObject (takes precedence over serde_json when both are enabled). |
bcs |
yes | Support BCS encoding (BcsObject, ZstdBcsObject). |
alloy |
yes (in mdbx-derive-traits) |
Implement KeyObjectEncode / KeyObjectDecode for alloy types (Address, B256, U256, etc.). |
Examples
Minimal — encode/decode only
mdbx-derive can be used purely for serialization without any MDBX dependency:
use Cursor;
use ;
use ;
// Key encode/decode
let k = TrivialKey ;
let encoded = k.key_encode.unwrap;
assert_eq!;
let decoded = key_decode.unwrap;
assert_eq!;
assert_eq!;
// Table object encode/decode (zstd + postcard)
let obj = TrivialObject ;
let encoded = obj.table_encode.unwrap;
let decoded = table_decode.unwrap;
assert_eq!;
assert_eq!;
ORM — tables and databases
Enable the mdbx feature to use the full ORM layer:
[]
= { = "0.7", = ["mdbx"] }
use *;
;
;
// Define tables with Key and Value types
mdbx_table!;
mdbx_table!;
// Query a table directly
let out: = get_item.await?;
// Group tables into a database
mdbx_database!;
// Open and auto-create tables
let db = open_create_tables_with_defaults.await?;
// DBI handles are available on the generated struct
let dbi: u32 = db.dbis.trivial_table;
// Or open existing tables without creating
let db = open_tables_with_defaults.await?;
// Read/write metadata
let meta: = db.metadata.await?;
db.write_metadata.await?;