Struct Tables

Source
pub struct Tables<'db, 'txn> { /* private fields */ }
Expand description

A collection of read-write tables. Read operation from ReadableTable and write operations insert, update, remove and migrate are available.

Implementations§

Source§

impl<'db, 'txn> Tables<'db, 'txn>

Source

pub fn insert<T: SDBItem>( &mut self, txn: &'txn Transaction<'db>, item: T, ) -> Result<()>

Insert data into the database.

Send a event::Insert event that you can receive using watch or others watch_* functions.

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

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

fn main() {
  let mut db = Db::create_tmp("my_db_t_insert").unwrap();
  // Initialize the table
  db.define::<Data>();
   
  // Insert a new data
  let mut txn = db.transaction().unwrap();
  {
     let mut tables = txn.tables();
     tables.insert(&txn, Data(1, "hello".to_string())).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit
}
Source

pub fn update<T: SDBItem>( &mut self, txn: &'txn Transaction<'db>, old_item: T, updated_item: T, ) -> Result<()>

Update data in the database.

Send a event::Update event that you can receive using watch or others watch_* functions.

§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_t_update").unwrap();
  // Initialize the table
  db.define::<Data>();
   
  // Insert a new data
  let mut txn = db.transaction().unwrap();
  {
    let mut tables = txn.tables();
    tables.insert(&txn, Data(1)).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit

  // Update the data, e.g: increment the value
  let mut txn = db.transaction().unwrap();
  {
      let mut tables = txn.tables();
      let old_data = tables.primary_get::<Data>(&txn, &1u32.to_be_bytes()).unwrap().unwrap();
      let new_data = Data(old_data.0 + 1);
      tables.update(&txn, old_data, new_data).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit

  // Get the updated data
  let mut txn = db.read_transaction().unwrap();
  let mut tables = txn.tables();
  let data:Data = tables.primary_get(&txn, &2u32.to_be_bytes()).unwrap().unwrap();
  assert_eq!(data, Data(2));
}
Source

pub fn remove<T: SDBItem>( &mut self, txn: &'txn Transaction<'db>, item: T, ) -> Result<()>

Remove data from the database.

Send a event::Delete event that you can receive using watch or others watch_* functions.

§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_t_remove").unwrap();
  // Initialize the table
  db.define::<Data>();
   
  // Insert a new data
  let mut txn = db.transaction().unwrap();
  {
     let mut tables = txn.tables();
     tables.insert(&txn, Data(1)).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit

  // Remove the data
  let mut txn = db.transaction().unwrap();
  {
     let mut tables = txn.tables();
     tables.remove(&txn, Data(1)).unwrap();
  }
  txn.commit().unwrap(); // /!\ Don't forget to commit

  // Get the removed data
  let mut txn = db.read_transaction().unwrap();
  let mut tables = txn.tables();
  let data:Option<Data> = tables.primary_get(&txn, &1u32.to_be_bytes()).unwrap();
  assert_eq!(data, None);
}
Source

pub fn migrate<OldType, NewType>( &mut self, txn: &'txn Transaction<'db>, ) -> Result<()>
where OldType: SDBItem + Clone, NewType: SDBItem + From<OldType>,

Migration from a type to another.

Not send any event.

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

type Data = DataV2;

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[struct_db(fn_primary_key(p_key))]
struct DataV1(u32);

impl DataV1 {
    pub fn p_key(&self) -> Vec<u8> {
        self.0.to_be_bytes().to_vec()
    }
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[struct_db(fn_primary_key(p_key))]
struct DataV2(String);

impl DataV2 {
    pub fn p_key(&self) -> Vec<u8> {
        self.0.as_bytes().to_vec()
    }
}

impl From<DataV1> for DataV2 {
    fn from(av1: DataV1) -> Self {
        Self(av1.0.to_string())
    }
}

fn main() {
  let mut db = Db::create_tmp("my_db_t_migration").unwrap();

  db.define::<DataV1>();
  db.define::<DataV2>();

  let data = DataV1(42);

  let txn = db.transaction().unwrap();
  {
    let mut tables = txn.tables();
    tables.insert(&txn, data).unwrap();
  }
  txn.commit().unwrap();

  // Migrate
  let txn = db.transaction().unwrap();
  {
    let mut tables = txn.tables();
    tables.migrate::<DataV1, DataV2>(&txn).unwrap();
  }
  txn.commit().unwrap();

  // Check migration
  let txn = db.read_transaction().unwrap();
  let mut tables = txn.tables();
  let data = tables.primary_get::<Data>(&txn, "42".as_bytes()).unwrap().unwrap();
  println!("migrated data: {:?}", data);
}

Trait Implementations§

Source§

impl<'db, 'txn> ReadableTable<'db, 'txn> for Tables<'db, 'txn>

Source§

type Table = Table<'db, 'txn, &'static [u8], &'static [u8]>

Source§

type Transaction<'x> = Transaction<'db>

Source§

fn open_table( &mut self, txn: &'txn Self::Transaction<'db>, table_name: &'static str, ) -> Result<()>

Source§

fn get_table(&self, table_name: &'static str) -> Option<&Self::Table>

Source§

fn primary_get<T: SDBItem>( &mut self, txn: &'txn Self::Transaction<'db>, key: &[u8], ) -> Result<Option<T>>

Get a value from the table. Returns Ok(None) if the key does not exist. Available in Tables and ReadOnlyTables. Read more
Source§

fn primary_iter<'a, T: SDBItem>( &'a mut self, txn: &'txn Self::Transaction<'db>, ) -> Result<PrimaryIterator<'_, 'txn, 'db, T>>
where 'db: 'a, 'txn: 'a,

Iterate over all the values of the table. Available in Tables and ReadOnlyTables. Read more
Source§

fn primary_iter_range<'a, 'b, T>( &'a mut self, txn: &'txn Self::Transaction<'db>, range_value: impl RangeBounds<&'a [u8]> + 'a, ) -> Result<PrimaryIterator<'_, 'txn, 'db, T>>
where T: SDBItem, 'db: 'a, 'txn: 'a,

Iterate over all the values of the table that are in the given range. Available in Tables and ReadOnlyTables. Read more
Source§

fn primary_iter_start_with<'a, T>( &'a mut self, txn: &'txn Self::Transaction<'db>, prefix_value: &'a [u8], ) -> Result<PrimaryIteratorStartWith<'_, 'txn, 'db, T>>
where T: SDBItem, 'db: 'a, 'txn: 'a,

Iterate over all the values of the table that start with the given prefix. Available in Tables and ReadOnlyTables. Read more
Source§

fn secondary_get<T: SDBItem>( &mut self, txn: &'txn Self::Transaction<'db>, key_def: impl KeyDefinition, key: &[u8], ) -> Result<Option<T>>

Get a value from the table using a secondary key. Returns Ok(None) if the key does not exist. Available in Tables and ReadOnlyTables. Read more
Source§

fn secondary_iter<'a, T: SDBItem>( &mut self, txn: &'txn Self::Transaction<'db>, key_def: impl KeyDefinition, ) -> Result<SecondaryIterator<'_, 'txn, 'db, T, Self::Table>>

Iterate over all the values of the table that start with the given prefix. Available in Tables and ReadOnlyTables. Read more
Source§

fn secondary_iter_range<'a, 'b, T>( &'a mut self, txn: &'txn Self::Transaction<'db>, key_def: impl KeyDefinition, range_key: impl RangeBounds<&'b [u8]> + 'b, ) -> Result<SecondaryIterator<'_, 'txn, 'db, T, Self::Table>>
where T: SDBItem, 'a: 'b,

Iterate over all the values of the table that start with the given prefix. Available in Tables and ReadOnlyTables. Read more
Source§

fn secondary_iter_start_with<'a, 'b, T>( &'a mut self, txn: &'txn Self::Transaction<'db>, key_def: impl KeyDefinition, key_prefix: &'b [u8], ) -> Result<SecondaryIteratorStartWith<'a, 'txn, 'db, T, Self::Table>>
where T: SDBItem, 'b: 'a,

Iterate over all the values of the table that start with the given prefix. Available in Tables and ReadOnlyTables. Read more
Source§

fn len<T: SDBItem>(&mut self, txn: &'txn Self::Transaction<'db>) -> Result<u64>

Returns the number of elements in the table. Available in Tables and ReadOnlyTables. Read more

Auto Trait Implementations§

§

impl<'db, 'txn> Freeze for Tables<'db, 'txn>

§

impl<'db, 'txn> !RefUnwindSafe for Tables<'db, 'txn>

§

impl<'db, 'txn> !Send for Tables<'db, 'txn>

§

impl<'db, 'txn> !Sync for Tables<'db, 'txn>

§

impl<'db, 'txn> Unpin for Tables<'db, 'txn>

§

impl<'db, 'txn> !UnwindSafe for Tables<'db, 'txn>

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

Source§

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

Source§

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.