vlorql-core 0.5.0

A high-performance SQL query optimizer with constant folding, predicate pushdown, column pruning, and cost-based join reordering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Cache for compiled SQL results (`ValidatedPlan → CompiledQuery`).
//!
//! [`CompileCache`] avoids re-compiling a plan that has already been
//! compiled for the same dialect.  The cache uses a [`CompileCacheKey`]
//! that captures the plan's content hash, the SQL dialect, and the
//! identifier quoting style, so that different dialects produce
//! different cache entries.

use crate::cache::CompileCacheKey;
use crate::compile::CompiledQuery;
use crate::errors::{ConfigErrorKind, VlorQLError};
use crate::schema::DialectProfile;
use crate::validate::ValidatedPlan;
use moka::future::Cache as MokaCache;
use serde_json::json;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;

/// A cache for [`CompiledQuery`] values keyed by plan hash + dialect.
///
/// Uses a [`moka::future::Cache`] with a weigher that limits the total
/// SQL string length, preventing unbounded memory growth.
///
/// # Examples
///
/// ```
/// use vlorql_core::cache::CompileCache;
/// use vlorql_core::schema::{DialectProfile, SqlDialect, QueryPlan, Projection, FromClause};
/// use vlorql_core::compile::CompiledQuery;
/// use vlorql_core::validate::ValidatedPlan;
/// use std::sync::Arc;
///
/// # async fn example() {
/// let cache = CompileCache::new(1024, 60);
/// let plan = ValidatedPlan(Arc::new(QueryPlan {
///     select: vec![Projection::Column {
///         table: None, column: "id".to_owned(), alias: None,
///     }],
///     from: FromClause::table("users".to_owned(), None),
///     r#where: None, group_by: None, having: None,
///     order_by: None, limit: None, offset: None,
///     joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
/// }));
/// let profile = DialectProfile::default();
///
/// assert!(cache.get(&plan, &profile).await.is_none());
///
/// let compiled = CompiledQuery {
///     sql: "SELECT \"id\" FROM \"users\"".to_owned(),
///     parameters: vec![],
///     dialect: SqlDialect::Postgres,
/// };
/// cache.insert(&plan, &profile, compiled.clone()).await;
///
/// let cached = cache.get(&plan, &profile).await;
/// assert!(cached.is_some());
/// assert_eq!(cached.unwrap().sql, "SELECT \"id\" FROM \"users\"");
/// # }
/// ```
#[derive(Debug)]
pub struct CompileCache {
    inner: MokaCache<CompileCacheKey, Arc<CompiledQuery>>,
    entries: Mutex<HashMap<CompileCacheKey, CompiledQuery>>,
    max_size: u64,
    persist_path: Option<PathBuf>,
}

impl CompileCache {
    /// Creates a new compile cache.
    ///
    /// * `max_size` — maximum total weight (sum of SQL string lengths in
    ///   bytes) before the cache evicts least-recently-used items.
    /// * `ttl_seconds` — time-to-live in seconds.  Entries older than
    ///   this are automatically invalidated.
    #[must_use]
    pub fn new(max_size: u64, ttl_seconds: u64) -> Self {
        let mut builder = MokaCache::builder()
            .weigher(|_k, v: &Arc<CompiledQuery>| -> u32 {
                // Weight is the SQL string length in bytes, capped at
                // u32::MAX to stay within moka's range.
                let len = v.sql.len() as u64;
                len.min(u64::from(u32::MAX)) as u32
            })
            .max_capacity(max_size);
        if ttl_seconds > 0 {
            builder = builder.time_to_live(std::time::Duration::from_secs(ttl_seconds));
        }
        let inner = builder.build();
        Self {
            inner,
            entries: Mutex::new(HashMap::new()),
            max_size,
            persist_path: None,
        }
    }

    /// Returns the cached compiled query for `plan` under `profile`, or
    /// `None` on a cache miss.
    ///
    /// The key is computed from the plan's normalised JSON hash, the
    /// dialect, and the quoting style, so the same plan compiled for
    /// different dialects produces different cache entries.
    pub async fn get(
        &self,
        plan: &ValidatedPlan,
        profile: &DialectProfile,
    ) -> Option<Arc<CompiledQuery>> {
        let key = CompileCacheKey::new(plan, profile);
        let result = self.inner.get(&key).await;
        let hit = result.is_some();
        tracing::debug!(
            target: "vlorql::cache",
            "Compile cache {} for plan_hash={:016x}, dialect={:?}",
            if hit { "HIT" } else { "MISS" },
            key.plan_hash,
            key.dialect,
        );
        result
    }

    /// Inserts a compiled query into the cache.
    ///
    /// The key is computed from `plan` and `profile` identically to
    /// [`Self::get`], ensuring that a subsequent `get` with the same
    /// arguments finds the entry.
    pub async fn insert(
        &self,
        plan: &ValidatedPlan,
        profile: &DialectProfile,
        query: CompiledQuery,
    ) {
        let key = CompileCacheKey::new(plan, profile);
        tracing::debug!(
            target: "vlorql::cache",
            "Compile cache INSERT for plan_hash={:016x}, dialect={:?}",
            key.plan_hash,
            key.dialect,
        );
        self.inner
            .insert(key.clone(), Arc::new(query.clone()))
            .await;
        self.entries
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key, query);
    }

    /// Removes the cache entry for `plan` under `profile`.
    ///
    /// # Errors
    ///
    /// Returns `Ok(())` unconditionally; errors from the underlying
    /// cache are propagated through the `Result` by the caller.
    pub async fn invalidate_plan(&self, plan: &ValidatedPlan, profile: &DialectProfile) {
        let key = CompileCacheKey::new(plan, profile);
        self.inner.invalidate(&key).await;
        self.entries
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&key);
    }

    /// Removes all entries from the cache.
    pub fn clear(&self) {
        self.inner.invalidate_all();
        self.entries
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
    }

    /// Returns the number of entries currently in the cache.
    #[must_use]
    pub fn size(&self) -> u64 {
        self.inner.entry_count()
    }

    /// Returns the maximum total weight of the cache.
    #[must_use]
    pub fn max_size(&self) -> u64 {
        self.max_size
    }

    /// Creates a new compile cache with a persistence path.
    ///
    /// The cache will be backed by the file at `path` — call
    /// [`persist`](Self::persist) to save entries to disk.
    #[must_use]
    pub fn with_persistence(max_size: u64, ttl_seconds: u64, path: PathBuf) -> Self {
        let mut cache = Self::new(max_size, ttl_seconds);
        cache.persist_path = Some(path);
        cache
    }

    /// Persists the current cache entries to disk via bincode serialization.
    ///
    /// Writes atomically by writing to a `.tmp` sibling file then renaming.
    /// Returns `Ok(())` when no `persist_path` is set (silent no-op).
    pub async fn persist(&self) -> Result<(), VlorQLError> {
        let Some(ref path) = self.persist_path else {
            return Ok(());
        };
        let bytes = {
            let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
            bincode::serialize(&*entries).map_err(|e| {
                VlorQLError::config(
                    ConfigErrorKind::ConfigFileError {
                        path: path.to_string_lossy().to_string(),
                        reason: e.to_string(),
                    },
                    json!({"operation": "serialize"}),
                )
            })?
        };
        // Atomic write: write to temp file then rename
        let tmp = path.with_extension("tmp");
        tokio::fs::write(&tmp, &bytes).await.map_err(|e| {
            VlorQLError::config(
                ConfigErrorKind::ConfigFileError {
                    path: tmp.to_string_lossy().to_string(),
                    reason: e.to_string(),
                },
                json!({"operation": "write_tmp"}),
            )
        })?;
        tokio::fs::rename(&tmp, path).await.map_err(|e| {
            VlorQLError::config(
                ConfigErrorKind::ConfigFileError {
                    path: path.to_string_lossy().to_string(),
                    reason: e.to_string(),
                },
                json!({"operation": "rename"}),
            )
        })?;
        Ok(())
    }

    /// Loads a compile cache from a bincode file on disk.
    ///
    /// If the file does not exist or is corrupt, returns an empty cache
    /// (warns on corruption). The cache's `persist_path` is set to `path`
    /// so future [`persist`](Self::persist) calls write to the same file.
    #[must_use]
    pub async fn load(path: &Path, max_size: u64, ttl_seconds: u64) -> Self {
        let mut cache = Self::new(max_size, ttl_seconds);
        cache.persist_path = Some(path.to_path_buf());
        let bytes = match tokio::fs::read(path).await {
            Ok(b) => b,
            Err(_) => return cache,
        };
        let entries: HashMap<CompileCacheKey, CompiledQuery> = match bincode::deserialize(&bytes) {
            Ok(e) => e,
            Err(_) => {
                tracing::warn!(target: "vlorql::cache", "corrupt compile cache file, starting fresh");
                return cache;
            }
        };
        for (key, query) in &entries {
            cache
                .inner
                .insert(key.clone(), Arc::new(query.clone()))
                .await;
            cache
                .entries
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .insert(key.clone(), query.clone());
        }
        cache
    }

    /// Sets the persistence path for the cache.
    ///
    /// After calling this, [`persist`](Self::persist) will write entries
    /// to `path` and [`load`](Self::load) will read from it.
    pub fn set_persist_path(&mut self, path: PathBuf) {
        self.persist_path = Some(path);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{FromClause, Projection, QueryPlan, SqlDialect};
    use std::sync::Arc;

    fn make_plan() -> ValidatedPlan {
        ValidatedPlan(Arc::new(QueryPlan {
            select: vec![Projection::Column {
                table: None,
                column: "id".to_owned(),
                alias: None,
            }],
            from: FromClause::table("users".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: None,
            distinct: false,
            distinct_on: None,
            set_operation: None,
        }))
    }

    fn make_compiled(dialect: SqlDialect) -> CompiledQuery {
        match dialect {
            SqlDialect::Postgres => CompiledQuery {
                sql: "SELECT \"id\" FROM \"users\"".to_owned(),
                parameters: vec![],
                dialect: SqlDialect::Postgres,
            },
            SqlDialect::Sqlite => CompiledQuery {
                sql: "SELECT \"id\" FROM \"users\"".to_owned(),
                parameters: vec![],
                dialect: SqlDialect::Sqlite,
            },
            SqlDialect::MySql => CompiledQuery {
                sql: "SELECT `id` FROM `users`".to_owned(),
                parameters: vec![],
                dialect: SqlDialect::MySql,
            },
        }
    }

    /// Same plan + same profile → cache hit.
    #[tokio::test]
    async fn same_plan_same_dialect_hits() {
        let cache = CompileCache::new(1024, 60);
        let plan = make_plan();
        let profile = DialectProfile::default();
        let compiled = make_compiled(SqlDialect::Postgres);

        assert!(cache.get(&plan, &profile).await.is_none());
        cache.insert(&plan, &profile, compiled.clone()).await;
        let cached = cache.get(&plan, &profile).await;
        assert_eq!(cached, Some(Arc::new(compiled)));
    }

    /// Same plan + different dialect → different cache entries.
    #[tokio::test]
    async fn same_plan_different_dialect_misses() {
        let cache = CompileCache::new(1024, 60);
        let plan = make_plan();

        let pg_profile = DialectProfile::default();
        let sqlite_profile = DialectProfile {
            dialect: SqlDialect::Sqlite,
            ..DialectProfile::default()
        };

        let pg_compiled = make_compiled(SqlDialect::Postgres);
        cache.insert(&plan, &pg_profile, pg_compiled).await;

        // SQLite query should not be found because the key includes
        // the dialect — even though the plan is the same.
        assert!(
            cache.get(&plan, &sqlite_profile).await.is_none(),
            "a different dialect must not return the cached value"
        );
    }

    /// Different plans produce different keys even with the same dialect.
    #[tokio::test]
    async fn different_plan_different_key() {
        let cache = CompileCache::new(1024, 60);
        let profile = DialectProfile::default();

        let plan_a = make_plan();
        let plan_b = ValidatedPlan(Arc::new(QueryPlan {
            select: vec![Projection::Column {
                table: None,
                column: "email".to_owned(),
                alias: None,
            }],
            from: FromClause::table("users".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: None,
            distinct: false,
            distinct_on: None,
            set_operation: None,
        }));

        let compiled_a = make_compiled(SqlDialect::Postgres);
        let compiled_b = CompiledQuery {
            sql: "SELECT \"email\" FROM \"users\"".to_owned(),
            parameters: vec![],
            dialect: SqlDialect::Postgres,
        };

        cache.insert(&plan_a, &profile, compiled_a).await;
        cache.insert(&plan_b, &profile, compiled_b.clone()).await;

        // plan_b should find its own entry.
        let cached = cache.get(&plan_b, &profile).await;
        assert_eq!(cached, Some(Arc::new(compiled_b)));
    }

    /// Cache respects the max_size weigher (small size for testing).
    #[cfg(not(miri))]
    #[tokio::test]
    async fn cache_evicts_under_lru_weight_limit() {
        // Use a very small max_size so entries are evicted quickly.
        let cache = CompileCache::new(50, 60); // 50 bytes total weight
        let profile = DialectProfile::default();

        // Insert entries until the cache evicts the oldest.
        for i in 0..20 {
            let plan = ValidatedPlan(Arc::new(QueryPlan {
                select: vec![Projection::Column {
                    table: None,
                    column: format!("col_{i}"),
                    alias: None,
                }],
                from: FromClause::table("t".to_owned(), None),
                r#where: None,
                group_by: None,
                having: None,
                order_by: None,
                limit: None,
                offset: None,
                joins: None,
                ctes: None,
                distinct: false,
                distinct_on: None,
                set_operation: None,
            }));
            let compiled = CompiledQuery {
                sql: format!("SELECT \"col_{i}\" FROM \"t\""),
                parameters: vec![],
                dialect: SqlDialect::Postgres,
            };
            cache.insert(&plan, &profile, compiled).await;
        }

        // The cache should have evicted some entries.
        // We can't assert the exact count because moka's eviction is
        // asynchronous, but we can verify it's not growing unbounded.
        let size = cache.size();
        assert!(
            size < 20,
            "cache should have evicted entries under tight weight limit, got {size}"
        );
    }

    /// Invalidate a specific plan.
    #[tokio::test]
    async fn invalidate_plan_removes_entry() {
        let cache = CompileCache::new(1024, 60);
        let plan = make_plan();
        let profile = DialectProfile::default();
        let compiled = make_compiled(SqlDialect::Postgres);

        cache.insert(&plan, &profile, compiled).await;
        assert!(cache.get(&plan, &profile).await.is_some());

        cache.invalidate_plan(&plan, &profile).await;
        assert!(
            cache.get(&plan, &profile).await.is_none(),
            "entry should be removed after invalidation"
        );
    }

    /// Clear removes all entries.
    #[tokio::test]
    async fn clear_removes_all_entries() {
        let cache = CompileCache::new(1024, 60);
        let plan = make_plan();
        let profile = DialectProfile::default();
        let compiled = make_compiled(SqlDialect::Postgres);

        cache.insert(&plan, &profile, compiled).await;
        assert!(cache.get(&plan, &profile).await.is_some());

        cache.clear();
        assert!(
            cache.get(&plan, &profile).await.is_none(),
            "entry should be removed after clear"
        );
    }

    /// TTL expiry causes a cache miss.
    #[tokio::test]
    async fn ttl_expiry_causes_miss() {
        let cache = CompileCache::new(1024, 1); // 1 second TTL
        let plan = make_plan();
        let profile = DialectProfile::default();
        let compiled = make_compiled(SqlDialect::Postgres);

        cache.insert(&plan, &profile, compiled).await;
        assert!(cache.get(&plan, &profile).await.is_some());

        // Wait for the entry to expire.
        tokio::time::sleep(std::time::Duration::from_millis(1100)).await;

        assert!(
            cache.get(&plan, &profile).await.is_none(),
            "entry should have expired after TTL"
        );
    }

    /// Concurrent access to the cache should not cause data races.
    #[tokio::test]
    async fn concurrent_access_is_safe() {
        let cache = std::sync::Arc::new(CompileCache::new(1024, 60));
        let profile = DialectProfile::default();
        let mut handles = Vec::new();

        for i in 0..20 {
            let cache = Arc::clone(&cache);
            let profile = profile.clone();
            handles.push(tokio::spawn(async move {
                let plan = ValidatedPlan(Arc::new(QueryPlan {
                    select: vec![Projection::Column {
                        table: None,
                        column: format!("col_{i}"),
                        alias: None,
                    }],
                    from: FromClause::table("t".to_owned(), None),
                    r#where: None,
                    group_by: None,
                    having: None,
                    order_by: None,
                    limit: None,
                    offset: None,
                    joins: None,
                    ctes: None,
                    distinct: false,
                    distinct_on: None,
                    set_operation: None,
                }));
                let compiled = CompiledQuery {
                    sql: format!("SELECT \"col_{i}\" FROM \"t\""),
                    parameters: vec![],
                    dialect: SqlDialect::Postgres,
                };

                // Insert and immediately retrieve.
                cache.insert(&plan, &profile, compiled).await;
                let result = cache.get(&plan, &profile).await;
                assert!(result.is_some(), "concurrent insert+get should succeed");
            }));
        }

        for handle in handles {
            handle.await.expect("concurrent task should not panic");
        }
    }

    #[tokio::test]
    async fn persist_then_load_roundtrip() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("compile_cache_test_persist_{}", std::process::id()));
        // Clean up any leftover from a previous failed run
        std::fs::remove_file(&path).ok();
        std::fs::remove_file(dir.join("compile_cache_test_persist_.tmp")).ok();

        let cache = CompileCache::with_persistence(1024, 60, path.clone());
        let plan = make_plan();
        let profile = DialectProfile::default();
        let compiled = make_compiled(SqlDialect::Postgres);
        cache.insert(&plan, &profile, compiled.clone()).await;
        cache.persist().await.expect("persist should succeed");

        let loaded = CompileCache::load(&path, 1024, 60).await;
        let cached = loaded.get(&plan, &profile).await;
        assert_eq!(cached, Some(Arc::new(compiled)));

        std::fs::remove_file(&path).ok();
    }

    #[tokio::test]
    async fn corrupt_file_loads_gracefully() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("compile_cache_test_corrupt_{}", std::process::id()));
        std::fs::remove_file(&path).ok();
        tokio::fs::write(&path, b"not valid bincode data")
            .await
            .expect("write");

        let cache = CompileCache::load(&path, 1024, 60).await;
        assert_eq!(cache.size(), 0, "corrupt file should load as empty");

        std::fs::remove_file(&path).ok();
    }

    #[tokio::test]
    async fn missing_file_loads_gracefully() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("compile_cache_test_missing_{}", std::process::id()));
        std::fs::remove_file(&path).ok();

        let cache = CompileCache::load(&path, 1024, 60).await;
        assert_eq!(cache.size(), 0, "missing file should load as empty");
    }

    #[tokio::test]
    async fn invalidate_removes_from_persist_state() {
        let cache = CompileCache::new(1024, 60);
        let plan = make_plan();
        let profile = DialectProfile::default();
        let compiled = make_compiled(SqlDialect::Postgres);

        cache.insert(&plan, &profile, compiled).await;
        assert_eq!(cache.entries.lock().unwrap().len(), 1);

        cache.invalidate_plan(&plan, &profile).await;
        assert_eq!(cache.entries.lock().unwrap().len(), 0);
    }
}