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
impl Db
sourcepub fn create(path: impl AsRef<Path>) -> Result<Self>
pub fn create(path: impl AsRef<Path>) -> Result<Self>
Creates a new Db instance using the given path.
sourcepub fn create_tmp(path: impl AsRef<Path>) -> Result<Self>
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.
sourcepub fn open(path: impl AsRef<Path>) -> Result<Self>
pub fn open(path: impl AsRef<Path>) -> Result<Self>
Opens an existing Db instance using the given path.
sourcepub fn open_tmp(path: impl AsRef<Path>) -> Result<Self>
pub fn open_tmp(path: impl AsRef<Path>) -> Result<Self>
Opens an existing Db instance using a temporary directory with the given path.
sourcepub fn define<T: SDBItem>(&mut self)
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
impl Db
sourcepub fn transaction(&self) -> Result<Transaction<'_>>
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
}sourcepub fn read_transaction(&self) -> Result<ReadOnlyTransaction<'_>>
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
impl Db
sourcepub fn primary_watch<T: SDBItem>(
&self,
key: Option<&[u8]>
) -> Result<(MpscReceiver<Event>, u64)>
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:
std::sync::mpsc::Receiverby defaulttokio::sync::mpsc::UnboundedReceiverwith the feature (async_tokio).
To unregister the watcher you need to call unwatch
with the returned id.
Get data from the event, use inner() method on:
watch::Insert::innerwatch::Update::inner_newto get the updated datawatch::Update::inner_oldto get the old datawatch::Delete::inner
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));
}
}
}sourcepub fn primary_watch_start_with<T: SDBItem>(
&self,
key_prefix: &[u8]
) -> Result<(MpscReceiver<Event>, u64)>
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
- Similar to
primary_watchbut with a prefix.
sourcepub fn secondary_watch<T: SDBItem>(
&self,
key_def: impl KeyDefinition,
key: Option<&[u8]>
) -> Result<(MpscReceiver<Event>, u64)>
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
- Similar to
primary_watchbut with a secondary key.
sourcepub fn secondary_watch_start_with<T: SDBItem>(
&self,
key_def: impl KeyDefinition,
key_prefix: &[u8]
) -> Result<(MpscReceiver<Event>, u64)>
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_watchbut with a secondary key and a prefix.