use crate::validate::ValidatedPlan;
use serde_json::Value;
pub fn normalize_plan(plan: &ValidatedPlan) -> String {
let value = serde_json::to_value(plan.as_plan())
.expect("invariant: ValidatedPlan should always serialize to JSON");
let sorted = sort_value(value);
serde_json::to_string(&sorted).expect("invariant: sorted JSON should serialize")
}
const MAX_SORT_DEPTH: usize = 64;
fn sort_value(value: Value) -> Value {
sort_value_with_depth(value, 0)
}
fn sort_value_with_depth(value: Value, depth: usize) -> Value {
if depth >= MAX_SORT_DEPTH {
return value;
}
let next_depth = depth + 1;
match value {
Value::Object(mut map) => {
let mut sorted = serde_json::Map::with_capacity(map.len());
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
for key in keys {
if let Some(val) = map.remove(&key) {
sorted.insert(key, sort_value_with_depth(val, next_depth));
}
}
Value::Object(sorted)
}
Value::Array(arr) => Value::Array(
arr.into_iter()
.map(|v| sort_value_with_depth(v, next_depth))
.collect(),
),
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{FromClause, Projection, QueryPlan};
use std::sync::Arc;
#[test]
fn same_plan_same_normalized() {
let 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,
}))
};
assert_eq!(normalize_plan(&plan()), normalize_plan(&plan()));
}
#[test]
fn different_plan_different_normalized() {
let plan_a = 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 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,
}));
assert_ne!(normalize_plan(&plan_a), normalize_plan(&plan_b));
}
}