Struct bonsaidb::local::Storage

pub struct Storage { /* private fields */ }
Expand description

A file-based, multi-database, multi-user database engine. This type blocks the current thread when used. See AsyncStorage for this type’s async counterpart.

Converting between Blocking and Async Types

AsyncStorage and Storage can be converted to and from each other using:

Converting from Database::open to Storage::open

Database::open is a simple method that uses Storage to create a database named default with the schema provided. These two ways of opening the database are the same:

// `bonsaidb_core` is re-exported to `bonsaidb::core` or `bonsaidb_local::core`.
use bonsaidb_core::connection::StorageConnection;
use bonsaidb_core::schema::Schema;
// `bonsaidb_local` is re-exported to `bonsaidb::local` if using the omnibus crate.
use bonsaidb_local::{
    config::{Builder, StorageConfiguration},
    Database, Storage,
};
// This creates a Storage instance, creates a database, and returns it.
let db = Database::open::<MySchema>(StorageConfiguration::new("my-db.bonsaidb"))?;

// This is the equivalent code being executed:
let storage =
    Storage::open(StorageConfiguration::new("my-db.bonsaidb").with_schema::<MySchema>()?)?;
storage.create_database::<MySchema>("default", true)?;
let db = storage.database::<MySchema>("default")?;

Using multiple databases

This example shows how to use Storage to create and use multiple databases with multiple schemas:

use bonsaidb_core::connection::StorageConnection;
use bonsaidb_core::schema::{Collection, Schema};
use bonsaidb_local::config::{Builder, StorageConfiguration};
use bonsaidb_local::Storage;
use serde::{Deserialize, Serialize};

#[derive(Debug, Schema)]
#[schema(name = "my-schema", collections = [BlogPost, Author])]
struct MySchema;

#[derive(Debug, Serialize, Deserialize, Collection)]
#[collection(name = "blog-posts")]
struct BlogPost {
    pub title: String,
    pub contents: String,
    pub author_id: u64,
}

#[derive(Debug, Serialize, Deserialize, Collection)]
#[collection(name = "blog-posts")]
struct Author {
    pub name: String,
}

let storage = Storage::open(
    StorageConfiguration::new("my-db.bonsaidb")
        .with_schema::<BlogPost>()?
        .with_schema::<MySchema>()?,
)?;

storage.create_database::<BlogPost>("ectons-blog", true)?;
let ectons_blog = storage.database::<BlogPost>("ectons-blog")?;
storage.create_database::<MySchema>("another-db", true)?;
let another_db = storage.database::<MySchema>("another-db")?;

Implementations§

§

impl Storage

pub fn backup<L>(&self, location: &L) -> Result<(), Error>where L: AnyBackupLocation,

Stores a copy of all data in this instance to location.

pub fn restore<L>(&self, location: &L) -> Result<(), Error>where L: AnyBackupLocation,

Restores all data from a previously stored backup location.

§

impl Storage

pub fn open(configuration: StorageConfiguration) -> Result<Storage, Error>

Creates or opens a multi-database Storage with its data stored in directory.

pub fn unique_id(&self) -> StorageId

Returns the unique id of the server.

This value is set from the StorageConfiguration or randomly generated when creating a server. It shouldn’t be changed after a server is in use, as doing can cause issues. For example, the vault that manages encrypted storage uses the server ID to store the vault key. If the server ID changes, the vault key storage will need to be updated with the new server ID.

pub fn register_schema<DB>(&self) -> Result<(), Error>where DB: Schema,

Registers a schema for use within the server.

pub fn with_effective_permissions( &self, effective_permissions: Permissions ) -> Option<Storage>

Restricts an unauthenticated instance to having effective_permissions. Returns None if a session has already been established.

pub fn into_async(self) -> AsyncStorage

Converts this instance into its blocking version, which is able to be used without async. The returned instance uses the current Tokio runtime handle to spawn blocking tasks.

Panics

Panics if called outside the context of a Tokio runtime.

pub fn into_async_with_runtime(self, runtime: Handle) -> AsyncStorage

Converts this instance into its blocking version, which is able to be used without async. The returned instance uses the provided runtime handle to spawn blocking tasks.

pub fn to_async(&self) -> AsyncStorage

Converts this instance into its blocking version, which is able to be used without async. The returned instance uses the current Tokio runtime handle to spawn blocking tasks.

Panics

Panics if called outside the context of a Tokio runtime.

pub fn to_async_with_runtime(&self, runtime: Handle) -> AsyncStorage

Converts this instance into its blocking version, which is able to be used without async. The returned instance uses the provided runtime handle to spawn blocking tasks.

Trait Implementations§

§

impl Clone for Storage

§

fn clone(&self) -> Storage

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
§

impl Debug for Storage

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'a> From<&'a AsyncStorage> for Storage

§

fn from(storage: &'a AsyncStorage) -> Storage

Converts to this type from the input type.
source§

impl<'a, B> From<&'a CustomServer<B>> for Storagewhere B: Backend,

source§

fn from(server: &'a CustomServer<B>) -> Storage

Converts to this type from the input type.
§

impl From<AsyncStorage> for Storage

§

fn from(storage: AsyncStorage) -> Storage

Converts to this type from the input type.
source§

impl<B> From<CustomServer<B>> for Storagewhere B: Backend,

source§

fn from(server: CustomServer<B>) -> Storage

Converts to this type from the input type.
§

impl From<StorageInstance> for Storage

§

fn from(instance: StorageInstance) -> Storage

Converts to this type from the input type.
§

impl HasSession for Storage

§

fn session(&self) -> Option<&Session>

Returns the currently authenticated session, if any.
§

fn allowed_to<'a, R, P>(&self, resource_name: R, action: &P) -> boolwhere R: AsRef<[Identifier<'a>]>, P: Action,

Checks if action is permitted against resource_name.
§

fn check_permission<'a, R, P>( &self, resource_name: R, action: &P ) -> Result<(), Error>where R: AsRef<[Identifier<'a>]>, P: Action,

Checks if action is permitted against resource_name. If permission is denied, returns a PermissionDenied error.
§

impl StorageConnection for Storage

§

type Authenticated = Storage

The StorageConnection type returned from authentication calls.
§

type Database = Database

The type that represents a database for this implementation.
§

fn admin(&self) -> <Storage as StorageConnection>::Database

Returns the administration database.
§

fn create_database_with_schema( &self, name: &str, schema: SchemaName, only_if_needed: bool ) -> Result<(), Error>

Creates a database named name using the SchemaName schema. Read more
§

fn database<DB>( &self, name: &str ) -> Result<<Storage as StorageConnection>::Database, Error>where DB: Schema,

Returns a reference to database name with schema DB.
§

fn delete_database(&self, name: &str) -> Result<(), Error>

Deletes a database named name. Read more
§

fn list_databases(&self) -> Result<Vec<Database, Global>, Error>

Lists the databases in this storage.
§

fn list_available_schemas(&self) -> Result<Vec<SchemaSummary, Global>, Error>

Lists the SchemaNames registered with this storage.
§

fn create_user(&self, username: &str) -> Result<u64, Error>

Creates a user.
§

fn delete_user<'user, U>(&self, user: U) -> Result<(), Error>where U: Nameable<'user, u64> + Send + Sync,

Deletes a user.
§

fn set_user_password<'user, U>( &self, user: U, password: SensitiveString ) -> Result<(), Error>where U: Nameable<'user, u64> + Send + Sync,

Sets a user’s password.
§

fn authenticate(&self, authentication: Authentication) -> Result<Storage, Error>

Authenticates using the active session, returning a connection with a new session upon success. The existing connection will remain usable with the existing authentication, if any.
§

fn assume_identity( &self, identity: IdentityReference<'_> ) -> Result<<Storage as StorageConnection>::Authenticated, Error>

Assumes the identity. If successful, the returned instance will have the permissions from identity.
§

fn add_permission_group_to_user<'user, 'group, U, G>( &self, user: U, permission_group: G ) -> Result<(), Error>where U: Nameable<'user, u64> + Send + Sync, G: Nameable<'group, u64> + Send + Sync,

Adds a user to a permission group.
§

fn remove_permission_group_from_user<'user, 'group, U, G>( &self, user: U, permission_group: G ) -> Result<(), Error>where U: Nameable<'user, u64> + Send + Sync, G: Nameable<'group, u64> + Send + Sync,

Removes a user from a permission group.
§

fn add_role_to_user<'user, 'group, U, G>( &self, user: U, role: G ) -> Result<(), Error>where U: Nameable<'user, u64> + Send + Sync, G: Nameable<'group, u64> + Send + Sync,

Adds a user to a permission group.
§

fn remove_role_from_user<'user, 'group, U, G>( &self, user: U, role: G ) -> Result<(), Error>where U: Nameable<'user, u64> + Send + Sync, G: Nameable<'group, u64> + Send + Sync,

Removes a user from a permission group.
§

fn create_database<DB>( &self, name: &str, only_if_needed: bool ) -> Result<Self::Database, Error>where DB: Schema,

Creates a database named name with the Schema provided. Read more
§

fn authenticate_with_token( &self, id: u64, token: &SensitiveString ) -> Result<<Self::Authenticated as StorageConnection>::Authenticated, Error>

Authenticates using an AuthenticationToken. If successful, the returned instance will have the permissions from identity.
§

fn authenticate_with_password<'name, User>( &self, user: User, password: SensitiveString ) -> Result<Self::Authenticated, Error>where User: Nameable<'name, u64>,

Authenticates a User using a password. If successful, the returned instance will have the permissions from identity.
§

impl StorageNonBlocking for Storage

§

fn path(&self) -> &Path

Returns the path of the database storage.
§

fn assume_session(&self, session: Session) -> Result<Storage, Error>

Returns a new instance of Storage with session as the effective authentication session. This call will only succeed if there is no current session.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32 ) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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> 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 Twhere 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> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere T: Clone,

§

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 Twhere 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 Twhere 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.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

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