Expand description
MacroDB
This crate exports a macro that can be used to turn an appropriate Rust struct into an in-memory database that guarantees consistency and supports indices. The Rust struct needs to be written by hand, the macro only generates a safe interface for using the in-memory database.
Example
Here is a full example of building a user database. An error type is defined, that is used by the database methods to return information failures. A struct for the record type that is to be stored is defined (the User struct). Finally, a struct for the database is defined that contains two indices. The table macro generates methods for inserting, updating and deleting rows.
use std::collections::{BTreeMap, BTreeSet};
use macrodb::table;
/// Error type for database interactions.
pub enum Error {
UserIdExists,
UserEmailExists,
UserNotFound,
}
type UserId = u64;
/// Record type for a user (a row in the database).
#[derive(Clone)]
pub struct User {
id: UserId,
name: String,
email: String,
}
/// Database definition.
pub struct Database {
/// Users table.
users: BTreeMap<UserId, User>,
/// Unique index of users by email.
user_by_email: BTreeMap<String, UserId>,
}
// The table macro will autogenerate the users_insert(), users_update() and users_delete()
// methods.
impl Database {
table!(
users: User,
id: UserId,
missing Error => Error::UserNotFound,
primary users id => Error::UserIdExists,
unique user_by_email email => Error::UserEmailExists
);
}
See the documentation on table for more information.