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
    .entity::<User>("user", 42)
    // Later, invalidate_tag("user:42") removes this result.
    .collection_tag("users")
    .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 cached_with<T>(&self, policy: QueryCachePolicy) -> DbQuery<T, C>

Start describing a cacheable database-loaded value with a reusable QueryCachePolicy.

This is useful when the same key/tag/TTL pattern is shared by a repository method, a SQLx call site, and a future ORM adapter.

Source

pub fn entity<T>(&self, kind: impl ToString, id: impl ToString) -> DbQuery<T, C>

Start describing an entity-shaped cached value.

This is a convenience layer over DbCache::cached that sets both the logical key and the entity invalidation tag from escaped key segments. For example, entity::<User>("user", 42) creates key user:42 and tag user:42; with namespace db, the physical cache key is db:user:42.

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

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

let queries = DbCache::new(HydraCache::local().build(), "db");
let query = queries.entity::<User>("user", 42);

assert_eq!(query.key_value(), Some("user:42"));
assert_eq!(query.tags_value(), &["user:42".to_owned()]);
assert_eq!(query.physical_key(), Some("db:user:42".to_owned()));
Source

pub fn for_entity<T>(&self, id: <T as CacheEntity>::Id) -> DbQuery<T, C>
where T: CacheEntity,

Start describing an entity-shaped cached value from CacheEntity metadata.

This helper removes repeated entity and collection literals from call sites. It sets the logical key, entity tag, and optional collection tag defined by T.

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

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

impl CacheEntity for User {
    type Id = i64;

    const ENTITY: &'static str = "user";
    const COLLECTION: Option<&'static str> = Some("users");
}

let queries = DbCache::new(HydraCache::local().build(), "db");
let query = queries.for_entity::<User>(42);

assert_eq!(query.key_value(), Some("user:42"));
assert_eq!(
    query.tags_value(),
    &["user:42".to_owned(), "users".to_owned()]
);
Source

pub fn collection<T>(&self, name: impl ToString) -> DbQuery<T, C>

Start describing a collection-shaped cached value.

This sets both the logical key and the collection invalidation tag to the escaped collection name. For example, collection::<User>("users") creates key users and tag users.

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

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

let queries = DbCache::new(HydraCache::local().build(), "db");
let query = queries.collection::<User>("users:active");

assert_eq!(query.key_value(), Some("users%3Aactive"));
assert_eq!(query.tags_value(), &["users%3Aactive".to_owned()]);
assert_eq!(query.physical_key(), Some("db:users%3Aactive".to_owned()));
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 = PostcardCodec> !RefUnwindSafe for DbCache<C>

§

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

§

impl<C> Freeze 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>

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