Struct struct_db::Db

source ·
pub struct Db { /* private fields */ }
Expand description

The Db struct represents a database instance. It allows add schema, create transactions and watcher.

Implementations§

source§

impl Db

source

pub fn create(path: impl AsRef<Path>) -> Result<Self>

Creates a new Db instance using the given path.

Use redb::Builder.create(…)

source

pub fn create_tmp(path: impl AsRef<Path>) -> Result<Self>

Creates a new Db instance using a temporary directory with the given path.

Example: Db::create_tmp('project/my_db') will create the db to /tmp/project/my_db.

Use redb::Builder.create(…)

source

pub fn open(path: impl AsRef<Path>) -> Result<Self>

Opens an existing Db instance using the given path.

source

pub fn open_tmp(path: impl AsRef<Path>) -> Result<Self>

Opens an existing Db instance using a temporary directory with the given path.

source

pub fn define<T: SDBItem>(&mut self)

Defines a table using the given schema.

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

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
#[struct_db(fn_primary_key(p_key))]
struct Data(u32);
impl Data {pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()}}

fn main() {
   let mut db = Db::create_tmp("my_db_as").unwrap();
   // Initialize the table
   db.define::<Data>();
}
source§

impl Db

source

pub fn transaction(&self) -> Result<Transaction<'_>>

Creates a new read-write transaction.

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

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[struct_db(fn_primary_key(p_key))]
struct Data(u32);
impl Data {pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()}}

fn main() {
  let mut db = Db::create_tmp("my_db_t").unwrap();
  db.define::<Data>();

  // Use transaction to insert a new data
  let mut txn = db.transaction().unwrap();
  {
    let mut data = Data(42);
    let mut tables = txn.tables();
    tables.insert(&txn, data).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit
   
  // Use transaction to update a data
  let mut txn = db.transaction().unwrap();
  {
      let mut tables = txn.tables();
      let (new_data, old_data) = {
          let old_data = tables.primary_get::<Data>(&txn, &42_u32.to_be_bytes()).unwrap().unwrap();
          let mut new_data = old_data.clone();
          new_data.0 = 43;
          (new_data, old_data)
      };       
      tables.update(&txn, old_data, new_data).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit

  // Use transaction to delete a data
  let mut txn = db.transaction().unwrap();
  {
     let mut tables = txn.tables();
     let data = tables.primary_get::<Data>(&txn, &43_u32.to_be_bytes()).unwrap().unwrap();
     tables.remove(&txn, data).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit
}
source

pub fn read_transaction(&self) -> Result<ReadOnlyTransaction<'_>>

Creates a new read-only transaction.

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

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[struct_db(fn_primary_key(p_key))]
struct Data(u32);
impl Data {pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()}}

fn main() {
 let mut db = Db::create_tmp("my_db_rt").unwrap();
 db.define::<Data>();
  
 // Insert a new data
 let mut txn = db.transaction().unwrap();
 {
   let mut tables = txn.tables();
   tables.insert(&txn, Data(42)).unwrap();
 }
 txn.commit().unwrap(); // /!\ Don't forget to commit
  
 let txn_read = db.read_transaction().unwrap();
 let mut tables = txn_read.tables();
 let len = tables.len::<Data>(&txn_read).unwrap();
 assert_eq!(len, 1);
}
source§

impl Db

source

pub fn primary_watch<T: SDBItem>( &self, key: Option<&[u8]> ) -> Result<(MpscReceiver<Event>, u64)>

Watches for changes in the specified table for the given primary key. If the argument key is None you will receive all the events from the table. Otherwise you will receive only the events for the given primary key.

Supported channels to to receive changes:

To unregister the watcher you need to call unwatch with the returned id.

Get data from the event, use inner() method on:

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

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[struct_db(fn_primary_key(p_key))]
struct Data(u32);
impl Data {pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()}}

fn main() {
 let mut db = Db::create_tmp("my_db").unwrap();
 db.define::<Data>();

 // None you will receive all the events from Data.
 let (event_receiver, _id) = db.primary_watch::<Data>(None).unwrap();

 // Add a new data
 let mut txn = db.transaction().unwrap();
 {
   let mut tables = txn.tables();
   tables.insert(&txn, Data(42)).unwrap();
 }
 txn.commit().unwrap(); // /!\ Don't forget to commit

 // Wait for the event
 for _ in 0..1 {
  // With the feature "async_tokio" you can use async/await pattern
  let event = event_receiver.recv().unwrap();
  if let watch::Event::Insert(insert) = event {
     let data = insert.inner::<Data>();
     assert_eq!(data, Data(42));
   }
 }
}
source

pub fn primary_watch_start_with<T: SDBItem>( &self, key_prefix: &[u8] ) -> Result<(MpscReceiver<Event>, u64)>

Watches for changes in the specified table for the given prefix. You will receive all the events for the given prefix.

To unregister the watcher you need to call unwatch with the returned id.

Example
source

pub fn secondary_watch<T: SDBItem>( &self, key_def: impl KeyDefinition, key: Option<&[u8]> ) -> Result<(MpscReceiver<Event>, u64)>

Watches for changes in the specified table for the given secondary key. If the argument key is None you will receive all the events from the table. Otherwise you will receive only the events for the given secondary key.

To unregister the watcher you need to call unwatch with the returned id.

Example
source

pub fn secondary_watch_start_with<T: SDBItem>( &self, key_def: impl KeyDefinition, key_prefix: &[u8] ) -> Result<(MpscReceiver<Event>, u64)>

Watches for changes in the specified table for the given prefix. You will receive all the events for the given prefix.

To unregister the watcher you need to call unwatch with the returned id.

Example
  • Similar to primary_watch but with a secondary key and a prefix.
source

pub fn unwatch(&self, id: u64) -> Result<()>

Unwatch the given id. You can get the id from the return value of primary_watch. If the id is not valid anymore, this function will do nothing. If the id is valid, the corresponding watcher will be removed.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Db

§

impl Send for Db

§

impl Sync for Db

§

impl Unpin for Db

§

impl !UnwindSafe for Db

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, 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>,

§

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>,

§

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.