Trait ultra_batch::Fetcher

source ·
pub trait Fetcher {
    type Key: Clone + Hash + Eq + Send + Sync;
    type Value: Clone + Send + Sync;
    type Error: Display;

    // Required method
    fn fetch(
        &self,
        keys: &[Self::Key],
        values: &mut Cache<'_, Self::Key, Self::Value>
    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
}
Expand description

A trait for fetching values from some datastore in bulk. A Fetcher will be given an array of keys and should insert fetched values into a given cache. Implementing Fetcher will allow queries to be batched using a BatchFetcher. See the BatchFetcher docs for details about batching, caching, and error semantics.

§Examples

struct UserFetcher {
    db_conn: DbConnection,
}

impl Fetcher for UserFetcher {
    type Key = UserId;
    type Value = User;
    type Error = anyhow::Error;

    async fn fetch(&self, keys: &[UserId], values: &mut Cache<'_, UserId, User>) -> anyhow::Result<()> {
        let users = self.db_conn.get_users_by_ids(keys).await?;
        for user in users {
            values.insert(user.id, user);
        }
        Ok(())
    }
}

Required Associated Types§

source

type Key: Clone + Hash + Eq + Send + Sync

The type used to look up a single value in a batch.

source

type Value: Clone + Send + Sync

The type returned in a batch. Value is usually a single database record, but could also be a more sophisticated type, such as a Vec of values for a Fetcher that deals with one-to-many relationships.

source

type Error: Display

The error indicating that fetching a batch failed.

Required Methods§

source

fn fetch( &self, keys: &[Self::Key], values: &mut Cache<'_, Self::Key, Self::Value> ) -> impl Future<Output = Result<(), Self::Error>> + Send

Retrieve the values associated with the given keys, and insert them into values if found. If Ok(_) is returned, then any keys not inserted into values will be marked as “not found” (meaning any future attempts to retrieve them will fail). If Err(_) is returned, then the caller(s) waiting on the batch will receive a LoadError::FetchError with the message from the returned error (note that any values inserted into values before the Err(_) is returned will still be cached). See the BatchFetcher docs for more details.

Object Safety§

This trait is not object safe.

Implementors§