Skip to main content

vlorql_core/cache/
compile_cache.rs

1//! Cache for compiled SQL results (`ValidatedPlan → CompiledQuery`).
2//!
3//! [`CompileCache`] avoids re-compiling a plan that has already been
4//! compiled for the same dialect.  The cache uses a [`CompileCacheKey`]
5//! that captures the plan's content hash, the SQL dialect, and the
6//! identifier quoting style, so that different dialects produce
7//! different cache entries.
8
9use crate::cache::CompileCacheKey;
10use crate::compile::CompiledQuery;
11use crate::schema::DialectProfile;
12use crate::validate::ValidatedPlan;
13use moka::future::Cache as MokaCache;
14use std::sync::Arc;
15
16/// A cache for [`CompiledQuery`] values keyed by plan hash + dialect.
17///
18/// Uses a [`moka::future::Cache`] with a weigher that limits the total
19/// SQL string length, preventing unbounded memory growth.
20///
21/// # Examples
22///
23/// ```
24/// use vlorql_core::cache::CompileCache;
25/// use vlorql_core::schema::{DialectProfile, SqlDialect, QueryPlan, Projection, FromClause};
26/// use vlorql_core::compile::CompiledQuery;
27/// use vlorql_core::validate::ValidatedPlan;
28/// use std::sync::Arc;
29///
30/// # async fn example() {
31/// let cache = CompileCache::new(1024, 60);
32/// let plan = ValidatedPlan(Arc::new(QueryPlan {
33///     select: vec![Projection::Column {
34///         table: None, column: "id".to_owned(), alias: None,
35///     }],
36///     from: FromClause { table: "users".to_owned(), alias: None },
37///     r#where: None, group_by: None, having: None,
38///     order_by: None, limit: None, offset: None,
39///     joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
40/// }));
41/// let profile = DialectProfile::default();
42///
43/// assert!(cache.get(&plan, &profile).await.is_none());
44///
45/// let compiled = CompiledQuery {
46///     sql: "SELECT \"id\" FROM \"users\"".to_owned(),
47///     parameters: vec![],
48///     dialect: SqlDialect::Postgres,
49/// };
50/// cache.insert(&plan, &profile, compiled.clone()).await;
51///
52/// let cached = cache.get(&plan, &profile).await;
53/// assert!(cached.is_some());
54/// assert_eq!(cached.unwrap().sql, "SELECT \"id\" FROM \"users\"");
55/// # }
56/// ```
57#[derive(Debug, Clone)]
58pub struct CompileCache {
59    inner: MokaCache<CompileCacheKey, Arc<CompiledQuery>>,
60    max_size: u64,
61}
62
63impl CompileCache {
64    /// Creates a new compile cache.
65    ///
66    /// * `max_size` — maximum total weight (sum of SQL string lengths in
67    ///   bytes) before the cache evicts least-recently-used items.
68    /// * `ttl_seconds` — time-to-live in seconds.  Entries older than
69    ///   this are automatically invalidated.
70    #[must_use]
71    pub fn new(max_size: u64, ttl_seconds: u64) -> Self {
72        let mut builder = MokaCache::builder()
73            .weigher(|_k, v: &Arc<CompiledQuery>| -> u32 {
74                // Weight is the SQL string length in bytes, capped at
75                // u32::MAX to stay within moka's range.
76                let len = v.sql.len() as u64;
77                len.min(u64::from(u32::MAX)) as u32
78            })
79            .max_capacity(max_size);
80        if ttl_seconds > 0 {
81            builder = builder.time_to_live(std::time::Duration::from_secs(ttl_seconds));
82        }
83        let inner = builder.build();
84        Self { inner, max_size }
85    }
86
87    /// Returns the cached compiled query for `plan` under `profile`, or
88    /// `None` on a cache miss.
89    ///
90    /// The key is computed from the plan's normalised JSON hash, the
91    /// dialect, and the quoting style, so the same plan compiled for
92    /// different dialects produces different cache entries.
93    pub async fn get(
94        &self,
95        plan: &ValidatedPlan,
96        profile: &DialectProfile,
97    ) -> Option<Arc<CompiledQuery>> {
98        let key = CompileCacheKey::new(plan, profile);
99        let result = self.inner.get(&key).await;
100        let hit = result.is_some();
101        tracing::debug!(
102            target: "vlorql::cache",
103            "Compile cache {} for plan_hash={:016x}, dialect={:?}",
104            if hit { "HIT" } else { "MISS" },
105            key.plan_hash,
106            key.dialect,
107        );
108        result
109    }
110
111    /// Inserts a compiled query into the cache.
112    ///
113    /// The key is computed from `plan` and `profile` identically to
114    /// [`Self::get`], ensuring that a subsequent `get` with the same
115    /// arguments finds the entry.
116    pub async fn insert(
117        &self,
118        plan: &ValidatedPlan,
119        profile: &DialectProfile,
120        query: CompiledQuery,
121    ) {
122        let key = CompileCacheKey::new(plan, profile);
123        tracing::debug!(
124            target: "vlorql::cache",
125            "Compile cache INSERT for plan_hash={:016x}, dialect={:?}",
126            key.plan_hash,
127            key.dialect,
128        );
129        self.inner.insert(key, Arc::new(query)).await;
130    }
131
132    /// Removes the cache entry for `plan` under `profile`.
133    pub async fn invalidate_plan(&self, plan: &ValidatedPlan, profile: &DialectProfile) {
134        let key = CompileCacheKey::new(plan, profile);
135        self.inner.invalidate(&key).await;
136    }
137
138    /// Removes all entries from the cache.
139    pub fn clear(&self) {
140        self.inner.invalidate_all();
141    }
142
143    /// Returns the number of entries currently in the cache.
144    #[must_use]
145    pub fn size(&self) -> u64 {
146        self.inner.entry_count()
147    }
148
149    /// Returns the maximum total weight of the cache.
150    #[must_use]
151    pub fn max_size(&self) -> u64 {
152        self.max_size
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use crate::schema::{FromClause, Projection, QueryPlan, SqlDialect};
160    use std::sync::Arc;
161
162    fn make_plan() -> ValidatedPlan {
163        ValidatedPlan(Arc::new(QueryPlan {
164            select: vec![Projection::Column {
165                table: None,
166                column: "id".to_owned(),
167                alias: None,
168            }],
169            from: FromClause {
170                table: "users".to_owned(),
171                alias: None,
172            },
173            r#where: None,
174            group_by: None,
175            having: None,
176            order_by: None,
177            limit: None,
178            offset: None,
179            joins: None,
180            ctes: None,
181            distinct: false,
182            distinct_on: None,
183            set_operation: None,
184        }))
185    }
186
187    fn make_compiled(dialect: SqlDialect) -> CompiledQuery {
188        match dialect {
189            SqlDialect::Postgres => CompiledQuery {
190                sql: "SELECT \"id\" FROM \"users\"".to_owned(),
191                parameters: vec![],
192                dialect: SqlDialect::Postgres,
193            },
194            SqlDialect::Sqlite => CompiledQuery {
195                sql: "SELECT \"id\" FROM \"users\"".to_owned(),
196                parameters: vec![],
197                dialect: SqlDialect::Sqlite,
198            },
199            SqlDialect::MySql => CompiledQuery {
200                sql: "SELECT `id` FROM `users`".to_owned(),
201                parameters: vec![],
202                dialect: SqlDialect::MySql,
203            },
204        }
205    }
206
207    /// Same plan + same profile → cache hit.
208    #[tokio::test]
209    async fn same_plan_same_dialect_hits() {
210        let cache = CompileCache::new(1024, 60);
211        let plan = make_plan();
212        let profile = DialectProfile::default();
213        let compiled = make_compiled(SqlDialect::Postgres);
214
215        assert!(cache.get(&plan, &profile).await.is_none());
216        cache.insert(&plan, &profile, compiled.clone()).await;
217        let cached = cache.get(&plan, &profile).await;
218        assert_eq!(cached, Some(Arc::new(compiled)));
219    }
220
221    /// Same plan + different dialect → different cache entries.
222    #[tokio::test]
223    async fn same_plan_different_dialect_misses() {
224        let cache = CompileCache::new(1024, 60);
225        let plan = make_plan();
226
227        let pg_profile = DialectProfile::default();
228        let sqlite_profile = DialectProfile {
229            dialect: SqlDialect::Sqlite,
230            ..DialectProfile::default()
231        };
232
233        let pg_compiled = make_compiled(SqlDialect::Postgres);
234        cache.insert(&plan, &pg_profile, pg_compiled).await;
235
236        // SQLite query should not be found because the key includes
237        // the dialect — even though the plan is the same.
238        assert!(
239            cache.get(&plan, &sqlite_profile).await.is_none(),
240            "a different dialect must not return the cached value"
241        );
242    }
243
244    /// Different plans produce different keys even with the same dialect.
245    #[tokio::test]
246    async fn different_plan_different_key() {
247        let cache = CompileCache::new(1024, 60);
248        let profile = DialectProfile::default();
249
250        let plan_a = make_plan();
251        let plan_b = ValidatedPlan(Arc::new(QueryPlan {
252            select: vec![Projection::Column {
253                table: None,
254                column: "email".to_owned(),
255                alias: None,
256            }],
257            from: FromClause {
258                table: "users".to_owned(),
259                alias: None,
260            },
261            r#where: None,
262            group_by: None,
263            having: None,
264            order_by: None,
265            limit: None,
266            offset: None,
267            joins: None,
268            ctes: None,
269            distinct: false,
270            distinct_on: None,
271            set_operation: None,
272        }));
273
274        let compiled_a = make_compiled(SqlDialect::Postgres);
275        let compiled_b = CompiledQuery {
276            sql: "SELECT \"email\" FROM \"users\"".to_owned(),
277            parameters: vec![],
278            dialect: SqlDialect::Postgres,
279        };
280
281        cache.insert(&plan_a, &profile, compiled_a).await;
282        cache.insert(&plan_b, &profile, compiled_b.clone()).await;
283
284        // plan_b should find its own entry.
285        let cached = cache.get(&plan_b, &profile).await;
286        assert_eq!(cached, Some(Arc::new(compiled_b)));
287    }
288
289    /// Cache respects the max_size weigher (small size for testing).
290    #[tokio::test]
291    async fn cache_evicts_under_lru_weight_limit() {
292        // Use a very small max_size so entries are evicted quickly.
293        let cache = CompileCache::new(50, 60); // 50 bytes total weight
294        let profile = DialectProfile::default();
295
296        // Insert entries until the cache evicts the oldest.
297        for i in 0..20 {
298            let plan = ValidatedPlan(Arc::new(QueryPlan {
299                select: vec![Projection::Column {
300                    table: None,
301                    column: format!("col_{i}"),
302                    alias: None,
303                }],
304                from: FromClause {
305                    table: "t".to_owned(),
306                    alias: None,
307                },
308                r#where: None,
309                group_by: None,
310                having: None,
311                order_by: None,
312                limit: None,
313                offset: None,
314                joins: None,
315                ctes: None,
316            distinct: false,
317            distinct_on: None,
318            set_operation: None,            }));
319            let compiled = CompiledQuery {
320                sql: format!("SELECT \"col_{i}\" FROM \"t\""),
321                parameters: vec![],
322                dialect: SqlDialect::Postgres,
323            };
324            cache.insert(&plan, &profile, compiled).await;
325        }
326
327        // The cache should have evicted some entries.
328        // We can't assert the exact count because moka's eviction is
329        // asynchronous, but we can verify it's not growing unbounded.
330        let size = cache.size();
331        assert!(
332            size < 20,
333            "cache should have evicted entries under tight weight limit, got {size}"
334        );
335    }
336
337    /// Invalidate a specific plan.
338    #[tokio::test]
339    async fn invalidate_plan_removes_entry() {
340        let cache = CompileCache::new(1024, 60);
341        let plan = make_plan();
342        let profile = DialectProfile::default();
343        let compiled = make_compiled(SqlDialect::Postgres);
344
345        cache.insert(&plan, &profile, compiled).await;
346        assert!(cache.get(&plan, &profile).await.is_some());
347
348        cache.invalidate_plan(&plan, &profile).await;
349        assert!(
350            cache.get(&plan, &profile).await.is_none(),
351            "entry should be removed after invalidation"
352        );
353    }
354
355    /// Clear removes all entries.
356    #[tokio::test]
357    async fn clear_removes_all_entries() {
358        let cache = CompileCache::new(1024, 60);
359        let plan = make_plan();
360        let profile = DialectProfile::default();
361        let compiled = make_compiled(SqlDialect::Postgres);
362
363        cache.insert(&plan, &profile, compiled).await;
364        assert!(cache.get(&plan, &profile).await.is_some());
365
366        cache.clear();
367        assert!(
368            cache.get(&plan, &profile).await.is_none(),
369            "entry should be removed after clear"
370        );
371    }
372
373    /// TTL expiry causes a cache miss.
374    #[tokio::test]
375    async fn ttl_expiry_causes_miss() {
376        let cache = CompileCache::new(1024, 1); // 1 second TTL
377        let plan = make_plan();
378        let profile = DialectProfile::default();
379        let compiled = make_compiled(SqlDialect::Postgres);
380
381        cache.insert(&plan, &profile, compiled).await;
382        assert!(cache.get(&plan, &profile).await.is_some());
383
384        // Wait for the entry to expire.
385        tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
386
387        assert!(
388            cache.get(&plan, &profile).await.is_none(),
389            "entry should have expired after TTL"
390        );
391    }
392
393    /// Concurrent access to the cache should not cause data races.
394    #[tokio::test]
395    async fn concurrent_access_is_safe() {
396        let cache = std::sync::Arc::new(CompileCache::new(1024, 60));
397        let profile = DialectProfile::default();
398        let mut handles = Vec::new();
399
400        for i in 0..20 {
401            let cache = Arc::clone(&cache);
402            let profile = profile.clone();
403            handles.push(tokio::spawn(async move {
404                let plan = ValidatedPlan(Arc::new(QueryPlan {
405                    select: vec![Projection::Column {
406                        table: None,
407                        column: format!("col_{i}"),
408                        alias: None,
409                    }],
410                    from: FromClause {
411                        table: "t".to_owned(),
412                        alias: None,
413                    },
414                    r#where: None,
415                    group_by: None,
416                    having: None,
417                    order_by: None,
418                    limit: None,
419                    offset: None,
420                    joins: None,
421                    ctes: None,
422            distinct: false,
423            distinct_on: None,
424            set_operation: None,                }));
425                let compiled = CompiledQuery {
426                    sql: format!("SELECT \"col_{i}\" FROM \"t\""),
427                    parameters: vec![],
428                    dialect: SqlDialect::Postgres,
429                };
430
431                // Insert and immediately retrieve.
432                cache.insert(&plan, &profile, compiled).await;
433                let result = cache.get(&plan, &profile).await;
434                assert!(result.is_some(), "concurrent insert+get should succeed");
435            }));
436        }
437
438        for handle in handles {
439            handle.await.expect("concurrent task should not panic");
440        }
441    }
442}