vlorql_core/cache/key.rs
1//! Cache key types for identifying cached artifacts.
2//!
3//! [`SchemaCacheKey`] identifies a versioned schema snapshot;
4//! [`CompileCacheKey`] identifies a compiled SQL result by plan hash,
5//! dialect, and quoting style.
6
7use crate::schema::{DialectProfile, IdentifierQuoting, SqlDialect};
8use crate::validate::ValidatedPlan;
9use serde::{Deserialize, Serialize};
10use xxhash_rust::xxh3::xxh3_64;
11
12/// Key used to cache schema snapshots by version and source.
13///
14/// Two snapshots with the same version and source are assumed to be
15/// identical, so the cache can return a cached snapshot without
16/// re-parsing or re-fetching.
17#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
18pub struct SchemaCacheKey {
19 /// User-specified version string, e.g. `"v1.2.3"`.
20 pub version: String,
21 /// Data-source identifier, e.g. `"postgres://prod-db.example.com:5432"`.
22 pub source: String,
23}
24
25/// Key used to cache compiled SQL results.
26///
27/// The key is derived from the [`QueryPlan`](crate::schema::QueryPlan)
28/// content (via a deterministic hash of its normalised JSON form) and
29/// the dialect/quoting parameters that affect the generated SQL.
30#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub struct CompileCacheKey {
32 /// 64-bit hash of the normalised query plan.
33 pub plan_hash: u64,
34 /// Target SQL dialect.
35 pub dialect: SqlDialect,
36 /// Identifier quoting style.
37 pub quote_style: IdentifierQuoting,
38}
39
40impl CompileCacheKey {
41 /// Creates a new key from a validated plan and a dialect profile.
42 ///
43 /// The plan is normalised (serialised to JSON with sorted keys,
44 /// `None` values skipped) before hashing, so two semantically
45 /// equivalent plans always produce the same key.
46 ///
47 /// # Examples
48 ///
49 /// ```
50 /// use vlorql_core::cache::CompileCacheKey;
51 /// use vlorql_core::schema::{DialectProfile, QueryPlan, Projection, FromClause};
52 /// use vlorql_core::validate::ValidatedPlan;
53 /// use std::sync::Arc;
54 ///
55 /// let plan = QueryPlan {
56 /// select: vec![Projection::Column {
57 /// table: None, column: "id".to_owned(), alias: None,
58 /// }],
59 /// from: FromClause { table: "users".to_owned(), alias: None },
60 /// r#where: None, group_by: None, having: None,
61 /// order_by: None, limit: None, offset: None,
62 /// joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
63 /// };
64 /// let validated = ValidatedPlan(Arc::new(plan));
65 /// let profile = DialectProfile::default();
66 /// let key = CompileCacheKey::new(&validated, &profile);
67 /// assert!(key.plan_hash != 0);
68 /// ```
69 pub fn new(plan: &ValidatedPlan, profile: &DialectProfile) -> Self {
70 let normalized = super::normalize::normalize_plan(plan);
71 let hash = xxh3_64(normalized.as_bytes());
72 Self {
73 plan_hash: hash,
74 dialect: profile.dialect,
75 quote_style: profile.quote_style,
76 }
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83 use crate::schema::{FromClause, Projection, QueryPlan};
84 use std::sync::Arc;
85
86 fn make_validated_plan() -> ValidatedPlan {
87 ValidatedPlan(Arc::new(QueryPlan {
88 select: vec![Projection::Column {
89 table: None,
90 column: "id".to_owned(),
91 alias: None,
92 }],
93 from: FromClause {
94 table: "users".to_owned(),
95 alias: None,
96 },
97 r#where: None,
98 group_by: None,
99 having: None,
100 order_by: None,
101 limit: None,
102 offset: None,
103 joins: None,
104 ctes: None,
105 distinct: false,
106 distinct_on: None,
107 set_operation: None,
108 }))
109 }
110
111 /// The same plan + profile always produces the same key.
112 #[test]
113 fn same_plan_same_key() {
114 let plan = make_validated_plan();
115 let profile = DialectProfile::default();
116 let a = CompileCacheKey::new(&plan, &profile);
117 let b = CompileCacheKey::new(&plan, &profile);
118 assert_eq!(a, b);
119 }
120
121 /// Different plans produce different keys.
122 #[test]
123 fn different_plan_different_key() {
124 let profile = DialectProfile::default();
125
126 let plan_a = make_validated_plan();
127
128 let plan_b = ValidatedPlan(Arc::new(QueryPlan {
129 select: vec![Projection::Column {
130 table: None,
131 column: "email".to_owned(),
132 alias: None,
133 }],
134 from: FromClause {
135 table: "users".to_owned(),
136 alias: None,
137 },
138 r#where: None,
139 group_by: None,
140 having: None,
141 order_by: None,
142 limit: None,
143 offset: None,
144 joins: None,
145 ctes: None,
146 distinct: false,
147 distinct_on: None,
148 set_operation: None,
149 }));
150
151 let key_a = CompileCacheKey::new(&plan_a, &profile);
152 let key_b = CompileCacheKey::new(&plan_b, &profile);
153 assert_ne!(key_a, key_b);
154 }
155
156 /// Different dialect profiles produce different keys.
157 #[test]
158 fn different_dialect_different_key() {
159 let plan = make_validated_plan();
160
161 let pg = DialectProfile::default();
162 let sqlite = DialectProfile {
163 dialect: SqlDialect::Sqlite,
164 ..DialectProfile::default()
165 };
166
167 let key_pg = CompileCacheKey::new(&plan, &pg);
168 let key_sqlite = CompileCacheKey::new(&plan, &sqlite);
169 assert_ne!(key_pg, key_sqlite);
170 }
171
172 /// SchemaCacheKey equality works correctly.
173 #[test]
174 fn schema_cache_key_equality() {
175 let a = SchemaCacheKey {
176 version: "v1".to_owned(),
177 source: "db://prod".to_owned(),
178 };
179 let b = SchemaCacheKey {
180 version: "v1".to_owned(),
181 source: "db://prod".to_owned(),
182 };
183 let c = SchemaCacheKey {
184 version: "v2".to_owned(),
185 source: "db://prod".to_owned(),
186 };
187 assert_eq!(a, b);
188 assert_ne!(a, c);
189 }
190}