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 = match &from {
FromClause::Table { table, alias } => alias.clone().unwrap_or_else(|| table.clone()),
FromClause::Subquery { alias, .. } => {
alias.clone().unwrap_or_else(|| "<subquery>".to_owned())
}
};
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_name()
.expect("FROM must have a table name in join reorder"),
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_name()
.expect("relation must have a table name in join reorder"),
)
.await?,
);
scan_cost.push(
self.cost
.estimate_scan(
relation
.from
.table_name()
.expect("relation must have a table name in join reorder"),
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: Box::new(one()),
op: ComparisonOperator::Eq,
right: Box::new(one()),
}
}
#[cfg(test)]
mod tests;