use crate::schema::{DialectProfile, IdentifierQuoting, SqlDialect};
use crate::validate::ValidatedPlan;
use serde::{Deserialize, Serialize};
use xxhash_rust::xxh3::xxh3_64;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SchemaCacheKey {
pub version: String,
pub source: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CompileCacheKey {
pub plan_hash: u64,
pub dialect: SqlDialect,
pub quote_style: IdentifierQuoting,
}
impl CompileCacheKey {
pub fn new(plan: &ValidatedPlan, profile: &DialectProfile) -> Self {
let normalized = super::normalize::normalize_plan(plan);
let hash = xxh3_64(normalized.as_bytes());
Self {
plan_hash: hash,
dialect: profile.dialect,
quote_style: profile.quote_style,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{FromClause, Projection, QueryPlan};
use std::sync::Arc;
fn make_validated_plan() -> ValidatedPlan {
ValidatedPlan(Arc::new(QueryPlan {
select: vec![Projection::Column {
table: None,
column: "id".to_owned(),
alias: None,
}],
from: FromClause {
table: "users".to_owned(),
alias: None,
},
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
}))
}
#[test]
fn same_plan_same_key() {
let plan = make_validated_plan();
let profile = DialectProfile::default();
let a = CompileCacheKey::new(&plan, &profile);
let b = CompileCacheKey::new(&plan, &profile);
assert_eq!(a, b);
}
#[test]
fn different_plan_different_key() {
let profile = DialectProfile::default();
let plan_a = make_validated_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(),
alias: None,
},
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
}));
let key_a = CompileCacheKey::new(&plan_a, &profile);
let key_b = CompileCacheKey::new(&plan_b, &profile);
assert_ne!(key_a, key_b);
}
#[test]
fn different_dialect_different_key() {
let plan = make_validated_plan();
let pg = DialectProfile::default();
let sqlite = DialectProfile {
dialect: SqlDialect::Sqlite,
..DialectProfile::default()
};
let key_pg = CompileCacheKey::new(&plan, &pg);
let key_sqlite = CompileCacheKey::new(&plan, &sqlite);
assert_ne!(key_pg, key_sqlite);
}
#[test]
fn schema_cache_key_equality() {
let a = SchemaCacheKey {
version: "v1".to_owned(),
source: "db://prod".to_owned(),
};
let b = SchemaCacheKey {
version: "v1".to_owned(),
source: "db://prod".to_owned(),
};
let c = SchemaCacheKey {
version: "v2".to_owned(),
source: "db://prod".to_owned(),
};
assert_eq!(a, b);
assert_ne!(a, c);
}
}