use std::cmp::Reverse;
use std::collections::HashSet;
use relate_ir::{Expr, NodePattern, PathPattern, PatternElement, RelPattern};
use relate_names::NamedToken;
use crate::stats::{NoPatternStats, PatternStats};
mod estimate;
mod junction;
mod selectivity;
mod strategy;
#[cfg(test)]
mod strategy_tests;
pub use estimate::{
best_seek, crossover_scan_rows, endpoint_estimate, range_seek_gated, where_conjuncts_of, Basis,
Bound, Estimate, SeekPick,
};
use estimate::{endpoint_bound, label_hits, RANK_BARE};
pub use junction::{
can_reverse_varlen_leg, detect_junction_split, junction_legs_have_cross_inline_refs,
reverse_varlen_leg, split_junction_legs, JunctionSplitPoint,
};
pub(crate) use strategy::plan_match_strategies;
pub use strategy::{
evaluate_cross_clause_cost, CrossClauseCost, CrossClauseSearchEnd, MatchStrategy,
HASH_JOIN_MIN_SIDE_ROWS,
};
fn orientation_locked(path: &PathPattern) -> bool {
path.has_path_name()
|| !path.has_compact_alternating_elements()
|| path.nodes.len() < 2
|| path
.rels
.iter()
.any(|rel| rel.var_length && rel.variable.is_some())
}
pub fn can_reverse_path(path: &PathPattern, bound: Bound<'_>) -> bool {
!orientation_locked(path) && reversal_safe(path, bound)
}
fn reversal_safe(path: &PathPattern, bound: Bound<'_>) -> bool {
let own = |var: &str| {
path.nodes
.iter()
.any(|n| n.variable.as_ref().is_some_and(|v| v == var))
|| path
.rels
.iter()
.any(|r| r.variable.as_ref().is_some_and(|v| v == var))
};
let mut refs = HashSet::new();
for node in &path.nodes {
let mut node_refs = HashSet::new();
if let Some(e) = &node.properties {
relate_ir::expr_vars(e, &mut node_refs);
}
if let Some(e) = &node.where_clause {
relate_ir::expr_vars(e, &mut node_refs);
}
if let Some(le) = &node.label_expr {
relate_ir::label_expr_vars(le, &mut node_refs);
}
if let Some(self_var) = &node.variable {
self_var.with_str(|s| {
node_refs.remove(s);
});
}
refs.extend(node_refs);
}
for rel in &path.rels {
let mut rel_refs = HashSet::new();
if let Some(e) = &rel.properties {
relate_ir::expr_vars(e, &mut rel_refs);
}
if let Some(e) = &rel.where_clause {
relate_ir::expr_vars(e, &mut rel_refs);
}
if let Some(self_var) = &rel.variable {
self_var.with_str(|s| {
rel_refs.remove(s);
});
}
refs.extend(rel_refs);
}
!refs.iter().any(|var| own(var) && !bound(var.as_str()))
}
#[derive(Clone, Copy)]
struct DirectionCost {
walked: u128,
seed: u128,
basis: Basis,
}
fn direction_cost(
path: &PathPattern,
reversed: bool,
bound: Bound<'_>,
where_conjuncts: &[&Expr],
stats: &dyn PatternStats,
) -> DirectionCost {
if path.nodes.is_empty() {
return DirectionCost {
walked: RANK_BARE,
seed: RANK_BARE,
basis: Basis::Rank,
};
}
let seed = if reversed {
path.nodes.last().expect("nodes is non-empty")
} else {
path.nodes.first().expect("nodes is non-empty")
};
let estimate = endpoint_estimate(seed, bound, where_conjuncts.iter().copied(), stats);
let walked = if reversed {
walk_cost(
estimate,
path.nodes
.iter()
.rev()
.zip(path.rels.iter().rev())
.map(|(node, rel)| (node, rel, seed_on_rel_start(rel, true))),
stats,
)
} else {
walk_cost(
estimate,
path.nodes
.iter()
.zip(path.rels.iter())
.map(|(node, rel)| (node, rel, seed_on_rel_start(rel, false))),
stats,
)
};
DirectionCost {
walked,
seed: seed_rows(estimate),
basis: estimate.basis(),
}
}
pub fn seed_on_rel_start(rel: &RelPattern, reversed: bool) -> bool {
match rel.direction {
relate_ir::Direction::Outgoing => !reversed,
relate_ir::Direction::Incoming => reversed,
relate_ir::Direction::Both => false,
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum HopRows {
Seeds,
Paths,
}
pub fn apply_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
) -> u128 {
scale_degree(rows, start, rel, seed_is_start, stats, HopRows::Seeds)
}
pub fn apply_path_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
) -> u128 {
scale_degree(rows, start, rel, seed_is_start, stats, HopRows::Paths)
}
fn scale_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
hop_rows: HopRows,
) -> u128 {
priced_degree(rows, start, rel, seed_is_start, stats, hop_rows).unwrap_or(rows)
}
enum RelTypes<'a> {
None,
One(&'a NamedToken),
Many,
}
impl<'a> RelTypes<'a> {
fn of(rel: &'a RelPattern) -> Self {
match rel.types.as_slice() {
[] => Self::None,
[one] => Self::One(one),
_ => Self::Many,
}
}
}
pub fn apply_hop_bound(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
) -> u128 {
if let Some(priced) = priced_degree(rows, start, rel, seed_is_start, stats, HopRows::Seeds) {
return priced;
}
if !seed_is_start {
return rows;
}
let rel_type = match RelTypes::of(rel) {
RelTypes::One((rel_type, _)) => Some(rel_type),
RelTypes::None | RelTypes::Many => None,
};
stats
.any_degree_tail(rel_type)
.map_or(rows, |tail| rows.saturating_mul(u128::from(tail)))
}
fn priced_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
hop_rows: HopRows,
) -> Option<u128> {
let RelTypes::One(rel_type) = RelTypes::of(rel) else {
return None;
};
if seed_is_start {
if let Some(tail) = start
.labels
.iter()
.filter_map(|label| stats.degree_tail(label, rel_type))
.min()
{
let scaled = rows.saturating_mul(u128::from(tail));
return Some(match (hop_rows, stats.rel_type_rows(rel_type)) {
(HopRows::Seeds, Some(total)) => scaled.min(u128::from(total)),
_ => scaled,
});
}
}
let rel_rows = stats.rel_type_rows(rel_type)?;
let label_rows = label_hits(start, stats)?;
if label_rows == 0 {
return None;
}
let scaled = rows.saturating_mul(u128::from(rel_rows)) / u128::from(label_rows);
Some(if rows > 0 && rel_rows > 0 && scaled == 0 {
1
} else {
scaled
})
}
pub fn seed_rows(estimate: Estimate) -> u128 {
walk_cost(estimate, std::iter::empty::<Hop<'_>>(), &NoPatternStats)
}
pub type Hop<'a> = (&'a NodePattern, &'a RelPattern, bool);
fn degree_walk<'a>(
rows: u128,
hops: impl Iterator<Item = Hop<'a>>,
stats: &dyn PatternStats,
) -> u128 {
let mut output = rows;
for (node, rel, seed_is_start) in hops {
output = apply_degree(output, node, rel, seed_is_start, stats);
}
output
}
pub fn walk_cost<'a>(
estimate: Estimate,
hops: impl Iterator<Item = Hop<'a>>,
stats: &dyn PatternStats,
) -> u128 {
match estimate {
Estimate::Measured(rows) => degree_walk(rows, hops, stats),
Estimate::Scanned { rows, scan, .. } => degree_walk(rows, hops, stats).max(scan),
Estimate::Rank(rows) => rows,
}
}
fn choose_orientation(
path: &PathPattern,
bound: Bound<'_>,
where_conjuncts: &[&Expr],
stats: &dyn PatternStats,
) -> (bool, u128) {
let forced = match (path.nodes.first(), path.nodes.last()) {
(Some(first), Some(last)) if can_reverse_path(path, bound) => {
let first_bound = endpoint_bound(first, bound);
let last_bound = endpoint_bound(last, bound);
if first_bound && !last_bound {
Some(false)
} else if last_bound && !first_bound {
Some(true)
} else {
None
}
}
_ => Some(false),
};
if let Some(reversed) = forced {
return (
reversed,
direction_cost(path, reversed, bound, where_conjuncts, stats).walked,
);
}
let written = direction_cost(path, false, bound, where_conjuncts, stats);
let flipped = direction_cost(path, true, bound, where_conjuncts, stats);
let flip = (flipped.walked, flipped.seed, Reverse(flipped.basis))
< (written.walked, written.seed, Reverse(written.basis));
if flip {
(true, flipped.walked)
} else {
(false, written.walked)
}
}
fn pattern_touches(path: &PathPattern, bound: Bound<'_>) -> bool {
relate_ir::path_pattern_vars(path).any(|var| var.with_str(|text| bound(text)))
}
pub fn reverse_path(path: &mut PathPattern) {
path.nodes.reverse();
path.rels.reverse();
for rel in &mut path.rels {
rel.direction = rel.direction.flip();
}
if path.elements.len() == path.nodes.len() + path.rels.len() {
path.elements.reverse();
for element in &mut path.elements {
if let PatternElement::Relationship(rel) = element {
rel.direction = rel.direction.flip();
}
}
}
}
pub(crate) fn order_patterns(
patterns: &mut Vec<PathPattern>,
prebound: &HashSet<String>,
where_clause: Option<&Expr>,
stats: &dyn PatternStats,
) {
let mut bound = prebound.clone();
let where_conjuncts = where_conjuncts_of(where_clause);
let mut pending: Vec<(usize, PathPattern)> =
std::mem::take(patterns).into_iter().enumerate().collect();
let mut chosen = Vec::with_capacity(pending.len());
while !pending.is_empty() {
let bound_view = |name: &str| bound.contains(name);
let connected_exists = !chosen.is_empty()
&& pending
.iter()
.any(|(_, path)| pattern_touches(path, &bound_view));
let (index, (reversed, _)) = pending
.iter()
.enumerate()
.filter(|(_, (_, path))| !connected_exists || pattern_touches(path, &bound_view))
.map(|(index, (_, path))| {
(
index,
choose_orientation(path, &bound_view, &where_conjuncts, stats),
)
})
.min_by_key(|&(index, (_, cost))| (cost, pending[index].0))
.expect("candidate set is non-empty");
let (_, mut path) = pending.remove(index);
if reversed {
reverse_path(&mut path);
}
add_pattern_vars(&mut bound, &path);
chosen.push(path);
}
*patterns = chosen;
}
fn add_pattern_vars(bound: &mut HashSet<String>, p: &PathPattern) {
bound.extend(
relate_ir::pattern_anchor_variables(p)
.into_iter()
.map(|name| name.to_string()),
);
}
#[cfg(test)]
mod tests;