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//!     .fetch_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, 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::{DbCache, PreparedQueryPolicy, QueryCachePolicy, SqlxCache, SqlxQueryExt};
119
120    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121    struct User {
122        id: u64,
123    }
124
125    #[tokio::test]
126    async fn sqlx_cache_alias_matches_database_cache_api() {
127        let query = SqlxCache::new(HydraCache::local().build(), "sqlx")
128            .cached::<User>()
129            .key("user:1");
130
131        assert_eq!(query.physical_key(), Some("sqlx:user:1".to_owned()));
132    }
133
134    #[tokio::test]
135    async fn db_cache_reexport_is_available_from_sqlx_crate() {
136        let query = DbCache::new(HydraCache::local().build(), "db")
137            .cached::<User>()
138            .key("user:1");
139
140        assert_eq!(query.physical_key(), Some("db:user:1".to_owned()));
141    }
142
143    #[tokio::test]
144    async fn query_cache_policy_reexport_is_available_from_sqlx_crate() {
145        let policy = QueryCachePolicy::new().key("user:1").tag("user:1");
146        let query = DbCache::new(HydraCache::local().build(), "db").cached_with::<User>(policy);
147
148        assert_eq!(query.physical_key(), Some("db:user:1".to_owned()));
149        assert_eq!(query.tags_value(), &["user:1".to_owned()]);
150    }
151
152    #[tokio::test]
153    async fn prepared_query_policy_reexport_is_available_from_sqlx_crate() {
154        let prepared = DbCache::new(HydraCache::local().build(), "db").prepare::<User>(
155            PreparedQueryPolicy::for_entity("user")
156                .with_name("load-user")
157                .collection_tag("users"),
158        );
159
160        let query = prepared.for_id(1);
161        assert_eq!(query.name(), Some("load-user"));
162        assert_eq!(query.physical_key(), Some("db:user:1".to_owned()));
163        assert_eq!(
164            query.tags_value(),
165            &["users".to_owned(), "user:1".to_owned()]
166        );
167    }
168
169    #[tokio::test]
170    async fn sqlx_helper_missing_key_returns_sqlx_cache_error() {
171        let pool = PgPoolOptions::new()
172            .connect_lazy("postgres://postgres:postgres@localhost/postgres")
173            .unwrap();
174
175        let result = DbCache::new(HydraCache::local().build(), "db")
176            .cached::<(i64,)>()
177            .fetch_one(pool, sqlx::query_as("select 1"))
178            .await;
179
180        let error = result.unwrap_err();
181        assert_eq!(
182            error.to_string(),
183            "database cached operation `db:unnamed` is missing an explicit cache key"
184        );
185    }
186
187    #[tokio::test]
188    async fn sqlx_cache_error_wraps_db_cache_errors() {
189        let error = hydracache_db::DbCacheError::MissingKey {
190            operation: "load-user".to_owned(),
191        };
192        let error = crate::SqlxCacheError::from(error);
193
194        assert_eq!(
195            error.to_string(),
196            "database cached operation `load-user` is missing an explicit cache key"
197        );
198    }
199}