Struct kyval::Kyval

source ·
pub struct Kyval { /* private fields */ }
Expand description

Key-Value Store Interface

Provides an synchronous interface to a key-value store. This implementation allows for setting, getting, removing, and clearing key-value pairs in a datastore with an optional Time-to-Live (TTL) for keys.

The Kyval struct is generic over any implementation of the Store trait, thus can be backed by various storage engines.

§Examples

§Create a new instance with in-memory store

let kyval = Kyval::default();

§Set and get a value

let kyval = Kyval::default();

kyval.set("array", vec!["hola", "test"]).unwrap();

match kyval.get("array").unwrap() {
    Some(array) => {
        let array: Vec<String> = serde_json::from_value(array).unwrap();
        assert_eq!(array, vec!["hola".to_string(), "test".to_string()])
    }
    None => assert!(false),
}

kyval.set("string", "life long").unwrap();
match kyval.get("string").unwrap() {
    Some(string) => {
        let string: String = serde_json::from_value(string).unwrap();
        assert_eq!(string, "life long");
    }
    None => assert!(false),
}

Implementations§

source§

impl Kyval

source

pub async fn try_new<S: Store + 'static>(store: S) -> Result<Self, KyvalError>

Attempts to create a new Kyval instance with a custom store.

This function will attempt to initialize the provided store. If the initialization is successful, a new Kyval instance is returned.

§Arguments
  • store - A custom store implementing the Store trait.
§Errors

Returns KyvalError if the store fails to initialize.

§Examples

let store = KyvalStoreBuilder::new()
    .uri(":memory:")
    .table_name("custom_table_name")
    .build()
    .unwrap();

let kyval = Kyval::try_new(store).unwrap();
source

pub async fn set<T: Serialize>( &self, key: &str, value: T, ) -> Result<Option<StoreModel>, KyvalError>

Sets a value for a given key without a TTL.

§Arguments
  • key - The key under which the value is stored.
  • value - The value to store. Must implement Serialize.
§Errors

Returns KyvalError if the operation fails.

§Examples
let kyval = Kyval::default();
kyval.set("key", "hello world").unwrap();
source

pub async fn set_with_ttl<T: Serialize>( &self, key: &str, value: T, ttl: u64, ) -> Result<Option<StoreModel>, KyvalError>

Sets a value for a given key with an expiry TTL (Time-To-Live).

§Arguments
  • key - A string slice that holds the key.
  • value - The value to be stored, which must implement Serialize.
  • ttl - The time-to-live (in seconds) for the key-value pair.
§Returns

Returns an Ok result on successful insertion, or a KyvalError on failure.

§Examples
let kyval = Kyval::default();
kyval.set_with_ttl("temp_key", "temp_value", 3600).unwrap(); // Expires in 1 hour
source

pub async fn get(&self, key: &str) -> Result<Option<Value>, KyvalError>

Retrieves a value based on a key.

§Arguments
  • key - A string slice that holds the key to retrieve the value for.
§Returns

Returns an Ok result with Option<Value> on success, where None indicates the key does not exist, or a KyvalError on failure.

§Examples
let kyval = Kyval::default();

kyval.set("array", vec!["hola", "test"]).unwrap();

match kyval.get("array").unwrap() {
    Some(array) => {
        let array: Vec<String> = serde_json::from_value(array).unwrap();
        assert_eq!(array, vec!["hola".to_string(), "test".to_string()])
    }
    None => assert!(false),
}

kyval.set("string", "life long").unwrap();
match kyval.get("string").unwrap() {
    Some(string) => {
        let string: String = serde_json::from_value(string).unwrap();
        assert_eq!(string, "life long");
    }
    None => assert!(false),
}
source

pub async fn list(&self) -> Result<Vec<StoreModel>, KyvalError>

Lists all key-value pairs stored in the Kyval store.

§Returns

Returns a Result containing a Vec of tuples, where each tuple contains the key (as a String) and the corresponding value (as a Value). If an error occurs, a KyvalError is returned.

§Examples
let kyval = Kyval::default();
let pairs = kyval.list().await.unwrap();
for (key, value) in pairs {
    println!("Key: {}, Value: {}", key, value);
}
source

pub async fn remove(&self, key: &str) -> Result<(), KyvalError>

Removes a specified key from the store.

§Arguments
  • key - A string slice that represents the key to be removed.
§Returns

Returns an Ok result if the key has been successfully removed, or a KyvalError on failure.

§Examples
let kyval = Kyval::default();
kyval.remove("my_key").unwrap(); // Removes "my_key" from the store
source

pub async fn remove_many<T: AsRef<str> + Sync>( &self, keys: &[T], ) -> Result<(), KyvalError>

Removes multiple keys from the store in one operation.

§Arguments
  • keys - A slice of strings or string-like objects that represent the keys to be removed.
§Returns

Returns an Ok result if the keys have been successfully removed, or a KyvalError on failure.

§Examples
let kyval = Kyval::default();
kyval.remove_many(&["key1", "key2"]).unwrap(); // Removes "key1" and "key2"
source

pub async fn clear(&self) -> Result<(), KyvalError>

Clears the entire store, removing all key-value pairs.

§Returns

Returns an Ok result if the store has been successfully cleared, or a KyvalError on failure.

§Examples
let kyval = Kyval::default();
kyval.clear().unwrap(); // Clears the entire store

Trait Implementations§

source§

impl Default for Kyval

Provides a default implementation for the Kyval struct, which creates an in-memory store. This is useful for quickly setting up a Kyval instance without needing to configure a specific storage backend.

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Kyval

§

impl !RefUnwindSafe for Kyval

§

impl Send for Kyval

§

impl Sync for Kyval

§

impl Unpin for Kyval

§

impl !UnwindSafe for Kyval

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> 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> IntoRequest<T> for T

source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where 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 T
where 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.
source§

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

source§

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