use indexmap::IndexMap;
use relate_core::{Result, Value};
use relate_ir::{Clause, Expr, OrderItem, PathPattern, Projection};
use relate_names::SmallName;
use crate::ctx::ExecCtx;
use crate::group_key::{row_key, GroupKey};
use crate::overlay::{ExecGraph, RetainedTotal};
use crate::row::Row;
use super::classification::{ProjectionClass, ProjectionShape};
use super::order::park_order_keys;
use super::pattern_policies::node_occurrence_counts;
use super::project::{project_classed, return_result, ProjectionInput};
use super::scope::ProjectionFields;
use super::QueryResult;
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.is_unconstrained() {
Pop::Any
} else {
Pop::No
}
}
pub(super) fn plain_match_patterns(clause: &Clause) -> Option<&[PathPattern]> {
Some(clause.plain_match()?.patterns)
}
pub(super) fn plain_match_pattern(clause: &Clause) -> Option<&PathPattern> {
let [pattern] = plain_match_patterns(clause)? else {
return None;
};
if pattern.needs_gpm() {
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> {
Some(pattern.whole_population_node()?.variable)
}
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 fields = ProjectionFields {
items: &identity,
distinct: false,
group_by: None,
order: &page.order,
skip: page.skip,
limit: page.limit,
where_clause: None,
};
let class = ProjectionClass::new(ctx.graph, &fields, ProjectionShape::decide(&fields)?);
for row in &mut grouped {
park_order_keys(&class.order_keys, row, |expr, scope| {
crate::eval::eval(ctx.graph, scope, expr, ctx.params)
})?;
}
let mut rows = project_classed(
ctx,
&class,
ProjectionInput::SinkProjected(grouped),
true,
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 = row_key(&keys);
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: impl FnOnce() -> 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(());
}
let keys = keys();
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 count_value(count: u64) -> Value {
Value::Int(i64::try_from(count).expect("a group count past i64 is a broken store"))
}
pub(super) fn grouped_row(
names: &[String],
count_at: usize,
mut keys: Vec<Value>,
count: u64,
) -> Row {
keys.insert(count_at, count_value(count));
assert_eq!(
names.len(),
keys.len(),
"one count column and one per key item"
);
names.iter().cloned().zip(keys).collect()
}
pub(super) fn node_vars_unique(pattern: &PathPattern) -> bool {
node_occurrence_counts(pattern)
.values()
.all(|count| *count == 1)
}