Skip to main content

DbQuery

Struct DbQuery 

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

A cacheable database query descriptor.

The descriptor is deliberately explicit: callers choose the key, tags, and TTL that match their freshness model. An operation name is optional and used only for diagnostics. fetch_with executes the supplied loader only on a cache miss.

Implementations§

Source§

impl<T, C> DbQuery<T, C>
where C: CacheCodec,

Source

pub fn name(&self) -> Option<&str>

Return the optional diagnostic operation name.

Source

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

Set or replace the diagnostic operation name.

Source

pub fn namespace(&self) -> &str

Return the namespace used for physical cache keys.

Source

pub fn key_value(&self) -> Option<&str>

Return the logical key, if one has been configured.

Source

pub fn physical_key(&self) -> Option<String>

Return the physical cache key, including the adapter namespace.

Source

pub fn tags_value(&self) -> &[String]

Return the configured tags.

Source

pub fn ttl_value(&self) -> Option<Duration>

Return the configured per-entry TTL.

Source

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

Set the logical cache key for this query result.

Source

pub fn key_builder(self, key: CacheKeyBuilder) -> DbQuery<T, C>

Set the logical cache key from a segmented key builder.

Source

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

Set the logical key and add an entity invalidation tag.

for_entity("user", 42) sets the key to user:42 and adds the tag user:42. Both segments are escaped with CacheKeyBuilder, so : and % inside one segment cannot accidentally create extra key segments.

§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
    .cached::<User>()
    .tag("users")
    .for_entity("user", 42);

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

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

Set the logical key and tags from CacheEntity metadata.

This is the metadata-driven equivalent of DbQuery::for_entity. It preserves any existing tags, then adds the 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
    .cached::<User>()
    .tag("tenant:7")
    .for_cache_entity(42);

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

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

Add one invalidation tag.

Source

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

Add a collection invalidation tag from one escaped key segment.

Use this with DbCache::entity or DbQuery::for_entity when one entity result also belongs to a broader list or query group.

§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)
    .collection_tag("users:active");

assert_eq!(
    query.tags_value(),
    &["user:42".to_owned(), "users%3Aactive".to_owned()]
);
Source

pub fn tags<I, S>(self, tags: I) -> DbQuery<T, C>
where I: IntoIterator<Item = S>, S: Into<String>,

Add several invalidation tags.

Source

pub fn tag_set(self, tags: TagSet) -> DbQuery<T, C>

Replace invalidation tags from a reusable TagSet.

Source

pub fn ttl(self, ttl: Duration) -> DbQuery<T, C>

Set a per-entry TTL for this query result.

Source

pub async fn fetch_with<E, F, Fut>(self, loader: F) -> Result<T, DbCacheError>
where T: Serialize + DeserializeOwned + Send + 'static, E: Error + Send + Sync + 'static, F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<T, E>> + Send + 'static,

Fetch a cached value or run the supplied database loader on miss.

The loader is intentionally caller-supplied so the database library remains responsible for pools, transactions, compile-time checked queries, and row mapping. HydraCache owns only the cache boundary.

Source

pub async fn fetch_value_with<U, E, F, Fut>( self, loader: F, ) -> Result<U, DbCacheError>
where U: Serialize + DeserializeOwned + Send + 'static, E: Error + Send + Sync + 'static, F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<U, E>> + Send + 'static,

Fetch a cached value with an output type chosen by an adapter.

Most application code should use DbQuery::fetch_with. This method is intended for adapter crates that keep the descriptor type focused on a database row while caching shapes such as Option<T> or Vec<T>.

Trait Implementations§

Source§

impl<T, C> Clone for DbQuery<T, C>
where C: CacheCodec,

Source§

fn clone(&self) -> DbQuery<T, 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<T, C> Debug for DbQuery<T, C>
where C: CacheCodec,

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<T, C> SqlxQueryExt<T, C> for DbQuery<T, C>
where C: CacheCodec,

Source§

fn fetch_one<'q, 'async_trait, DB, A, E>( self, executor: E, query: QueryAs<'q, DB, T, A>, ) -> Pin<Box<dyn Future<Output = Result<T>> + Send + 'async_trait>>
where T: Serialize + DeserializeOwned + Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'static, DB: Database + Send + Sync + 'static + 'async_trait, A: IntoArguments<'q, DB> + Send + 'static + 'async_trait, E: Send + Sync + 'static + 'async_trait, for<'c> &'c E: Executor<'c, Database = DB>, Self: 'async_trait, 'q: 'static + 'async_trait,

Execute a SQLx query on miss and cache exactly one row.
Source§

fn fetch_optional<'q, 'async_trait, DB, A, E>( self, executor: E, query: QueryAs<'q, DB, T, A>, ) -> Pin<Box<dyn Future<Output = Result<Option<T>>> + Send + 'async_trait>>
where T: Serialize + DeserializeOwned + Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'static, DB: Database + Send + Sync + 'static + 'async_trait, A: IntoArguments<'q, DB> + Send + 'static + 'async_trait, E: Send + Sync + 'static + 'async_trait, for<'c> &'c E: Executor<'c, Database = DB>, Self: 'async_trait, 'q: 'static + 'async_trait,

Execute a SQLx query on miss and cache either one row or None.
Source§

fn fetch_all<'q, 'async_trait, DB, A, E>( self, executor: E, query: QueryAs<'q, DB, T, A>, ) -> Pin<Box<dyn Future<Output = Result<Vec<T>>> + Send + 'async_trait>>
where T: Serialize + DeserializeOwned + Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'static, DB: Database + Send + Sync + 'static + 'async_trait, A: IntoArguments<'q, DB> + Send + 'static + 'async_trait, E: Send + Sync + 'static + 'async_trait, for<'c> &'c E: Executor<'c, Database = DB>, Self: 'async_trait, 'q: 'static + 'async_trait,

Execute a SQLx query on miss and cache all returned rows.

Auto Trait Implementations§

§

impl<T, C> Freeze for DbQuery<T, C>

§

impl<T, C = PostcardCodec> !RefUnwindSafe for DbQuery<T, C>

§

impl<T, C> Send for DbQuery<T, C>

§

impl<T, C> Sync for DbQuery<T, C>

§

impl<T, C> Unpin for DbQuery<T, C>

§

impl<T, C> UnsafeUnpin for DbQuery<T, C>

§

impl<T, C = PostcardCodec> !UnwindSafe for DbQuery<T, 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