1use 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#[derive(Debug, Clone)]
58pub struct CompileCache {
59 inner: MokaCache<CompileCacheKey, Arc<CompiledQuery>>,
60 max_size: u64,
61}
62
63impl CompileCache {
64 #[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 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 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 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 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 pub fn clear(&self) {
140 self.inner.invalidate_all();
141 }
142
143 #[must_use]
145 pub fn size(&self) -> u64 {
146 self.inner.entry_count()
147 }
148
149 #[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 #[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 #[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 assert!(
239 cache.get(&plan, &sqlite_profile).await.is_none(),
240 "a different dialect must not return the cached value"
241 );
242 }
243
244 #[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 let cached = cache.get(&plan_b, &profile).await;
286 assert_eq!(cached, Some(Arc::new(compiled_b)));
287 }
288
289 #[tokio::test]
291 async fn cache_evicts_under_lru_weight_limit() {
292 let cache = CompileCache::new(50, 60); let profile = DialectProfile::default();
295
296 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 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 #[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 #[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 #[tokio::test]
375 async fn ttl_expiry_causes_miss() {
376 let cache = CompileCache::new(1024, 1); 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 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 #[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 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}