3 releases (breaking)

0.3.0 Oct 20, 2023
0.2.0 Sep 14, 2023
0.1.0 May 31, 2023

#1692 in Database interfaces

Download history 25/week @ 2023-12-17 25/week @ 2023-12-24 1/week @ 2023-12-31 16/week @ 2024-01-07 20/week @ 2024-01-14 12/week @ 2024-01-21 13/week @ 2024-01-28 18/week @ 2024-02-04 25/week @ 2024-02-11 39/week @ 2024-02-18 61/week @ 2024-02-25 35/week @ 2024-03-03 45/week @ 2024-03-10 59/week @ 2024-03-17 86/week @ 2024-03-24 98/week @ 2024-03-31

299 downloads per month
Used in 14 crates (via sov-db)

Apache-2.0

32KB
479 lines

Schema DB

This package is a low-level wrapper transforming RocksDB from a byte-oriented key value store into a type-oriented store. It's adapted from a similar package in Aptos-Core.

The most important concept exposed by Schema DB is a Schema, which maps a column-family name codec's for the key and value.

pub trait Schema  {
    /// The column family name associated with this struct.
    /// Note: all schemas within the same SchemaDB must have distinct column family names.
    const COLUMN_FAMILY_NAME: &'static str;

    /// Type of the key.
    type Key: KeyCodec<Self>;

    /// Type of the value.
    type Value: ValueCodec<Self>;
}

Using this schema, we can write generic functions for storing and fetching typed data, and ensure that it's always encoded/decoded in the way we expect.

impl SchemaDB {
	pub fn put<S: Schema>(&self, key: &impl KeyCodec<S>, value: &impl ValueCodec<S>) -> Result<()> {
		let key_bytes = key.encode_key()?;
        let value_bytes = value.encode_value()?;
		self.rocks_db_handle.put(S::COLUMN_FAMILY_NAME, key_bytes, value_bytes)
	}
}

To actually store and retrieve data, all we need to do is to implement a Schema:

pub struct AccountBalanceSchema;

impl Schema for AccountBalanceSchema {
	const COLUMN_FAMILY_NAME: &str = "account_balances";
	type Key = Account;
	type Value = u64;
}

impl KeyCodec<AccountBalanceSchema> for Account {
	fn encode_key(&self) -> Vec<u8> {
		bincode::to_vec(self)
	}

	fn decode_key(key: Vec<u8>) -> Self {
		// elided
	}
}

impl ValueCode<AccountBlanceSchema> for u64 {
	// elided
}

Dependencies

~25–33MB
~567K SLoC