use hawdb_plan_cypher::{
AggregateFunction, AggregateTarget, GraphEntityKind, GraphMatchNode, GraphMatchProgram,
GraphMatchStep, PhysicalPlan, Predicate, ProjectionExpression, SortItem, SortKey,
};
use std::collections::{BTreeMap, BTreeSet};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, PartialEq, Eq)]
enum Need {
Whole,
Properties(BTreeSet<String>),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Demand(BTreeMap<String, Need>);
impl Demand {
fn whole(&mut self, variable: &str) {
self.0.insert(variable.to_string(), Need::Whole);
}
fn identity(&mut self, variable: &str) {
self.0
.entry(variable.to_string())
.or_insert_with(|| Need::Properties(BTreeSet::new()));
}
fn property(&mut self, variable: &str, property: &str) {
let need = self
.0
.entry(variable.to_string())
.or_insert_with(|| Need::Properties(BTreeSet::new()));
if let Need::Properties(properties) = need {
properties.insert(property.to_string());
}
}
fn merge(&mut self, other: &Demand) {
for (variable, need) in &other.0 {
match need {
Need::Whole => self.whole(variable),
Need::Properties(properties) => {
self.identity(variable);
for property in properties {
self.property(variable, property);
}
}
}
}
}
fn projection(&self, variable: &str) -> Option<BTreeSet<String>> {
match self.0.get(variable) {
None => Some(BTreeSet::new()),
Some(Need::Properties(properties)) => Some(properties.clone()),
Some(Need::Whole) => None,
}
}
}
pub(super) fn project_graph_match_reads(
plan: PhysicalPlan,
decisions: &mut Vec<String>,
) -> PhysicalPlan {
if !returns_values(&plan) {
return plan;
}
let mut walk = Walk::default();
let plan = project(plan, Demand::default(), false, &mut walk);
if !walk.projected.is_empty() {
decisions.push(format!(
"GraphMatchExec reads only the node and relationship properties later operators use: {}",
walk.projected.join(", ")
));
}
if !walk.consumed.is_empty() {
decisions.push(format!(
"UnwindRowsExec takes its source column out of each row instead of copying it into \
every output row, because no later operator reads it: {}",
walk.consumed.join(", ")
));
}
plan
}
fn returns_values(plan: &PhysicalPlan) -> bool {
match plan {
PhysicalPlan::ProjectExec { .. } | PhysicalPlan::AggregateExec { .. } => true,
PhysicalPlan::LimitExec { input, .. }
| PhysicalPlan::DistinctExec { input }
| PhysicalPlan::SortExec { input, .. }
| PhysicalPlan::TopNExec { input, .. }
| PhysicalPlan::FilterExec { input, .. } => returns_values(input),
_ => false,
}
}
#[derive(Default)]
struct Walk {
projected: Vec<String>,
consumed: Vec<String>,
}
fn project(
plan: PhysicalPlan,
mut demand: Demand,
compared: bool,
walk: &mut Walk,
) -> PhysicalPlan {
match plan {
PhysicalPlan::ProjectExec { items, input } => {
for item in &items {
expression(&item.expression, &mut demand);
}
PhysicalPlan::ProjectExec {
items,
input: Box::new(project(*input, demand, false, walk)),
}
}
PhysicalPlan::AggregateExec {
group_keys,
items,
input,
} => {
for key in &group_keys {
expression(&key.expression, &mut demand);
}
for item in &items {
aggregate(item.function, &item.target, &mut demand);
}
PhysicalPlan::AggregateExec {
group_keys,
items,
input: Box::new(project(*input, demand, false, walk)),
}
}
PhysicalPlan::FilterExec { predicate, input } => {
self::predicate(&predicate, &mut demand);
PhysicalPlan::FilterExec {
predicate,
input: Box::new(project(*input, demand, compared, walk)),
}
}
PhysicalPlan::SortExec { items, input } => {
sort_items(&items, &mut demand);
PhysicalPlan::SortExec {
items,
input: Box::new(project(*input, demand, compared, walk)),
}
}
PhysicalPlan::TopNExec {
items,
offset,
limit,
input,
} => {
sort_items(&items, &mut demand);
PhysicalPlan::TopNExec {
items,
offset,
limit,
input: Box::new(project(*input, demand, compared, walk)),
}
}
PhysicalPlan::LimitExec {
offset,
limit,
input,
} => PhysicalPlan::LimitExec {
offset,
limit,
input: Box::new(project(*input, demand, compared, walk)),
},
PhysicalPlan::DistinctExec { input } => PhysicalPlan::DistinctExec {
input: Box::new(project(*input, demand, true, walk)),
},
PhysicalPlan::GraphMatchExec { program, input } => {
let (program, mut input_demand) =
project_program(program, &demand, &mut walk.projected);
for import in &program.imports {
input_demand.identity(&import.column);
}
PhysicalPlan::GraphMatchExec {
program,
input: input.map(|input| Box::new(project(*input, input_demand, compared, walk))),
}
}
PhysicalPlan::UnwindRowsExec {
expression,
variable,
consumes_source,
input,
} => {
let consumes_source = consumes_source
|| matches!(
&expression,
ProjectionExpression::Column(column)
if column != &variable && !compared && !demand.0.contains_key(column)
);
if consumes_source && let ProjectionExpression::Column(column) = &expression {
walk.consumed.push(column.clone());
}
demand.0.remove(&variable);
self::expression(&expression, &mut demand);
PhysicalPlan::UnwindRowsExec {
expression,
variable,
consumes_source,
input: Box::new(project(*input, demand, compared, walk)),
}
}
plan => plan,
}
}
fn project_program(
mut program: GraphMatchProgram,
demand: &Demand,
projected: &mut Vec<String>,
) -> (GraphMatchProgram, Demand) {
let own = program_demand(&program);
let bound = program
.introduced
.iter()
.chain(program.imports.iter().map(|import| &import.variable))
.cloned()
.collect::<BTreeSet<_>>();
let mut nodes = program
.imports
.iter()
.filter(|import| import.kind == GraphEntityKind::Node)
.map(|import| import.variable.clone())
.collect::<BTreeSet<_>>();
let mut relationships = BTreeSet::new();
for step in &program.steps {
match step {
GraphMatchStep::Node(node) => nodes.insert(node.variable.clone()),
GraphMatchStep::Expand {
relationship,
target,
min_hops,
max_hops,
..
} => {
if let Some(relationship) = relationship
&& *min_hops == 1
&& *max_hops == 1
{
relationships.insert(relationship.clone());
}
nodes.insert(target.variable.clone())
}
GraphMatchStep::ShortestPath(_) => false,
};
}
for import in &program.imports {
relationships.remove(&import.variable);
}
let mut total = demand.clone();
total.merge(&own);
let mut projected_nodes = BTreeMap::new();
for variable in nodes.iter().filter(|variable| bound.contains(*variable)) {
if let Some(properties) = total.projection(variable) {
projected.push(format!(
"{variable}[{}]",
properties.iter().cloned().collect::<Vec<_>>().join(",")
));
projected_nodes.insert(variable.clone(), properties);
}
}
program.projected_nodes = projected_nodes;
let mut projected_relationships = BTreeMap::new();
for variable in relationships
.iter()
.filter(|variable| bound.contains(*variable))
{
if let Some(properties) = total.projection(variable) {
projected.push(format!(
"relationship {variable}[{}]",
properties.iter().cloned().collect::<Vec<_>>().join(",")
));
projected_relationships.insert(variable.clone(), properties);
}
}
program.projected_relationships = projected_relationships;
let input = Demand(
total
.0
.into_iter()
.filter(|(variable, _)| !bound.contains(variable))
.collect(),
);
(program, input)
}
fn program_demand(program: &GraphMatchProgram) -> Demand {
fn node(node: &GraphMatchNode, demand: &mut Demand) {
demand.identity(&node.variable);
for property in node.properties.keys() {
demand.property(&node.variable, property);
}
}
let mut demand = Demand::default();
for step in &program.steps {
match step {
GraphMatchStep::Node(pattern) => node(pattern, &mut demand),
GraphMatchStep::Expand {
source,
relationship,
properties,
target,
..
} => {
demand.identity(source);
if let Some(relationship) = relationship {
demand.identity(relationship);
for property in properties.keys() {
demand.property(relationship, property);
}
}
node(target, &mut demand);
}
GraphMatchStep::ShortestPath(step) => {
demand.identity(&step.source);
demand.identity(&step.target);
demand.whole(&step.path);
}
}
}
if let Some(predicate) = &program.predicate {
self::predicate(predicate, &mut demand);
}
demand
}
fn sort_items(items: &[SortItem], demand: &mut Demand) {
for item in items {
match &item.key {
SortKey::Property { variable, property } => demand.property(variable, property),
SortKey::Id { variable } => demand.identity(variable),
SortKey::Expression(expression) => self::expression(expression, demand),
SortKey::Column(column) => demand.whole(column),
}
}
}
fn aggregate(function: AggregateFunction, target: &AggregateTarget, demand: &mut Demand) {
match target {
AggregateTarget::All => {}
AggregateTarget::Variable(variable) if function == AggregateFunction::Count => {
demand.identity(variable)
}
AggregateTarget::Variable(variable) | AggregateTarget::Column(variable) => {
demand.whole(variable)
}
AggregateTarget::ColumnProperty { column, .. } => demand.whole(column),
AggregateTarget::Property { variable, property } => demand.property(variable, property),
AggregateTarget::Ranked {
document_id, score, ..
} => {
demand.whole(document_id);
demand.whole(score);
}
AggregateTarget::Expression(expression) => self::expression(expression, demand),
}
}
fn predicate(predicate: &Predicate, demand: &mut Demand) {
match predicate {
Predicate::And(predicates) | Predicate::Or(predicates) => {
for predicate in predicates {
self::predicate(predicate, demand);
}
}
Predicate::Not(predicate) => self::predicate(predicate, demand),
Predicate::ConstantBool(_) => {}
Predicate::RelationshipExists { variable, .. } => demand.identity(variable),
Predicate::BoundRelationshipExists {
source_variable,
target_variable,
..
} => {
demand.identity(source_variable);
demand.identity(target_variable);
}
Predicate::IdEq { variable, .. }
| Predicate::IdNotEq { variable, .. }
| Predicate::IdCompare { variable, .. }
| Predicate::IdIn { variable, .. } => demand.identity(variable),
Predicate::PropertyEq {
variable, property, ..
}
| Predicate::PropertyNotEq {
variable, property, ..
}
| Predicate::PropertyCompare {
variable, property, ..
}
| Predicate::PropertyListContains {
variable, property, ..
}
| Predicate::PropertyListContainsLower {
variable, property, ..
}
| Predicate::PropertyContains {
variable, property, ..
}
| Predicate::PropertyStartsWith {
variable, property, ..
}
| Predicate::PropertyEndsWith {
variable, property, ..
}
| Predicate::PropertyRegexMatch {
variable, property, ..
}
| Predicate::PropertyIsNull { variable, property }
| Predicate::PropertyIsNotNull { variable, property }
| Predicate::PropertyIn {
variable, property, ..
} => demand.property(variable, property),
Predicate::ExpressionEq { expression, value }
| Predicate::ExpressionNotEq { expression, value }
| Predicate::ExpressionCompare {
expression, value, ..
}
| Predicate::ExpressionContains { expression, value } => {
self::expression(expression, demand);
self::expression(value, demand);
}
Predicate::ExpressionRegexMatch { expression, .. } => {
self::expression(expression, demand);
}
Predicate::ExpressionIn { expression, .. } => self::expression(expression, demand),
}
}
fn expression(expression: &ProjectionExpression, demand: &mut Demand) {
match expression {
ProjectionExpression::Variable { variable }
| ProjectionExpression::RelationshipType { variable } => demand.whole(variable),
ProjectionExpression::Column(column)
| ProjectionExpression::ColumnProperty { column, .. }
| ProjectionExpression::ColumnDefaultIfNullOrEq { column, .. }
| ProjectionExpression::ColumnValueDefaultIfNull { column, .. }
| ProjectionExpression::ColumnValueCasePropertyNotNullOrEq { column, .. }
| ProjectionExpression::Path { column, .. } => demand.whole(column),
ProjectionExpression::CaseColumnSearchRank(rank) => demand.whole(&rank.column),
ProjectionExpression::Id { variable } => demand.identity(variable),
ProjectionExpression::RelationshipEndpoint {
variable,
endpoints,
..
} => {
demand.identity(variable);
for node in endpoints.iter().flatten() {
demand.whole(node);
}
}
ProjectionExpression::Property { variable, property }
| ProjectionExpression::DatePart {
variable, property, ..
}
| ProjectionExpression::DefaultIfNullOrEq {
variable, property, ..
}
| ProjectionExpression::DefaultIfNull {
variable, property, ..
}
| ProjectionExpression::CasePropertyNotNullOrEq {
variable, property, ..
}
| ProjectionExpression::CasePropertyEqualsRank {
variable, property, ..
}
| ProjectionExpression::CaseLowerPropertyDefault {
variable, property, ..
} => demand.property(variable, property),
ProjectionExpression::CaseCoalesceDifferenceFloorZero { variable, terms } => {
demand.identity(variable);
for term in terms {
demand.property(variable, &term.property);
}
}
ProjectionExpression::CaseEntitySearchRank(rank) => {
demand.property(&rank.variable, &rank.name_property);
demand.property(&rank.variable, &rank.aliases_property);
}
ProjectionExpression::Literal(_) | ProjectionExpression::LocalVariable { .. } => {}
ProjectionExpression::Pattern(pattern) => {
for name in pattern.graph_variables.iter().chain(&pattern.columns) {
demand.whole(name);
}
for argument in pattern
.arguments
.iter()
.map(|(_, argument)| argument)
.chain(pattern.seeds.iter().flat_map(|seeds| &seeds.expressions))
{
self::expression(argument, demand);
}
}
ProjectionExpression::Coalesce(_)
| ProjectionExpression::VectorDistance { .. }
| ProjectionExpression::JsonValue { .. }
| ProjectionExpression::Left { .. }
| ProjectionExpression::Lower(_)
| ProjectionExpression::Case { .. }
| ProjectionExpression::Binary { .. }
| ProjectionExpression::Not(_)
| ProjectionExpression::IsNull { .. }
| ProjectionExpression::List(_)
| ProjectionExpression::ListFunction { .. }
| ProjectionExpression::StringFunction { .. }
| ProjectionExpression::ListComprehension(_)
| ProjectionExpression::ListIndex { .. }
| ProjectionExpression::ListSlice { .. }
| ProjectionExpression::Conversion { .. }
| ProjectionExpression::NumericFunction { .. }
| ProjectionExpression::Reduce(_)
| ProjectionExpression::TemporalFunction { .. }
| ProjectionExpression::PropertyAccess { .. }
| ProjectionExpression::RelationshipValueEndpoint { .. }
| ProjectionExpression::MapLiteral(_) => {
expression.all_children(|child| {
self::expression(child, demand);
true
});
}
}
}