Skip to main content

DbCache

Struct DbCache 

Source
pub struct DbCache<C = PostcardCodec>
where C: CacheCodec,
{ /* private fields */ }
Expand description

A database-oriented view over a HydraCache instance.

DbCache groups query result keys under a namespace while keeping all cache storage, single-flight, tags, TTL, and stats in the shared local cache.

§Example

use std::time::Duration;

use hydracache::HydraCache;
use hydracache_db::DbCache;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct User {
    id: i64,
    name: String,
}

let local = HydraCache::local().build();
let queries = DbCache::new(local, "db");

let user = queries
    .cached::<User>()
    // Physical cache key: "db:user:42".
    .key("user:42")
    // Later, invalidate_tag("user:42") removes this result.
    .tag("user:42")
    .ttl(Duration::from_secs(60))
    .fetch_with(|| async {
        // Replace this block with code from sqlx, diesel, sea-orm, or any
        // other database client. It is called only when the cache does not
        // already contain "db:user:42" or when the cached value has expired.
        Ok::<_, std::io::Error>(User {
            id: 42,
            name: "Ada".to_owned(),
        })
    })
    .await?;

assert_eq!(user.id, 42);

Implementations§

Source§

impl<C> DbCache<C>
where C: CacheCodec,

Source

pub fn new(cache: HydraCache<C>, namespace: impl Into<String>) -> DbCache<C>

Create a database query cache adapter over an existing local cache.

Source

pub fn namespace(&self) -> &str

Return the namespace used for physical cache keys.

Source

pub fn cache(&self) -> &HydraCache<C>

Return the underlying local cache.

Source

pub fn cached<T>(&self) -> DbQuery<T, C>

Start describing a cacheable database-loaded value.

This is the preferred entry point when the query is already visible inside the fetch_with loader through a database client, ORM, or repository method.

Source

pub fn named<T>(&self, name: impl Into<String>) -> DbQuery<T, C>

Start describing a cacheable database-loaded value with a diagnostic name.

Source

pub fn query_as<T>(&self, sql: impl Into<String>) -> DbQuery<T, C>

Start describing a cacheable SQL query result.

Prefer DbCache::cached or DbCache::named when writing new code. This method remains useful if you want the SQL text itself to be the diagnostic label for errors and logs.

Trait Implementations§

Source§

impl<C> Clone for DbCache<C>
where C: CacheCodec,

Source§

fn clone(&self) -> DbCache<C>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<C> Debug for DbCache<C>
where C: CacheCodec,

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<C> Freeze for DbCache<C>

§

impl<C = PostcardCodec> !RefUnwindSafe for DbCache<C>

§

impl<C> Send for DbCache<C>

§

impl<C> Sync for DbCache<C>

§

impl<C> Unpin for DbCache<C>

§

impl<C> UnsafeUnpin for DbCache<C>

§

impl<C = PostcardCodec> !UnwindSafe for DbCache<C>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

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 T
where U: Into<T>,

Source§

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>,

Source§

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<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