Crate struct_db

Source
Expand description

–> /!\ Important Update: This crate struct_db has been renamed to native_db to better reflect its functionality and purpose. Please update your dependencies to use native_db for the latest features and updates. <–

Struct DB is a Rust library that provides a simple, fast, and embedded database solution, focusing on maintaining coherence between Rust types and stored data with minimal boilerplate. It supports multiple indexes, real-time watch with filters, schema migration.

Use macro struct_db:

  • required: fn_primary_key(<function name>) associates a function of the struct that generates the primary key of the struct. Allows only one fn_primary_key declaration.
  • optional: fn_secondary_key(<function name>) associates a function of the struct that generates a secondary key of the struct. Allows multiple fn_secondary_key declarations.

struct_db generates an enum <your_type> with the suffix Key that contains all the secondary keys like: E.g. <your_type>Key::<your_secondary_key> more details here.

§API

§Example

use serde::{Deserialize, Serialize};
use struct_db::*;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[struct_db(
   fn_primary_key(p_key),  // required
   fn_secondary_key(s_key),  // optional
   // ... other fn_secondary_key ...
)]
struct Data(u32, String);

impl Data {
  // Returns primary key as big-endian bytes for consistent lexicographical ordering.
  pub fn p_key(&self) -> Vec<u8> {
    self.0.to_be_bytes().to_vec()
  }

  // Generates a secondary key combining the String field and the big-endian bytes of
  // the primary key for versatile queries.
  pub fn s_key(&self) -> Vec<u8> {
    let mut s_key = self.1.as_bytes().to_vec();
    s_key.extend_from_slice(&self.p_key().as_slice());
    s_key
  }
 }

 fn main() {
  let mut db = Db::create_tmp("my_db_example").unwrap();
  // Initialize the schema
  db.define::<Data>();

  // Insert data
  let txn = db.transaction().unwrap();
  {
     let mut tables = txn.tables();
     tables.insert(&txn, Data(1,"red".to_string())).unwrap();
     tables.insert(&txn, Data(2,"red".to_string())).unwrap();
     tables.insert(&txn, Data(3,"blue".to_string())).unwrap();
  }
  txn.commit().unwrap();
    
  let txn_read = db.read_transaction().unwrap();
  let mut tables = txn_read.tables();
    
  // Retrieve data with p_key=3
  let retrieve_data: Data = tables.primary_get(&txn_read, &3_u32.to_be_bytes()).unwrap().unwrap();
  println!("data p_key='3' : {:?}", retrieve_data);
    
  // Iterate data with s_key="red" String
  for item in tables.secondary_iter_start_with::<Data>(&txn_read, DataKey::s_key, "red".as_bytes()).unwrap() {
     println!("data s_key='1': {:?}", item);
  }

  // Remove data
  let txn = db.transaction().unwrap();
  {
     let mut tables = txn.tables();
     tables.remove(&txn, retrieve_data).unwrap();
  }
  txn.commit().unwrap();
 }

Modules§

watch

Structs§

Builder
Builder for the Db instance.
Db
The Db struct represents a database instance. It allows add schema, create transactions and watcher.
PrimaryIterator
Provides a way to iterate over the values stored in a database and automatically deserialize them into items of type T.
PrimaryIteratorStartWith
Same as PrimaryIterator but only returns values which primary key starts with the given prefix.
ReadOnlyTables
A collection of read-only tables. Only read operations available through the ReadableTable trait are allowed.
ReadOnlyTransaction
Can open only ReadOnlyTables.
Schema
Schema of the Item. Returned by the <your_item>::struct_db_schema() method.
SecondaryIterator
Same as PrimaryIterator but only returns values that match the given secondary key.
SecondaryIteratorStartWith
Same as PrimaryIterator but only returns values with secondary keys that start with the given prefix.
Tables
A collection of read-write tables. Read operation from ReadableTable and write operations insert, update, remove and migrate are available.
Transaction
Can open only Tables.

Enums§

Error

Traits§

KeyDefinition
ReadableTable
SDBItem

Functions§

bincode_decode_from_slice
bincode_encode_to_vec

Type Aliases§

Result

Attribute Macros§

struct_db