Skip to main content

hydracache_sqlx/
lib.rs

1//! SQLx-facing integration crate for HydraCache database result caching.
2//!
3//! The database-neutral query cache API lives in `hydracache-db`. This crate
4//! keeps SQLx users on a convenient import path while avoiding a hard conceptual
5//! dependency between the generic adapter and SQLx itself.
6//!
7//! # Example
8//!
9//! ```no_run
10//! use hydracache::HydraCache;
11//! use hydracache_sqlx::{DbCache, HydraCacheEntity, PreparedQueryPolicy, SqlxQueryExt};
12//!
13//! #[derive(serde::Serialize, serde::Deserialize, HydraCacheEntity)]
14//! #[hydracache(entity = "user", collection = "users", id = i64)]
15//! struct User {
16//!     id: i64,
17//!     name: String,
18//! }
19//!
20//! # async fn example(pool: sqlx::PgPool) -> hydracache_sqlx::Result<()> {
21//! let local = HydraCache::local().build();
22//!
23//! // SQLx users may import DbCache from this crate, but the type itself is
24//! // database-neutral and comes from hydracache-db.
25//! let queries = DbCache::new(local, "db");
26//!
27//! let user: User = queries
28//!     .for_entity::<User>(42)
29//!     .fetch_with(move || async move {
30//!         let (id, name): (i64, String) =
31//!             sqlx::query_as("select id, name from users where id = $1")
32//!                 .bind(42_i64)
33//!                 .fetch_one(&pool)
34//!                 .await?;
35//!
36//!         Ok::<_, sqlx::Error>(User { id, name })
37//!     })
38//!     .await?;
39//!
40//! assert_eq!(user.id, 42);
41//! assert!(!user.name.is_empty());
42//! # Ok(())
43//! # }
44//! ```
45//!
46//! Prepared policies keep repeated repository methods cheap while still using
47//! ordinary SQLx query execution on cache misses:
48//!
49//! ```no_run
50//! use hydracache::HydraCache;
51//! use hydracache_sqlx::{DbCache, HydraCacheEntity, PreparedQueryPolicy, SqlxQueryExt};
52//!
53//! #[derive(serde::Serialize, serde::Deserialize, HydraCacheEntity)]
54//! #[hydracache(entity = "user", collection = "users", id = i64)]
55//! struct User {
56//!     id: i64,
57//!     name: String,
58//! }
59//!
60//! # async fn example(pool: sqlx::PgPool) -> hydracache_sqlx::Result<()> {
61//! let queries = DbCache::new(HydraCache::local().build(), "db");
62//! let load_user = queries.prepare::<(i64, String)>(
63//!     PreparedQueryPolicy::for_cache_entity::<User>().with_name("load-user"),
64//! );
65//!
66//! let (id, name) = load_user
67//!     .for_id(42)
68//!     .sqlx_one(
69//!         pool.clone(),
70//!         sqlx::query_as("select id, name from users where id = $1").bind(42_i64),
71//!     )
72//!     .await?;
73//!
74//! assert_eq!(id, 42);
75//! assert!(!name.is_empty());
76//! # Ok(())
77//! # }
78//! ```
79//!
80//! Use [`DbQuery::fetch_with`] when you need SQLx macros, transactions, or a
81//! repository function instead of a pool-like executor.
82//!
83//! [`QueryCachePolicy`] and [`PreparedQueryPolicy`] are also re-exported for
84//! SQLx users, but the policy types are database-neutral and live in
85//! `hydracache-db`.
86//! [`query_cache_policy!`] is re-exported for the same convenience.
87
88extern crate self as hydracache_sqlx;
89
90mod error;
91mod query_ext;
92
93pub use error::{Result, SqlxCacheError};
94pub use hydracache_db::{
95    query_cache_policy, CacheEntity, DbCache, DbCacheError, DbQuery, HydraCacheEntity,
96    PreparedDbQuery, PreparedQueryPolicy, QueryCachePolicy, RefreshPolicy, Result as DbResult,
97};
98pub use query_ext::SqlxQueryExt;
99
100/// SQLx-specific compatibility name for [`DbCache`].
101pub type SqlxCache<C = hydracache::PostcardCodec> = DbCache<C>;
102
103/// SQLx-specific compatibility name for [`DbQuery`].
104pub type SqlxQuery<T, C = hydracache::PostcardCodec> = DbQuery<T, C>;
105
106/// Re-export the SQLx crate used by this adapter.
107///
108/// This lets downstream users keep one adapter-aligned SQLx version in examples
109/// and integration code without hiding SQLx behind HydraCache abstractions.
110pub use sqlx;
111
112#[cfg(test)]
113mod tests {
114    use hydracache::HydraCache;
115    use serde::{Deserialize, Serialize};
116    use sqlx::postgres::PgPoolOptions;
117
118    use crate::{
119        DbCache, PreparedQueryPolicy, QueryCachePolicy, RefreshPolicy, SqlxCache, SqlxQueryExt,
120    };
121
122    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123    struct User {
124        id: u64,
125    }
126
127    #[tokio::test]
128    async fn sqlx_cache_alias_matches_database_cache_api() {
129        let query = SqlxCache::new(HydraCache::local().build(), "sqlx")
130            .cached::<User>()
131            .key("user:1");
132
133        assert_eq!(query.physical_key(), Some("sqlx:user:1".to_owned()));
134    }
135
136    #[tokio::test]
137    async fn db_cache_reexport_is_available_from_sqlx_crate() {
138        let query = DbCache::new(HydraCache::local().build(), "db")
139            .cached::<User>()
140            .key("user:1");
141
142        assert_eq!(query.physical_key(), Some("db:user:1".to_owned()));
143    }
144
145    #[tokio::test]
146    async fn query_cache_policy_reexport_is_available_from_sqlx_crate() {
147        let refresh =
148            RefreshPolicy::new().stale_while_revalidate(std::time::Duration::from_secs(5));
149        let policy = QueryCachePolicy::new()
150            .key("user:1")
151            .tag("user:1")
152            .refresh_policy(refresh);
153        let query = DbCache::new(HydraCache::local().build(), "db").cached_with::<User>(policy);
154
155        assert_eq!(query.physical_key(), Some("db:user:1".to_owned()));
156        assert_eq!(query.tags_value(), &["user:1".to_owned()]);
157        assert_eq!(query.refresh_policy_value(), Some(refresh));
158    }
159
160    #[tokio::test]
161    async fn prepared_query_policy_reexport_is_available_from_sqlx_crate() {
162        let prepared = DbCache::new(HydraCache::local().build(), "db").prepare::<User>(
163            PreparedQueryPolicy::for_entity("user")
164                .with_name("load-user")
165                .collection_tag("users"),
166        );
167
168        let query = prepared.for_id(1);
169        assert_eq!(query.name(), Some("load-user"));
170        assert_eq!(query.physical_key(), Some("db:user:1".to_owned()));
171        assert_eq!(
172            query.tags_value(),
173            &["users".to_owned(), "user:1".to_owned()]
174        );
175    }
176
177    #[tokio::test]
178    async fn sqlx_helper_missing_key_returns_sqlx_cache_error() {
179        let pool = PgPoolOptions::new()
180            .connect_lazy("postgres://postgres:postgres@localhost/postgres")
181            .unwrap();
182
183        let result = DbCache::new(HydraCache::local().build(), "db")
184            .cached::<(i64,)>()
185            .sqlx_one(pool, sqlx::query_as("select 1"))
186            .await;
187
188        let error = result.unwrap_err();
189        assert_eq!(
190            error.to_string(),
191            "database cached operation `db:unnamed` is missing an explicit cache key"
192        );
193    }
194
195    #[tokio::test]
196    async fn sqlx_cache_error_wraps_db_cache_errors() {
197        let error = hydracache_db::DbCacheError::MissingKey {
198            operation: "load-user".to_owned(),
199        };
200        let error = crate::SqlxCacheError::from(error);
201
202        assert_eq!(
203            error.to_string(),
204            "database cached operation `load-user` is missing an explicit cache key"
205        );
206    }
207}