use std::collections::HashMap;
use std::sync::Arc;
use crate::errors::VlorQLError;
use crate::schema::{FromClause, JoinClause, JoinType, Predicate, QueryPlan};
use crate::statistics::{Cost, CostEstimator, DEFAULT_JOIN_SELECTIVITY, StatisticsProvider};
use super::analyze::{columns_in_predicate, combine_conjuncts, split_conjuncts};
pub const MAX_DP_RELATIONS: usize = 5;
#[derive(Debug, Clone)]
struct Relation {
from: FromClause,
key: String,
}
impl Relation {
fn new(from: FromClause) -> Self {
let key = from.alias.clone().unwrap_or_else(|| from.table.clone());
Self { from, key }
}
}
#[derive(Debug, Clone)]
struct Conjunct {
pred: Predicate,
tables: u32,
ambiguous: bool,
}
#[derive(Debug, Clone)]
pub struct JoinGraph {
relations: Vec<Relation>,
conjuncts: Vec<Conjunct>,
}
impl JoinGraph {
pub fn build(plan: &QueryPlan) -> Option<Self> {
let joins = plan.joins.as_ref()?;
if joins.is_empty() {
return None;
}
if joins.iter().any(|join| join.join_type != JoinType::Inner) {
return None;
}
let mut relations = Vec::with_capacity(joins.len() + 1);
relations.push(Relation::new(plan.from.clone()));
for join in joins {
relations.push(Relation::new(join.right_table.clone()));
}
let n = relations.len();
let mut key_index: HashMap<String, usize> = HashMap::with_capacity(n);
for (index, relation) in relations.iter().enumerate() {
if key_index.insert(relation.key.clone(), index).is_some() {
return None;
}
}
let mut conjuncts = Vec::new();
for join in joins {
for pred in split_conjuncts(&join.on) {
let mut tables: u32 = 0;
let mut ambiguous = false;
for (qualifier, _column) in columns_in_predicate(&pred) {
match qualifier.and_then(|q| key_index.get(&q).copied()) {
Some(index) => {
tables |= 1u32 << index;
}
None => ambiguous = true,
}
}
conjuncts.push(Conjunct {
pred,
tables,
ambiguous,
});
}
}
if !Self::is_connected(n, &conjuncts) {
return None;
}
Some(Self {
relations,
conjuncts,
})
}
pub fn relation_count(&self) -> usize {
self.relations.len()
}
fn is_connected(n: usize, conjuncts: &[Conjunct]) -> bool {
let mut parent: Vec<usize> = (0..n).collect();
fn find(parent: &mut [usize], mut x: usize) -> usize {
while parent[x] != x {
parent[x] = parent[parent[x]];
x = parent[x];
}
x
}
for conjunct in conjuncts {
if conjunct.ambiguous || conjunct.tables.count_ones() != 2 {
continue;
}
let bits = conjunct.tables;
let a = bits.trailing_zeros() as usize;
let b = (bits & !(1u32 << a)).trailing_zeros() as usize;
let ra = find(&mut parent, a);
let rb = find(&mut parent, b);
parent[ra] = rb;
}
let root = find(&mut parent, 0);
(1..n).all(|i| find(&mut parent, i) == root)
}
fn connecting(&self, in_set_mask: u32, j: usize) -> Vec<usize> {
let j_bit = 1u32 << j;
let needed = in_set_mask | j_bit;
self.conjuncts
.iter()
.enumerate()
.filter(|(_, conjunct)| {
if conjunct.ambiguous || conjunct.tables & j_bit == 0 {
return false;
}
let remaining = conjunct.tables & !needed;
if remaining != 0 {
return false;
}
conjunct.tables == j_bit || (conjunct.tables & in_set_mask) != 0
})
.map(|(index, _)| index)
.collect()
}
fn combine(&self, indices: &[usize]) -> Option<Predicate> {
combine_conjuncts(
indices
.iter()
.map(|&i| self.conjuncts[i].pred.clone())
.collect(),
)
}
fn assign_conjuncts(&self, order: &[usize]) -> Vec<Vec<usize>> {
let n = order.len();
let mut position = vec![0usize; n];
for (slot, &relation) in order.iter().enumerate() {
position[relation] = slot;
}
let mut steps = vec![Vec::new(); n];
for (index, conjunct) in self.conjuncts.iter().enumerate() {
let step = if conjunct.ambiguous || conjunct.tables == 0 {
n - 1
} else if conjunct.tables.count_ones() == 1 {
let t = conjunct.tables.trailing_zeros() as usize;
position[t].max(1)
} else {
(0..n)
.filter(|&i| conjunct.tables & (1u32 << i) != 0)
.map(|t| position[t])
.max()
.expect("non-empty table set")
};
steps[step].push(index);
}
steps
}
}
#[derive(Debug, Clone)]
pub struct JoinReorderer {
cost: CostEstimator,
}
#[derive(Debug, Clone)]
struct DpEntry {
cost: Cost,
card: u64,
order: Vec<usize>,
}
impl JoinReorderer {
pub fn new(stats_provider: Arc<dyn StatisticsProvider>) -> Self {
Self {
cost: CostEstimator::new(stats_provider),
}
}
pub fn with_cost_estimator(cost: CostEstimator) -> Self {
Self { cost }
}
pub async fn reorder(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
let Some(graph) = JoinGraph::build(plan) else {
return Ok(plan.clone());
};
let n = graph.relation_count();
if n < 2 {
return Ok(plan.clone());
}
let (base_card, scan_cost) = self.base_estimates(&graph).await?;
let order = if n <= MAX_DP_RELATIONS {
self.dp_order(&graph, &base_card, &scan_cost).await?
} else {
self.greedy_order(&graph, &base_card, &scan_cost).await?
};
let identity: Vec<usize> = (0..n).collect();
if order == identity {
return Ok(plan.clone());
}
let (new_cost, _) = self
.cost_of_order(&graph, &order, &base_card, &scan_cost)
.await?;
let (old_cost, _) = self
.cost_of_order(&graph, &identity, &base_card, &scan_cost)
.await?;
if new_cost.total() >= old_cost.total() {
return Ok(plan.clone());
}
Ok(self.rewrite_plan(plan, &graph, &order))
}
pub async fn estimate_plan_cost(&self, plan: &QueryPlan) -> Result<Cost, VlorQLError> {
match JoinGraph::build(plan) {
Some(graph) => {
let (base_card, scan_cost) = self.base_estimates(&graph).await?;
let identity: Vec<usize> = (0..graph.relation_count()).collect();
let (cost, _) = self
.cost_of_order(&graph, &identity, &base_card, &scan_cost)
.await?;
Ok(cost)
}
None => self.cost.estimate_scan(&plan.from.table, None).await,
}
}
async fn base_estimates(
&self,
graph: &JoinGraph,
) -> Result<(Vec<u64>, Vec<Cost>), VlorQLError> {
let n = graph.relation_count();
let mut base_card = Vec::with_capacity(n);
let mut scan_cost = Vec::with_capacity(n);
for relation in &graph.relations {
base_card.push(
self.cost
.cardinality()
.estimate_table_cardinality(&relation.from.table)
.await?,
);
scan_cost.push(self.cost.estimate_scan(&relation.from.table, None).await?);
}
Ok((base_card, scan_cost))
}
async fn greedy_order(
&self,
graph: &JoinGraph,
base_card: &[u64],
scan_cost: &[Cost],
) -> Result<Vec<usize>, VlorQLError> {
let n = graph.relation_count();
let seed = (0..n)
.min_by(|&a, &b| base_card[a].cmp(&base_card[b]).then(a.cmp(&b)))
.unwrap_or(0);
let mut in_set: u32 = 1u32 << seed;
let mut order = vec![seed];
let mut running_cost = scan_cost[seed];
let mut running_card = base_card[seed];
while order.len() < n {
let mut best: Option<(f64, usize, Cost, u64)> = None;
for connected_only in [true, false] {
for j in 0..n {
if in_set & (1u32 << j) != 0 {
continue;
}
let connections = graph.connecting(in_set, j);
if connected_only && connections.is_empty() {
continue;
}
let card = self
.step_cardinality(graph, in_set, running_card, base_card[j], j)
.await?;
let candidate = self.cost.estimate_join(running_cost, scan_cost[j], card);
let score = candidate.total();
if best.is_none_or(|(best_score, ..)| score < best_score) {
best = Some((score, j, candidate, card));
}
}
if best.is_some() {
break;
}
}
let Some((_, j, cost, card)) = best else {
order.extend((0..n).filter(|&j| in_set & (1u32 << j) == 0));
break;
};
in_set |= 1u32 << j;
order.push(j);
running_cost = cost;
running_card = card;
}
Ok(order)
}
async fn dp_order(
&self,
graph: &JoinGraph,
base_card: &[u64],
scan_cost: &[Cost],
) -> Result<Vec<usize>, VlorQLError> {
let n = graph.relation_count();
let full: u32 = (1u32 << n) - 1;
let mut dp: HashMap<u32, DpEntry> = HashMap::new();
for i in 0..n {
dp.insert(
1u32 << i,
DpEntry {
cost: scan_cost[i],
card: base_card[i],
order: vec![i],
},
);
}
let mut masks: Vec<u32> = (1..=full).collect();
masks.sort_by_key(|mask| mask.count_ones());
for mask in masks {
let Some(entry) = dp.get(&mask).cloned() else {
continue;
};
for j in 0..n {
if mask & (1u32 << j) != 0 {
continue;
}
let connections = graph.connecting(mask, j);
if connections.is_empty() {
continue; }
let card = self
.step_cardinality(graph, mask, entry.card, base_card[j], j)
.await?;
let cost = self.cost.estimate_join(entry.cost, scan_cost[j], card);
let new_mask = mask | (1u32 << j);
let seed = entry.order[0];
let better = dp.get(&new_mask).is_none_or(|existing| {
let cheaper = cost.total() < existing.cost.total();
let tied = cost.total() == existing.cost.total();
cheaper || (tied && base_card[seed] < base_card[existing.order[0]])
});
if better {
let mut new_order = entry.order.clone();
new_order.push(j);
dp.insert(
new_mask,
DpEntry {
cost,
card,
order: new_order,
},
);
}
}
}
Ok(dp
.get(&full)
.map(|entry| entry.order.clone())
.unwrap_or_else(|| (0..n).collect()))
}
async fn cost_of_order(
&self,
graph: &JoinGraph,
order: &[usize],
base_card: &[u64],
scan_cost: &[Cost],
) -> Result<(Cost, u64), VlorQLError> {
let seed = order[0];
let mut in_set: u32 = 1u32 << seed;
let mut cost = scan_cost[seed];
let mut card = base_card[seed];
for &j in &order[1..] {
let step_card = self
.step_cardinality(graph, in_set, card, base_card[j], j)
.await?;
cost = self.cost.estimate_join(cost, scan_cost[j], step_card);
card = step_card;
in_set |= 1u32 << j;
}
Ok((cost, card))
}
async fn step_cardinality(
&self,
graph: &JoinGraph,
in_set_mask: u32,
running_card: u64,
base_j: u64,
j: usize,
) -> Result<u64, VlorQLError> {
let connections = graph.connecting(in_set_mask, j);
match graph.combine(&connections) {
Some(pred) => {
self.cost
.cardinality()
.estimate_join_cardinality(running_card, base_j, &pred)
.await
}
None => {
let estimate = running_card as f64 * base_j as f64 * DEFAULT_JOIN_SELECTIVITY;
Ok(estimate.round().clamp(0.0, u64::MAX as f64) as u64)
}
}
}
fn rewrite_plan(&self, plan: &QueryPlan, graph: &JoinGraph, order: &[usize]) -> QueryPlan {
let steps = graph.assign_conjuncts(order);
let mut rewritten = plan.clone();
rewritten.from = graph.relations[order[0]].from.clone();
let mut joins = Vec::with_capacity(order.len() - 1);
for (slot, &relation) in order.iter().enumerate().skip(1) {
let on = graph.combine(&steps[slot]).unwrap_or_else(true_predicate);
joins.push(JoinClause {
join_type: JoinType::Inner,
right_table: graph.relations[relation].from.clone(),
on,
});
}
rewritten.joins = Some(joins);
rewritten
}
}
fn true_predicate() -> Predicate {
use crate::schema::{ComparisonOperator, DataType, Expression};
let one = || Expression::Literal {
value: serde_json::json!(1),
data_type: DataType::Int,
};
Predicate::Comparison {
left: one(),
op: ComparisonOperator::Eq,
right: one(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{
ComparisonOperator, Expression, FromClause, JoinClause, JoinType, Predicate, Projection,
QueryPlan,
};
use crate::statistics::{
ColumnStatistics, DummyStatisticsProvider, StatisticsCatalog, TableStatistics,
};
use std::collections::HashSet;
fn from(table: &str) -> FromClause {
FromClause {
table: table.to_owned(),
alias: None,
}
}
fn col(table: &str, column: &str) -> Expression {
Expression::ColumnRef {
table: Some(table.to_owned()),
column: column.to_owned(),
}
}
fn cmp(left: Expression, op: ComparisonOperator, right: Expression) -> Predicate {
Predicate::Comparison { left, op, right }
}
fn eq(left: Expression, right: Expression) -> Predicate {
cmp(left, ComparisonOperator::Eq, right)
}
fn inner_join(table: &str, on: Predicate) -> JoinClause {
JoinClause {
join_type: JoinType::Inner,
right_table: from(table),
on,
}
}
fn plan_with_joins(from_table: &str, joins: Vec<JoinClause>) -> QueryPlan {
QueryPlan {
select: vec![Projection::Star { table: None }],
from: from(from_table),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: Some(joins),
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}
}
fn table(row_count: u64, columns: &[(&str, u64)]) -> TableStatistics {
let mut stats = TableStatistics {
row_count,
..TableStatistics::default()
};
for (name, distinct) in columns {
stats.columns.insert(
(*name).to_owned(),
ColumnStatistics {
distinct_count: *distinct,
..ColumnStatistics::default()
},
);
}
stats
}
fn reorderer(catalog: StatisticsCatalog) -> JoinReorderer {
JoinReorderer::new(Arc::new(DummyStatisticsProvider::new(catalog)))
}
fn on_conjuncts(plan: &QueryPlan) -> Vec<String> {
let mut out = Vec::new();
if let Some(joins) = &plan.joins {
for join in joins {
for pred in split_conjuncts(&join.on) {
out.push(serde_json::to_string(&pred).expect("predicate serializes"));
}
}
}
out.sort();
out
}
fn relation_names(plan: &QueryPlan) -> HashSet<String> {
let mut names = HashSet::new();
names.insert(plan.from.table.clone());
if let Some(joins) = &plan.joins {
for join in joins {
names.insert(join.right_table.table.clone());
}
}
names
}
#[tokio::test]
async fn three_table_join_starts_from_smallest_base_table() {
let mut catalog = StatisticsCatalog::default();
catalog
.tables
.insert("users".to_owned(), table(10_000, &[("id", 10_000)]));
catalog.tables.insert(
"orders".to_owned(),
table(50_000, &[("user_id", 8_000), ("id", 50_000)]),
);
catalog
.tables
.insert("items".to_owned(), table(100, &[("order_id", 100)]));
let plan = plan_with_joins(
"users",
vec![
inner_join("orders", eq(col("users", "id"), col("orders", "user_id"))),
inner_join("items", eq(col("orders", "id"), col("items", "order_id"))),
],
);
let reorderer = reorderer(catalog);
let original_cost = reorderer.estimate_plan_cost(&plan).await.unwrap();
let reordered = reorderer.reorder(&plan).await.unwrap();
assert_eq!(reordered.from.table, "items");
assert_eq!(relation_names(&reordered), relation_names(&plan));
assert_eq!(on_conjuncts(&plan), on_conjuncts(&reordered));
let joins = reordered.joins.as_ref().unwrap();
assert_eq!(joins.len(), 2);
assert!(joins.iter().all(|j| j.join_type == JoinType::Inner));
let reordered_cost = reorderer.estimate_plan_cost(&reordered).await.unwrap();
assert!(
reordered_cost.total() < original_cost.total(),
"expected {reordered_cost:?} < {original_cost:?}"
);
}
#[tokio::test]
async fn non_equi_join_condition_degrades_to_default_selectivity() {
let mut catalog = StatisticsCatalog::default();
catalog
.tables
.insert("a".to_owned(), table(100, &[("x", 100)]));
catalog.tables.insert(
"b".to_owned(),
table(50_000, &[("x", 40_000), ("y", 50_000)]),
);
catalog
.tables
.insert("c".to_owned(), table(10_000, &[("y", 10_000)]));
let plan = plan_with_joins(
"c",
vec![
inner_join(
"b",
cmp(col("b", "y"), ComparisonOperator::Gt, col("c", "y")),
),
inner_join("a", eq(col("a", "x"), col("b", "x"))),
],
);
let reorderer = reorderer(catalog);
let reordered = reorderer.reorder(&plan).await.unwrap();
assert_eq!(on_conjuncts(&plan), on_conjuncts(&reordered));
assert_eq!(relation_names(&reordered), relation_names(&plan));
assert_eq!(reordered.from.table, "a");
let original_cost = reorderer.estimate_plan_cost(&plan).await.unwrap();
let reordered_cost = reorderer.estimate_plan_cost(&reordered).await.unwrap();
assert!(
reordered_cost.total() < original_cost.total(),
"expected {reordered_cost:?} < {original_cost:?}"
);
}
#[tokio::test]
async fn missing_statistics_fall_back_to_default_cardinality() {
let plan = plan_with_joins(
"users",
vec![
inner_join("orders", eq(col("users", "id"), col("orders", "user_id"))),
inner_join("items", eq(col("orders", "id"), col("items", "order_id"))),
],
);
let reorderer = reorderer(StatisticsCatalog::default());
let reordered = reorderer.reorder(&plan).await.unwrap();
assert_eq!(reordered, plan);
}
#[tokio::test]
async fn left_join_is_left_unchanged() {
let plan = plan_with_joins(
"users",
vec![JoinClause {
join_type: JoinType::Left,
right_table: from("orders"),
on: eq(col("users", "id"), col("orders", "user_id")),
}],
);
assert!(JoinGraph::build(&plan).is_none());
let reorderer = reorderer(StatisticsCatalog::default());
assert_eq!(reorderer.reorder(&plan).await.unwrap(), plan);
}
#[tokio::test]
async fn disconnected_join_graph_is_left_unchanged() {
let plan = plan_with_joins(
"users",
vec![
inner_join(
"accounts",
eq(col("users", "id"), col("accounts", "user_id")),
),
inner_join("orders", eq(col("orders", "a"), col("orders", "b"))),
],
);
assert!(JoinGraph::build(&plan).is_none());
}
}