use std::collections::HashSet;
use relate_core::{Error, Result};
use relate_names::SmallName;
use relate_front::agg::is_aggregate_name as is_agg_fn;
use relate_ir::{
is_agg_call, is_agg_expr, walk_scope_children, ChildScope, Expr, MapProjectionItem, OrderItem,
Projection, Query,
};
pub(crate) type Imports = std::collections::HashSet<String>;
fn explicit_keys_cover_star_scope(keys: &[Expr], outer_names: &crate::binding::Env) -> bool {
let names: Option<std::collections::HashSet<String>> = keys
.iter()
.map(|k| match k {
Expr::Variable(v) => Some(v.to_string()),
_ => None,
})
.collect();
!keys.is_empty()
&& names.is_some_and(|names| {
names.len() == outer_names.len() && outer_names.keys().all(|s| names.contains(s))
})
}
pub(crate) fn check_agg_projections(
items: &[Projection],
group_by: Option<&[Expr]>,
imports: &Imports,
outer_names: &crate::binding::Env,
) -> Result<()> {
if let Some(keys) = group_by {
let star_item = items.iter().any(|i| matches!(i.expr, Expr::Star));
if star_item && !keys.iter().any(|k| matches!(k, Expr::Star)) {
let covers_scope = items.iter().any(|i| is_agg_expr(&i.expr))
&& explicit_keys_cover_star_scope(keys, outer_names);
if !covers_scope {
return Err(Error::syntax(
"AmbiguousAggregationExpression: `*` projection is not allowed with an explicit GROUP BY",
));
}
}
}
if !items.iter().any(|i| is_agg_expr(&i.expr)) && group_by.is_none() {
return Ok(());
}
let group_keys = grouping_keys(items, group_by);
for item in items {
if !is_agg_expr(&item.expr)
&& (group_by.is_none()
|| contains_subquery_expression(&item.expr)
|| group_keys
.iter()
.any(|key| **key == item.expr || key_is_property_of(key, &item.expr)))
{
continue;
}
check_item_grouping(&item.expr, &group_keys, imports, outer_names)?;
}
Ok(())
}
fn contains_subquery_expression(expr: &Expr) -> bool {
expr.any(&mut |node| {
matches!(
node,
Expr::CountSubquery { .. } | Expr::CollectSubquery { .. } | Expr::ExistsSubquery { .. }
)
})
}
fn key_is_property_of(key: &Expr, item: &Expr) -> bool {
matches!(key, Expr::Property { expr, .. } if **expr == *item)
}
fn grouping_keys<'a>(items: &'a [Projection], group_by: Option<&'a [Expr]>) -> Vec<&'a Expr> {
match group_by {
Some(keys) => keys.iter().collect(),
None => items
.iter()
.filter(|i| !is_agg_expr(&i.expr))
.map(|i| &i.expr)
.collect(),
}
}
fn check_item_grouping(
expr: &Expr,
group_keys: &[&Expr],
imports: &Imports,
outer_names: &crate::binding::Env,
) -> Result<()> {
let mut leaves = Vec::new();
collect_non_agg_leaves(expr, false, &mut leaves);
let mut offending: Vec<String> = Vec::new();
let mut rejected = false;
for leaf in &leaves {
if !leaf_allowed_as_group(leaf, group_keys, imports) {
rejected = true;
push_offending_name(leaf, &mut offending);
}
}
if rejected {
return Err(non_grouping_ref(&offending));
}
check_nested_scope_refs(expr, group_keys, imports, outer_names)
}
fn push_offending_name(leaf: &Expr, out: &mut Vec<String>) {
let name = match leaf {
Expr::Variable(v) => Some(v.to_string()),
Expr::Property { expr, .. } => match expr.as_ref() {
Expr::Variable(v) => Some(v.to_string()),
_ => None,
},
_ => None,
};
if let Some(name) = name {
if !out.contains(&name) {
out.push(name);
}
}
}
fn non_grouping_ref(offending: &[String]) -> Error {
let named = match offending {
[] => String::new(),
[one] => format!(": the expression contains a non-grouping sub-expression `{one}`"),
[rest @ .., last] => format!(
": the expression contains non-grouping sub-expressions {} and `{last}`",
rest.iter()
.map(|name| format!("`{name}`"))
.collect::<Vec<_>>()
.join(", ")
),
};
Error::syntax(format!(
"AmbiguousAggregationExpression: non-aggregated expression must be a grouping key{named}"
))
}
pub(crate) fn check_post_projection_leaves(
items: &[Projection],
group_by: Option<&[Expr]>,
imports: &Imports,
outer_names: &crate::binding::Env,
expr: &Expr,
context: &str,
) -> Result<()> {
let group_keys = grouping_keys(items, group_by);
let output_names: Vec<String> = items
.iter()
.enumerate()
.map(|(i, item)| item.output_name(i))
.collect();
let mut leaves = Vec::new();
collect_nested_scope_leaves(expr, &mut Vec::new(), &mut leaves);
for leaf in &leaves {
if leaf_root_name(leaf)
.is_some_and(|name| !name.with_str(|text| outer_names.contains_key(text)))
{
continue;
}
if leaf_allowed_in_aggregating_scope(leaf, &group_keys, &output_names, imports) {
continue;
}
if group_by.is_none()
&& group_keys
.iter()
.filter(|key| !is_subquery_expression(key))
.any(|key| expr_contains_deep(key, leaf) && expr_contains_deep(expr, key))
{
continue;
}
return Err(Error::syntax(format!(
"UndefinedVariable: {context} refers to a non-projecting variable"
)));
}
Ok(())
}
fn is_subquery_expression(expr: &Expr) -> bool {
matches!(
expr,
Expr::CountSubquery { .. } | Expr::CollectSubquery { .. } | Expr::ExistsSubquery { .. }
)
}
fn expr_contains_deep(haystack: &Expr, needle: &Expr) -> bool {
let mut exprs: Vec<&Expr> = vec![haystack];
let mut queries: Vec<&Query> = Vec::new();
let mut seen_exprs: HashSet<*const Expr> = HashSet::new();
let mut seen_queries: HashSet<*const Query> = HashSet::new();
loop {
while let Some(expr) = exprs.pop() {
if expr == needle {
return true;
}
if !seen_exprs.insert(expr as *const Expr) {
continue;
}
expr.each_child(&mut |child| exprs.push(child));
if let Expr::CountSubquery { query }
| Expr::CollectSubquery { query }
| Expr::ExistsSubquery { query } = expr
{
queries.push(query);
}
}
let Some(query) = queries.pop() else {
return false;
};
if !seen_queries.insert(query as *const Query) {
continue;
}
relate_ir::walk_query(query, &mut |_| {}, &mut |expr| exprs.push(expr));
}
}
fn leaf_allowed_in_aggregating_scope(
leaf: &Expr,
group_keys: &[&Expr],
output_names: &[String],
imports: &Imports,
) -> bool {
if group_keys.iter().any(|key| **key == *leaf) {
return true;
}
let base_var = match leaf {
Expr::Variable(v) => v.clone(),
Expr::Property { expr, .. } => match expr.as_ref() {
Expr::Variable(v) => v.clone(),
_ => return false,
},
_ => return true,
};
group_keys
.iter()
.any(|key| matches!(key, Expr::Variable(k) if k == &base_var) || matches!(key, Expr::Star))
|| base_var.with_str(|text| output_names.iter().any(|name| name == text))
|| base_var.with_str(|text| imports.contains(text))
}
fn same_clause_ref(context: &str) -> Error {
Error::syntax(format!(
"InvalidAggregation: {context} cannot reference variables declared in the same clause"
))
}
fn check_nested_scope_refs(
item: &Expr,
group_keys: &[&Expr],
imports: &Imports,
outer_names: &crate::binding::Env,
) -> Result<()> {
let mut leaves = Vec::new();
collect_nested_scope_leaves(item, &mut Vec::new(), &mut leaves);
for leaf in &leaves {
let root = leaf_root_name(leaf);
if root.is_none_or(|name| name.with_str(|text| outer_names.contains_key(text)))
&& !leaf_allowed_as_group(leaf, group_keys, imports)
{
let mut offending = Vec::new();
push_offending_name(leaf, &mut offending);
return Err(non_grouping_ref(&offending));
}
}
Ok(())
}
fn leaf_root_name(leaf: &Expr) -> Option<&SmallName> {
match leaf {
Expr::Variable(v) => Some(v),
Expr::Property { expr, .. } => match expr.as_ref() {
Expr::Variable(v) => Some(v),
_ => None,
},
_ => None,
}
}
fn collect_nested_scope_leaves(expr: &Expr, bound: &mut Vec<SmallName>, out: &mut Vec<Expr>) {
if is_agg_call(expr) {
return;
}
fn read(name: &SmallName, bound: &[SmallName], out: &mut Vec<Expr>) {
if !bound.iter().any(|b| b == name) {
out.push(Expr::Variable(name.clone()));
}
}
match expr {
Expr::Variable(v) => {
read(v, bound, out);
return;
}
Expr::Property { expr: target, .. } => {
if let Expr::Variable(v) = target.as_ref() {
if !bound.iter().any(|b| b == v) {
out.push(expr.clone());
}
return;
}
}
Expr::PatternPred { path } | Expr::ShortestPath { path, .. } => {
for name in path.path_names().chain(relate_ir::path_pattern_vars(path)) {
read(name, bound, out);
}
return;
}
Expr::PatternComp {
path,
predicate,
projection,
} => {
let names: Vec<&SmallName> = path
.path_names()
.chain(relate_ir::path_pattern_vars(path))
.collect();
for name in names.iter().copied() {
read(name, bound, out);
}
let mark = bound.len();
bound.extend(names.into_iter().cloned());
if let Some(predicate) = predicate {
collect_nested_scope_leaves(predicate, bound, out);
}
collect_nested_scope_leaves(projection, bound, out);
bound.truncate(mark);
return;
}
Expr::ExistsSubquery { query }
| Expr::CountSubquery { query }
| Expr::CollectSubquery { query } => {
let mut names: Vec<&SmallName> = Vec::new();
relate_ir::walk_query(
query,
&mut |clause| {
let relate_ir::Clause::Match { patterns, .. } = clause else {
return;
};
for pattern in patterns {
names.extend(
pattern
.path_names()
.chain(relate_ir::path_pattern_vars(pattern)),
);
}
},
&mut |_| {},
);
relate_ir::walk_query(query, &mut |_| {}, &mut |e| {
if let Expr::Variable(v) = e {
names.push(v);
}
});
for name in names {
read(name, bound, out);
}
return;
}
_ => {}
}
walk_scope_children(expr, &mut |child, scope| match scope {
ChildScope::Enclosing => collect_nested_scope_leaves(child, bound, out),
ChildScope::Element(names) => {
let mark = bound.len();
bound.extend(names.iter().cloned());
collect_nested_scope_leaves(child, bound, out);
bound.truncate(mark);
}
});
}
fn collect_non_agg_leaves(expr: &Expr, inside_agg: bool, out: &mut Vec<Expr>) {
if matches!(expr, Expr::CountStar) {
return;
}
let inside_agg =
inside_agg || matches!(expr, Expr::Function { name, .. } if name.with_str(is_agg_fn));
if matches!(expr, Expr::Variable(_) | Expr::Property { .. }) && !inside_agg {
out.push(expr.clone());
return;
}
if expr.binds_identifiers() {
return;
}
if let Expr::MapProjection {
expr: target,
items,
} = expr
{
if !inside_agg {
for item in items {
match item {
MapProjectionItem::Variable { name } => {
out.push(Expr::Variable(name.clone()));
}
MapProjectionItem::Property { key } => {
out.push(Expr::property((**target).clone(), key.clone()));
}
MapProjectionItem::KeyValue { .. } | MapProjectionItem::AllProperties => {}
}
}
}
}
expr.each_child(&mut |child| collect_non_agg_leaves(child, inside_agg, out));
}
fn leaf_allowed_as_group(leaf: &Expr, group_keys: &[&Expr], imports: &Imports) -> bool {
if group_keys.contains(&leaf) {
return true;
}
if matches!(leaf, Expr::Variable(_)) && group_keys.iter().any(|g| matches!(g, Expr::Star)) {
return true;
}
if let Expr::Variable(v) = leaf {
if v.with_str(|text| imports.contains(text)) {
return true;
}
}
if let Expr::Property { expr, .. } = leaf {
if let Expr::Variable(v) = expr.as_ref() {
if v.with_str(|text| imports.contains(text)) {
return true;
}
return group_keys
.iter()
.any(|g| matches!(g, Expr::Variable(k) if k == v));
}
}
false
}
fn subexpr_contains(haystack: &Expr, needle: &Expr) -> bool {
haystack == needle || haystack.any(&mut |e| e == needle)
}
pub(crate) fn order_key_within_projection(expr: &Expr, items: &[Projection]) -> bool {
let mut leaves = Vec::new();
collect_non_agg_leaves(expr, false, &mut leaves);
leaves
.iter()
.all(|leaf| items.iter().any(|item| subexpr_contains(&item.expr, leaf)))
}
pub(crate) fn reject_agg_in_pred(expr: &Expr) -> Result<()> {
if is_agg_expr(expr) {
return Err(Error::syntax(
"InvalidAggregation: aggregations are not allowed in WHERE",
));
}
Ok(())
}
pub(crate) fn projection_aggregates(
items: &[Projection],
group_by: Option<&[Expr]>,
distinct: bool,
) -> bool {
items.iter().any(|i| is_agg_expr(&i.expr)) || group_by.is_some() || distinct
}
pub(crate) fn check_subclause_agg_leaves(
items: &[Projection],
group_by: Option<&[Expr]>,
imports: &Imports,
expr: &Expr,
context: &str,
) -> Result<()> {
let group_keys = grouping_keys(items, group_by);
let output_names: Vec<String> = items
.iter()
.enumerate()
.map(|(i, item)| item.output_name(i))
.collect();
let reintroduced: Vec<String> = items
.iter()
.enumerate()
.filter(|(_, item)| {
!is_agg_expr(&item.expr) && !item.expr.any(&mut |e| matches!(e, Expr::Variable(_)))
})
.map(|(i, item)| item.output_name(i))
.collect();
let mut leaves = Vec::new();
collect_non_agg_leaves(expr, false, &mut leaves);
for leaf in &leaves {
if matches!(leaf, Expr::Variable(v) if v.with_str(|t| reintroduced.iter().any(|r| r == t)))
{
return Err(same_clause_ref(context));
}
if !leaf_allowed_as_group(leaf, &group_keys, imports)
&& !matches!(leaf, Expr::Variable(v)
if v.with_str(|t| output_names.iter().any(|n| n == t)))
&& !items
.iter()
.any(|item| subexpr_contains(&item.expr, leaf) && subexpr_contains(expr, &item.expr))
{
return Err(Error::syntax(format!(
"UndefinedVariable: {context} refers to a non-projected expression"
)));
}
}
check_same_clause_refs(items, expr, &reintroduced, context)?;
Ok(())
}
pub(crate) fn is_projected_item(items: &[Projection], expr: &Expr) -> bool {
items.iter().any(|item| item.expr == *expr)
}
fn check_same_clause_refs(
items: &[Projection],
expr: &Expr,
reintroduced: &[String],
context: &str,
) -> Result<()> {
if is_projected_item(items, expr) {
return Ok(());
}
let mut calls = Vec::new();
expr.visit(&mut |e| {
if matches!(e, Expr::CountStar)
|| matches!(e, Expr::Function { name, .. } if name.with_str(is_agg_fn))
{
calls.push(e.clone());
}
});
for call in calls {
let mut vars = Vec::new();
call.visit(&mut |e| {
if let Expr::Variable(v) = e {
vars.push(v.clone());
}
});
if vars
.iter()
.any(|v| v.with_str(|t| reintroduced.iter().any(|r| r == t)))
{
return Err(same_clause_ref(context));
}
}
Ok(())
}
pub(crate) fn reject_order_by_agg(
items: &[Projection],
group_by: Option<&[Expr]>,
distinct: bool,
imports: &Imports,
order: &[OrderItem],
) -> Result<()> {
let order_has_agg = order.iter().any(|o| is_agg_expr(&o.expr));
if order_has_agg && !projection_aggregates(items, group_by, distinct) {
return Err(Error::syntax(
"InvalidAggregation: aggregation functions are not allowed in ORDER BY when clause has no aggregation",
));
}
for o in order {
if !is_agg_expr(&o.expr) {
continue;
}
reject_shadowed_aggregate_argument(items, &o.expr)?;
check_subclause_agg_leaves(items, group_by, imports, &o.expr, "ORDER BY aggregation")?;
}
Ok(())
}
fn reject_shadowed_aggregate_argument(items: &[Projection], expr: &Expr) -> Result<()> {
if is_projected_item(items, expr) {
return Ok(());
}
let aggregate_aliases: Vec<String> = items
.iter()
.enumerate()
.filter(|(_, item)| is_agg_expr(&item.expr))
.map(|(index, item)| item.output_name(index))
.collect();
if aggregate_aliases.is_empty() {
return Ok(());
}
let mut calls = Vec::new();
expr.visit(&mut |e| {
if matches!(e, Expr::CountStar)
|| matches!(e, Expr::Function { name, .. } if name.with_str(is_agg_fn))
{
calls.push(e.clone());
}
});
for call in calls {
let mut shadowed = false;
call.visit(&mut |e| {
if let Expr::Variable(v) = e {
shadowed |= v.with_str(|t| aggregate_aliases.iter().any(|a| a == t));
}
});
if shadowed {
return Err(Error::syntax(
"InvalidAggregation: ORDER BY aggregation references an aggregate \
projected in the same clause",
));
}
}
Ok(())
}
#[cfg(test)]
mod tests;