Database

Struct Database 

Source
pub struct Database { /* private fields */ }
Expand description

The main database handle

This is a thread-safe, cloneable handle to the underlying RocksDB instance. All operations are synchronous and fast - no async overhead.

§Thread Safety

The database uses RocksDB’s multi-threaded column family mode, making it safe to use concurrently from multiple threads without additional synchronization.

§Examples

use ngdb::{Database, DatabaseConfig, Storable};
use borsh::{BorshSerialize, BorshDeserialize};

#[derive(BorshSerialize, BorshDeserialize)]
struct User {
    id: u64,
    name: String,
}

impl Storable for User {
    type Key = u64;
    fn key(&self) -> Self::Key {
        self.id
    }
}

fn main() -> Result<(), ngdb::Error> {
    let db = DatabaseConfig::new("./data")
        .create_if_missing(true)
        .open()?;

    let users = db.collection::<User>("users")?;
    let user = User { id: 1, name: "Alice".to_string() };
    users.put(&user)?;

    Ok(())
}

Implementations§

Source§

impl Database

Source

pub fn collection<T: Storable>(&self, name: &str) -> Result<Collection<T>>

Get a typed collection for storing and retrieving values

Collections are backed by RocksDB column families and provide type-safe access to your data.

§Arguments
  • name - The name of the column family
§Errors

Returns an error if the column family doesn’t exist. Make sure to declare all column families in DatabaseConfig::add_column_family() before opening.

§Examples
let users = db.collection::<User>("users")?;
Source

pub fn list_collections(&self) -> Result<Vec<String>>

List all column families in the database

Returns a list of all collection names (column families) in the database.

§Errors

Returns an error if the database has been shut down or if listing fails.

Source

pub fn flush(&self) -> Result<()>

Flush all memtables to disk

This forces all in-memory data to be written to SST files.

Source

pub fn compact_all(&self) -> Result<()>

Compact all data in the database

This will trigger compaction across all column families.

Source

pub fn backup<P: AsRef<Path>>(&self, backup_path: P) -> Result<()>

Create a backup of the database

§Arguments
  • backup_path - Directory where the backup will be stored
Source

pub fn restore_from_backup<P: AsRef<Path>>( backup_path: P, restore_path: P, ) -> Result<()>

Restore database from a backup

§Arguments
  • backup_path - Directory containing the backup
  • restore_path - Directory where the database will be restored
Source

pub fn list_backups<P: AsRef<Path>>(backup_path: P) -> Result<Vec<BackupInfo>>

List all available backups

Source

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

Create a new transaction for atomic operations

Transactions allow you to group multiple operations and commit them atomically. All writes in a transaction are buffered in memory until commit.

§Examples
let txn = db.transaction()?;
let accounts = txn.collection::<Account>("accounts")?;

accounts.put(&Account { id: 1, balance: 100 })?;
accounts.put(&Account { id: 2, balance: 200 })?;

txn.commit()?;
Source

pub fn shutdown(&self) -> Result<()>

Gracefully shut down the database

Flushes all memtables, marks the database as shut down, and prevents new operations. After calling this, all subsequent operations will fail.

This acquires a write lock, which will block until all ongoing operations (which hold read locks) complete. This eliminates the TOCTOU race condition.

If flushing fails, the database will NOT be marked as shut down, allowing operations to continue or shutdown to be retried.

Trait Implementations§

Source§

impl Clone for Database

Source§

fn clone(&self) -> Database

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Send for Database

Source§

impl Sync for Database

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more