use std::collections::HashSet;
use indexmap::IndexMap;
use relate_core::{Result, Value};
use relate_ir::{Clause, Expr, MatchMode, OrderItem, PathPattern, Projection};
use relate_names::SmallName;
use crate::ctx::ExecCtx;
use crate::group_key::GroupKey;
use crate::overlay::{ExecGraph, RetainedTotal};
use crate::row::Row;
use super::order::{park_order_keys, OrderKeys};
use super::project::{project_rows, return_result, RowSource};
use super::scope::ProjectionFields;
use super::{QueryResult, RowFeed};
pub(super) enum Pop<'a> {
Label(&'a SmallName),
Any,
No,
}
pub(super) fn node_population(np: &relate_ir::NodePattern) -> Pop<'_> {
let plain = np.properties.is_none() && np.where_clause.is_none();
if np.labels.len() == 1 && plain && super::label_expr_ok(&np.label_expr, &np.labels) {
Pop::Label(&np.labels[0].0)
} else if np.labels.is_empty() && np.label_expr.is_none() && plain {
Pop::Any
} else {
Pop::No
}
}
pub(super) fn plain_match_pattern(clause: &Clause) -> Option<&PathPattern> {
let Clause::Match {
optional: false,
match_mode: MatchMode::DifferentRelationships,
patterns,
where_clause: None,
search: None,
using_index: _,
using_join: _,
} = clause
else {
return None;
};
let [pattern] = &patterns[..] else {
return None;
};
if pattern.where_clause.is_some() || pattern.mode.is_some() || pattern.selector.is_some() {
return None;
}
Some(pattern)
}
pub(super) fn match_return_pattern(clauses: &[Clause]) -> Option<&PathPattern> {
if clauses.len() != 2 {
return None;
}
plain_match_pattern(&clauses[0])
}
fn single_node_population(pattern: &PathPattern) -> Option<(&SmallName, Pop<'_>)> {
let ([node], true) = (&pattern.nodes[..], pattern.rels.is_empty()) else {
return None;
};
Some((node.variable.as_ref()?, node_population(node)))
}
pub(super) fn whole_population_node_var(pattern: &PathPattern) -> Option<&SmallName> {
match single_node_population(pattern)? {
(var, Pop::Any) => Some(var),
(_, Pop::Label(_) | Pop::No) => None,
}
}
pub(super) fn single_label_node(pattern: &PathPattern) -> Option<(&SmallName, &SmallName)> {
match single_node_population(pattern)? {
(var, Pop::Label(label)) => Some((var, label)),
(_, Pop::Any | Pop::No) => None,
}
}
#[derive(Clone, Copy, Debug)]
pub(super) enum Count<'a> {
Star,
Of(&'a SmallName),
}
pub(super) fn count_of(expr: &Expr) -> Option<Count<'_>> {
match expr {
Expr::CountStar => Some(Count::Star),
Expr::Function {
name,
distinct: false,
args,
} if name.with_str(relate_ir::classify_aggregate)
== Some(relate_ir::AggregateKind::Count) =>
{
match &args[..] {
[Expr::Variable(v)] => Some(Count::Of(v)),
_ => None,
}
}
_ => None,
}
}
pub(super) fn is_node_count(expr: &Expr, var: &SmallName) -> bool {
match count_of(expr) {
Some(Count::Star) => true,
Some(Count::Of(v)) => v == var,
None => false,
}
}
pub(super) struct GroupedPage<'a> {
pub(super) order: Vec<OrderItem>,
pub(super) skip: Option<&'a Expr>,
pub(super) limit: Option<&'a Expr>,
}
pub(super) fn finish_grouped_rows(
ctx: ExecCtx<'_>,
clauses: &[Clause],
items: &[Projection],
page: GroupedPage<'_>,
mut grouped: Vec<Row>,
scope: Option<&Row>,
) -> Result<(Vec<Row>, QueryResult)> {
let identity: Vec<Projection> = super::scope::projection_names(items)
.into_iter()
.map(|name| Projection {
expr: Expr::Variable(SmallName::from_name(&name)),
alias: Some(SmallName::from_name(&name)),
source_text: None,
})
.collect();
let order_keys = OrderKeys::new(&page.order, &identity, false);
for row in &mut grouped {
park_order_keys(&order_keys, row, |expr, scope| {
crate::eval::eval(ctx.graph, scope, expr, ctx.params)
})?;
}
let mut rows = project_rows(
ctx,
RowFeed::Held(grouped),
&ProjectionFields {
items: &identity,
distinct: false,
group_by: None,
order: &page.order,
skip: page.skip,
limit: page.limit,
where_clause: None,
},
true,
RowSource::SinkProjected,
scope,
)?;
let result = return_result(ctx.graph, items, clauses, &mut rows)?;
Ok((rows, result))
}
pub(super) struct CountedGroups {
table: IndexMap<Vec<GroupKey>, (Vec<Value>, u64)>,
}
impl CountedGroups {
pub(super) fn new() -> Self {
CountedGroups {
table: IndexMap::new(),
}
}
pub(super) fn add(
&mut self,
graph: &ExecGraph<'_>,
retained: &mut RetainedTotal,
keys: Vec<Value>,
count: u64,
) -> Result<()> {
let identity: Vec<GroupKey> = keys.iter().map(GroupKey::new).collect();
self.land(graph, retained, &identity, keys, count)
}
pub(super) fn add_one(
&mut self,
graph: &ExecGraph<'_>,
retained: &mut RetainedTotal,
value: &Value,
count: u64,
) -> Result<()> {
let identity = GroupKey::new(value);
self.land(
graph,
retained,
std::slice::from_ref(&identity),
vec![value.clone()],
count,
)
}
fn land(
&mut self,
graph: &ExecGraph<'_>,
retained: &mut RetainedTotal,
identity: &[GroupKey],
keys: Vec<Value>,
count: u64,
) -> Result<()> {
if let Some((_, n)) = self.table.get_mut(identity) {
*n = n
.checked_add(count)
.expect("count overflow: a group sum past u64 is a broken store");
return Ok(());
}
for key in &keys {
retained.add_owned(graph, key)?;
}
retained.add_group_landing(
graph,
self.table.len(),
identity,
keys.len(),
crate::overlay::SeatShape::ZERO_SEATS,
)?;
self.table.insert(identity.to_vec(), (keys, count));
Ok(())
}
pub(super) fn into_rows(
self,
graph: &ExecGraph<'_>,
retained: &mut RetainedTotal,
mut row_of: impl FnMut(Vec<Value>, u64) -> Row,
) -> Result<Vec<Row>> {
let mut rows = Vec::with_capacity(self.table.len());
for (_, (keys, count)) in self.table {
let row = row_of(keys, count);
retained.add_row(graph, row.values())?;
rows.push(row);
}
Ok(rows)
}
pub(super) fn total_count(&self) -> u64 {
self.table.values().fold(0u64, |total, (_, n)| {
total
.checked_add(*n)
.expect("count overflow: a group sum past u64 is a broken store")
})
}
}
pub(super) fn node_vars_unique(pattern: &PathPattern) -> bool {
let mut node_vars: HashSet<&SmallName> = HashSet::new();
pattern
.nodes
.iter()
.filter_map(|n| n.variable.as_ref())
.all(|v| node_vars.insert(v))
}